context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) 2015-2021, Saritasa. All rights reserved. // Licensed under the BSD license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using Xunit; using Saritasa.Tools.Common.Utils; namespace Saritasa.Tools.Common.Tests { /// <summary> /// Collection utils. /// </summary> public class CollectionTests { [DebuggerDisplay("{Id}, {Name}")] private sealed class User { public int Id { get; } public string Name { get; internal set; } public User(int id, string name) { this.Id = id; this.Name = name; } } private sealed class UserIdentityEqualityComparer : IEqualityComparer<User> { public bool Equals(User x, User y) => x.Id == y.Id; public int GetHashCode(User obj) => obj.Id.GetHashCode(); } private sealed class UserEqualityComparer : IEqualityComparer<User> { public bool Equals(User x, User y) => y != null && x != null && x.Id == y.Id && x.Name == y.Name; public int GetHashCode(User obj) => obj.Id.GetHashCode() ^ obj.Name.GetHashCode(); } [Fact] public void Diff_TargetCollectionWithNewElements_NewElementsAreAdded() { // Arrange var source = new[] { 1, 2, 3 }; var target = new[] { 1, 2, 4 }; // Act var diff = CollectionUtils.Diff(source, target); var diffEq = CollectionUtils.Diff(source, target, EqualityComparer<int>.Default); // Assert Assert.Equal(new[] { 4 }, diff.Added); Assert.Equal(new[] { 4 }, diffEq.Added); } [Fact] public void Diff_TargetCollectionWithoutOldElements_OldElementsAreRemoved() { // Arrange var source = new[] { 1, 2, 3 }; var target = new[] { 1, 4 }; // Act var diff = CollectionUtils.Diff(source, target); var diffEq = CollectionUtils.Diff(source, target, EqualityComparer<int>.Default); // Assert Assert.Equal(new[] { 2, 3 }, diff.Removed); Assert.Equal(new[] { 2, 3 }, diffEq.Removed); } [Fact] public void Diff_TargetCollectionWithExistingElements_ExistingElementsAreUpdated() { // Arrange var doug = new User(1, "Doug"); var source = new[] { doug, new User(2, "Pasha") }; var target = new[] { doug, new User(2, "Pavel") }; // Act var diff = CollectionUtils.Diff(source, target, (u1, u2) => u1.Id == u2.Id); var diffEq = CollectionUtils.Diff(source, target, new UserIdentityEqualityComparer()); // Assert Assert.Equal(new[] { new DiffResultUpdatedItems<User>(source[1], target[1]) }, diff.Updated); Assert.Equal(new[] { new DiffResultUpdatedItems<User>(source[1], target[1]) }, diffEq.Updated); } [Fact] public void Diff_TargetCollectionWithUpdatedElementsAndComparer_NotUpdatedElementsSkipped() { // Arrange var source = new User[] { new(1, "Doug"), new(2, "Pasha") }; var target = new User[] { new(1, "Doug"), new(2, "Pavel") }; // Act var diff = CollectionUtils.Diff(source, target, (u1, u2) => u1.Id == u2.Id, (u1, u2) => u2 != null && (u1 != null && (u1.Id == u2.Id && u1.Name == u2.Name))); var diffEq = CollectionUtils.Diff(source, target, new UserIdentityEqualityComparer(), (u1, u2) => u2 != null && (u1 != null && (u1.Id == u2.Id && u1.Name == u2.Name))); // Assert Assert.Equal(new[] { new DiffResultUpdatedItems<User>(source[1], target[1]) }, diff.Updated); Assert.Equal(new[] { new DiffResultUpdatedItems<User>(source[1], target[1]) }, diffEq.Updated); } [Fact] public void Diff_TargetCollectionWithElements_ElementsWereAddedRemovedUpdated() { // Arrange var source = new List<User> { new(1, "Ivan"), new(2, "Roma"), new(3, "Vlad"), new(4, "Denis"), new(5, "Nastya"), new(6, "Marina"), new(7, "Varvara"), }; var target = new List<User> { new(1, "Ivan"), new(2, "Roman"), new(5, "Anastasya"), new(6, "Marina"), new(7, "Varvara"), new(0, "Tamara"), new(0, "Pavel"), }; // Act var diff = CollectionUtils.Diff(source, target, (u1, u2) => u1.Id == u2.Id); var diffEq = CollectionUtils.Diff(source, target, new UserIdentityEqualityComparer()); // Assert Assert.Equal(2, diff.Added.Count); Assert.Equal(5, diff.Updated.Count); Assert.Equal(2, diff.Removed.Count); Assert.Equal(2, diffEq.Added.Count); Assert.Equal(5, diffEq.Updated.Count); Assert.Equal(2, diffEq.Removed.Count); } [Fact] public void ApplyDiff_TargetCollectionWithElements_AfterApplyCollectionsAreEqual() { // Arrange var source = new List<User> { new(1, "Ivan"), new(2, "Roma"), new(3, "Vlad"), new(4, "Denis"), new(5, "Nastya"), new(6, "Marina"), new(7, "Varvara"), }; var target = new List<User> { new(1, "Ivan"), new(2, "Roman"), new(5, "Anastasya"), new(6, "Marina"), new(7, "Varvara"), new(0, "Tamara"), new(0, "Pavel"), }; // Act var diff = CollectionUtils.Diff(source, target, (u1, u2) => u1.Id == u2.Id); CollectionUtils.ApplyDiff(source, diff, (source, target) => { source.Name = target.Name; }); // Assert Assert.Equal(target.OrderBy(u => u.Id), source.OrderBy(u => u.Id), new UserEqualityComparer()); } [Fact] public void ApplyDiffEqComparer_TargetCollectionWithElements_AfterApplyCollectionsAreEqual() { // Arrange var source = new List<User> { new(1, "Ivan"), new(2, "Roma"), new(3, "Vlad"), new(4, "Denis"), new(5, "Nastya"), new(6, "Marina"), new(7, "Varvara"), }; var target = new List<User> { new(1, "Ivan"), new(2, "Roman"), new(5, "Anastasya"), new(6, "Marina"), new(7, "Varvara"), new(0, "Tamara"), new(0, "Pavel"), }; // Act var diff = CollectionUtils.Diff(source, target, new UserIdentityEqualityComparer()); CollectionUtils.ApplyDiff(source, diff, (source, target) => { source.Name = target.Name; }); // Assert Assert.Equal(target.OrderBy(u => u.Id), source.OrderBy(u => u.Id), new UserEqualityComparer()); } [Fact] public void OrderParsingDelegates_QueryString_CollectionOfSortEntries() { // Arrange var query = "id:asc,name:desc;year salary;year:desc"; // Act var sortingEntries = OrderParsingDelegates.ParseSeparated(query); // Assert var expected = new[] { ("id", ListSortDirection.Ascending), ("name", ListSortDirection.Descending), ("year salary", ListSortDirection.Ascending), ("year", ListSortDirection.Descending) }; Assert.Equal(expected, sortingEntries); } [Fact] public void OrderMultiple_NotOrderedQueryableCollectionOfUsers_OrderedCollection() { // Arrange var source = new List<User> { new(1, "A"), new(4, "B"), new(4, "Z"), new(2, "D") }; // Act var target = CollectionUtils.OrderMultiple( source.AsQueryable(), OrderParsingDelegates.ParseSeparated("id:asc;name:desc"), ("id", u => u.Id), ("name", u => u.Name) ); // Assert var expected = new List<User> { new(1, "A"), new(2, "D"), new(4, "Z"), new(4, "B") }; Assert.Equal(expected, target, new UserEqualityComparer()); } [Fact] public void OrderMultiple_NotOrderedListOfUsers_OrderedCollection() { // Arrange var source = new List<User> { new(1, "A"), new(4, "B"), new(4, "Z"), new(2, "D") }; // Act var target = CollectionUtils.OrderMultiple( source, OrderParsingDelegates.ParseSeparated("id:asc;name:desc"), ("id", u => u.Id), ("name", u => u.Name) ); // Assert var expected = new List<User> { new(1, "A"), new(2, "D"), new(4, "Z"), new(4, "B") }; Assert.Equal(expected, target, new UserEqualityComparer()); } [Fact] public void OrderMultiple_EmptyOrderList_ReturnsSourceCollection() { // Arrange var source = new List<User> { new(2, "B"), new(1, "A") }; // Act var target = CollectionUtils.OrderMultiple( source, OrderParsingDelegates.ParseSeparated(string.Empty), ("id", u => u.Id) ); // Assert var expected = new List<User> { new(2, "B"), new(1, "A") }; Assert.Equal(expected, target, new UserEqualityComparer()); } [Fact] public void OrderMultiple_SelectorWithDoubleKey_OrderWithOrderThen() { // Arrange var source = new List<User> { new(1, "B"), new(1, "A"), new(2, "C"), }; // Act var target = CollectionUtils.OrderMultiple( source, OrderParsingDelegates.ParseSeparated("key:asc"), ("key", u => u.Id), ("key", u => u.Name) ); // Assert var expected = new List<User> { new(1, "A"), new(1, "B"), new(2, "C"), }; Assert.Equal(expected, target, new UserEqualityComparer()); } [Fact] public void OrderMultiple_OrderByNotExistingKey_InvalidOrderFieldException() { // Arrange var source = new List<User> { new(1, "B"), }; // Assert Assert.Throws<InvalidOrderFieldException>(() => { var target = CollectionUtils.OrderMultiple( source, OrderParsingDelegates.ParseSeparated("date:asc"), ("id", u => u.Id), ("name", u => u.Name) ); }); } [Fact] public void OrderMultiple_OrderWithCamelCaseKey_KeysMatchShouldBeCaseInsensitive() { // Arrange var source = new List<User> { new(1, "B"), new(2, "A") }; // Act var target = CollectionUtils.OrderMultiple( source, OrderParsingDelegates.ParseSeparated("name:asc"), ("Name", u => u.Name) ); // Assert var expected = new List<User> { new User(2, "A"), new User(1, "B") }; Assert.Equal(expected, target, new UserEqualityComparer()); } [Fact] public void ChunkSelectRange_ListWithItems_ShouldIterateWholeList() { // Arrange int capacity = 250; int sum = 0; IList<int> list = new List<int>(capacity); for (int i = 0; i < capacity; i++) { list.Add(i); } // Act foreach (var sublist in CollectionUtils.ChunkSelectRange(list.AsQueryable(), 45)) { foreach (var item in sublist) { sum += item; } } // Assert Assert.Equal(31125, sum); } [Fact] public void ChunkSelect_ListWithItems_ShouldIterateWholeList() { // Arrange int capacity = 250; int sum = 0; IList<int> list = new List<int>(capacity); for (int i = 0; i < capacity; i++) { list.Add(i); } // Act foreach (var item in CollectionUtils.ChunkSelect(list.AsQueryable(), 45)) { sum += item; } // Assert Assert.Equal(31125, sum); } [Fact] public async System.Threading.Tasks.Task ChunkSelectAsync_EnumerableWithItems_ShouldIterateWholeList() { // Arrange static async IAsyncEnumerable<int> GetInts() { for (int i = 0; i < 250; i++) { yield return i; } await System.Threading.Tasks.Task.CompletedTask; } int sum = 0; // Act await foreach (var subitems in CollectionUtils.ChunkSelectRangeAsync(GetInts(), 250)) { await foreach (var item in subitems) { sum += item; } } // Assert Assert.Equal(31125, sum); } [Fact] public async System.Threading.Tasks.Task ChunkSelectAsync_EnumerableWithItems_ShouldSkipItems() { // Arrange static async IAsyncEnumerable<int> GetInts() { for (int i = 0; i < 250; i++) { yield return i; } await System.Threading.Tasks.Task.CompletedTask; } int iterations = 0; // Act await foreach (var subitems in CollectionUtils.ChunkSelectRangeAsync(GetInts(), 25, 25)) { iterations++; await foreach (var item in subitems) { } } // Assert Assert.Equal(9, iterations); } [Fact] public void Pairwise_List_ShouldCreateCorrectly() { // Arrange var collection = new int[] { 1, 2, 3, 4, }; // Act var pairwisedCollection = CollectionUtils.Pairwise(collection).ToList(); // Assert var expected = new List<(int, int)> { (1, 2), (2, 3), (3, 4) }; Assert.Equal(expected, pairwisedCollection); } [Fact] public void Pairwise_List_EmptyIfOneElement() { // Arrange var collection = new int[] { 1, }; // Act var pairwisedCollection = CollectionUtils.Pairwise(collection).ToList(); // Assert Assert.Empty(pairwisedCollection); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Navigation; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text.Differencing; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane { internal partial class PreviewPane : UserControl, IDisposable { private static readonly string s_dummyThreeLineTitle = "A" + Environment.NewLine + "A" + Environment.NewLine + "A"; private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity); private readonly string _id; private readonly bool _logIdVerbatimInTelemetry; private bool _isExpanded; private double _heightForThreeLineTitle; private IWpfDifferenceViewer _previewDiffViewer; public PreviewPane(Image severityIcon, string id, string title, string description, Uri helpLink, string helpLinkToolTipText, IList<object> previewContent, bool logIdVerbatimInTelemetry) { InitializeComponent(); _id = id; _logIdVerbatimInTelemetry = logIdVerbatimInTelemetry; // Initialize header portion. if ((severityIcon != null) && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(title)) { HeaderStackPanel.Visibility = Visibility.Visible; SeverityIconBorder.Child = severityIcon; // Set the initial title text to three lines worth so that we can measure the pixel height // that WPF requires to render three lines of text under the current font and DPI settings. TitleRun.Text = s_dummyThreeLineTitle; TitleTextBlock.Measure(availableSize: s_infiniteSize); _heightForThreeLineTitle = TitleTextBlock.DesiredSize.Height; // Now set the actual title text. TitleRun.Text = title; InitializeHyperlinks(helpLink, helpLinkToolTipText); if (!string.IsNullOrWhiteSpace(description)) { DescriptionParagraph.Inlines.Add(description); } } // Initialize preview (i.e. diff view) portion. InitializePreviewElement(previewContent); } private void InitializePreviewElement(IList<object> previewItems) { var previewElement = CreatePreviewElement(previewItems); if (previewElement != null) { HeaderSeparator.Visibility = Visibility.Visible; PreviewDockPanel.Visibility = Visibility.Visible; PreviewScrollViewer.Content = previewElement; previewElement.VerticalAlignment = VerticalAlignment.Top; previewElement.HorizontalAlignment = HorizontalAlignment.Left; } // 1. Width of the header section should not exceed the width of the preview content. // In other words, the text we put in the header at the top of the preview pane // should not cause the preview pane itself to grow wider than the width required to // display the preview content at the bottom of the pane. // 2. Adjust the height of the header section so that it displays only three lines worth // by default. AdjustWidthAndHeight(previewElement); } private FrameworkElement CreatePreviewElement(IList<object> previewItems) { if (previewItems == null || previewItems.Count == 0) { return null; } const int MaxItems = 3; if (previewItems.Count > MaxItems) { previewItems = previewItems.Take(MaxItems).Concat("...").ToList(); } var grid = new Grid(); for (var i = 0; i < previewItems.Count; i++) { var previewItem = previewItems[i]; FrameworkElement previewElement = null; if (previewItem is IWpfDifferenceViewer) { _previewDiffViewer = (IWpfDifferenceViewer)previewItem; previewElement = _previewDiffViewer.VisualElement; PreviewDockPanel.Background = _previewDiffViewer.InlineView.Background; } else if (previewItem is string) { previewElement = GetPreviewForString((string)previewItem, createBorder: previewItems.Count == 0); } else if (previewItem is FrameworkElement) { previewElement = (FrameworkElement)previewItem; } var rowDefinition = i == 0 ? new RowDefinition() : new RowDefinition() { Height = GridLength.Auto }; grid.RowDefinitions.Add(rowDefinition); Grid.SetRow(previewElement, grid.RowDefinitions.IndexOf(rowDefinition)); grid.Children.Add(previewElement); if (i == 0) { grid.Width = previewElement.Width; } } var preview = grid.Children.Count == 0 ? (FrameworkElement)grid.Children[0] : grid; return preview; } private void InitializeHyperlinks(Uri helpLink, string helpLinkToolTipText) { IdHyperlink.SetVSHyperLinkStyle(); LearnMoreHyperlink.SetVSHyperLinkStyle(); IdHyperlink.Inlines.Add(_id); IdHyperlink.NavigateUri = helpLink; IdHyperlink.IsEnabled = true; IdHyperlink.ToolTip = helpLinkToolTipText; LearnMoreHyperlink.Inlines.Add(string.Format(ServicesVSResources.LearnMoreLinkText, _id)); LearnMoreHyperlink.NavigateUri = helpLink; LearnMoreHyperlink.ToolTip = helpLinkToolTipText; } public static FrameworkElement GetPreviewForString(string previewContent, bool useItalicFontStyle = false, bool centerAlignTextHorizontally = false, bool createBorder = false) { var textBlock = new TextBlock() { Margin = new Thickness(5), VerticalAlignment = VerticalAlignment.Center, Text = previewContent, TextWrapping = TextWrapping.Wrap, }; if (useItalicFontStyle) { textBlock.FontStyle = FontStyles.Italic; } if (centerAlignTextHorizontally) { textBlock.TextAlignment = TextAlignment.Center; } FrameworkElement preview = textBlock; if (createBorder) { preview = new Border() { Width = 400, MinHeight = 75, Child = textBlock }; } return preview; } // This method adjusts the width of the header section to match that of the preview content // thereby ensuring that the preview pane itself is never wider than the preview content. // This method also adjusts the height of the header section so that it displays only three lines // worth by default. private void AdjustWidthAndHeight(FrameworkElement previewElement) { var headerStackPanelWidth = double.PositiveInfinity; var titleTextBlockHeight = double.PositiveInfinity; if (previewElement == null) { HeaderStackPanel.Measure(availableSize: s_infiniteSize); headerStackPanelWidth = HeaderStackPanel.DesiredSize.Width; TitleTextBlock.Measure(availableSize: s_infiniteSize); titleTextBlockHeight = TitleTextBlock.DesiredSize.Height; } else { PreviewDockPanel.Measure(availableSize: new Size(previewElement.Width, double.PositiveInfinity)); headerStackPanelWidth = PreviewDockPanel.DesiredSize.Width; if (IsNormal(headerStackPanelWidth)) { TitleTextBlock.Measure(availableSize: new Size(headerStackPanelWidth, double.PositiveInfinity)); titleTextBlockHeight = TitleTextBlock.DesiredSize.Height; } } if (IsNormal(headerStackPanelWidth)) { HeaderStackPanel.Width = headerStackPanelWidth; } // If the pixel height required to render the complete title in the // TextBlock is larger than that required to render three lines worth, // then trim the contents of the TextBlock with an ellipsis at the end and // display the expander button that will allow users to view the full text. if (HasDescription || (IsNormal(titleTextBlockHeight) && (titleTextBlockHeight > _heightForThreeLineTitle))) { TitleTextBlock.MaxHeight = _heightForThreeLineTitle; TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis; ExpanderToggleButton.Visibility = Visibility.Visible; if (_isExpanded) { ExpanderToggleButton.IsChecked = true; } } } private static bool IsNormal(double size) { return size > 0 && !double.IsNaN(size) && !double.IsInfinity(size); } private bool HasDescription { get { return DescriptionParagraph.Inlines.Count > 0; } } #region IDisposable Implementation private bool _disposedValue = false; // VS editor will call Dispose at which point we should Close() the embedded IWpfDifferenceViewer. protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing && (_previewDiffViewer != null) && !_previewDiffViewer.IsClosed) { _previewDiffViewer.Close(); } } _disposedValue = true; } void IDisposable.Dispose() { Dispose(true); } #endregion private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { if (e.Uri == null) { return; } BrowserHelper.StartBrowser(e.Uri); e.Handled = true; var hyperlink = sender as Hyperlink; if (hyperlink == null) { return; } DiagnosticLogger.LogHyperlink(hyperlink.Name ?? "Preview", _id, HasDescription, _logIdVerbatimInTelemetry, e.Uri.AbsoluteUri); } private void ExpanderToggleButton_CheckedChanged(object sender, RoutedEventArgs e) { if (ExpanderToggleButton.IsChecked ?? false) { TitleTextBlock.MaxHeight = double.PositiveInfinity; TitleTextBlock.TextTrimming = TextTrimming.None; if (HasDescription) { DescriptionDockPanel.Visibility = Visibility.Visible; if (LearnMoreHyperlink.NavigateUri != null) { LearnMoreTextBlock.Visibility = Visibility.Visible; LearnMoreHyperlink.IsEnabled = true; } } _isExpanded = true; } else { TitleTextBlock.MaxHeight = _heightForThreeLineTitle; TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis; DescriptionDockPanel.Visibility = Visibility.Collapsed; _isExpanded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace System.Linq.Expressions.Tests { public interface I { void M(); } public class C : IEquatable<C>, I { void I.M() { } public override bool Equals(object o) { return o is C && Equals((C)o); } public bool Equals(C c) { return c != null; } public override int GetHashCode() { return 0; } } public class D : C, IEquatable<D> { public int Val; public string S; public D() { } public D(int val) : this(val, "") { } public D(int val, string s) { Val = val; S = s; } public override bool Equals(object o) { return o is D && Equals((D)o); } public bool Equals(D d) { return d != null && d.Val == Val; } public override int GetHashCode() { return Val; } } public enum E { A = 1, B = 2, Red = 0, Green, Blue } public enum El : long { A, B, C } public struct S : IEquatable<S> { public override bool Equals(object o) { return (o is S) && Equals((S)o); } public bool Equals(S other) { return true; } public override int GetHashCode() { return 0; } } public struct Sp : IEquatable<Sp> { public Sp(int i, double d) { I = i; D = d; } public int I; public double D; public override bool Equals(object o) { return (o is Sp) && Equals((Sp)o); } public bool Equals(Sp other) { return other.I == I && other.D.Equals(D); } public override int GetHashCode() { return I.GetHashCode() ^ D.GetHashCode(); } } public struct Ss : IEquatable<Ss> { public Ss(S s) { Val = s; } public S Val; public override bool Equals(object o) { return (o is Ss) && Equals((Ss)o); } public bool Equals(Ss other) { return other.Val.Equals(Val); } public override int GetHashCode() { return Val.GetHashCode(); } } public struct Sc : IEquatable<Sc> { public Sc(string s) { S = s; } public string S; public override bool Equals(object o) { return (o is Sc) && Equals((Sc)o); } public bool Equals(Sc other) { return other.S == S; } public override int GetHashCode() { return S.GetHashCode(); } } public struct Scs : IEquatable<Scs> { public Scs(string s, S val) { S = s; Val = val; } public string S; public S Val; public override bool Equals(object o) { return (o is Scs) && Equals((Scs)o); } public bool Equals(Scs other) { return other.S == S && other.Val.Equals(Val); } public override int GetHashCode() { return S.GetHashCode() ^ Val.GetHashCode(); } } public class BaseClass { } public class FC { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public struct FS { public int II; public static int SI; public const int CI = 42; public static readonly int RI = 42; } public class PC { public int II { get; set; } public static int SI { get; set; } public int this[int i] { get { return 1; } set { } } } public struct PS { public int II { get; set; } public static int SI { get; set; } } internal class CompilationTypes : IEnumerable<object[]> { private static readonly object[] False = new object[] { false }; private static readonly object[] True = new object[] { true }; public IEnumerator<object[]> GetEnumerator() { yield return False; yield return True; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// // 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.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories.Models { /// <summary> /// The properties for the HDInsight linkedService. /// </summary> public partial class HDInsightOnDemandLinkedService : LinkedServiceProperties { private IList<string> _additionalLinkedServiceNames; /// <summary> /// Optional. Specify additional Azure storage accounts that need to be /// accessible from the cluster. /// </summary> public IList<string> AdditionalLinkedServiceNames { get { return this._additionalLinkedServiceNames; } set { this._additionalLinkedServiceNames = value; } } private int _clusterSize; /// <summary> /// Required. HDInsight cluster size. /// </summary> public int ClusterSize { get { return this._clusterSize; } set { this._clusterSize = value; } } private string _clusterType; /// <summary> /// Optional. Gets or sets the flavor for the HDInsight cluster. /// </summary> public string ClusterType { get { return this._clusterType; } set { this._clusterType = value; } } private IDictionary<string, string> _coreConfiguration; /// <summary> /// Optional. Allows user to override default values for core /// configuration. /// </summary> public IDictionary<string, string> CoreConfiguration { get { return this._coreConfiguration; } set { this._coreConfiguration = value; } } private string _dataNodeSize; /// <summary> /// Optional. Gets or sets the size of the Data Node. /// </summary> public string DataNodeSize { get { return this._dataNodeSize; } set { this._dataNodeSize = value; } } private IDictionary<string, string> _hBaseConfiguration; /// <summary> /// Optional. Allows user to override default values for HBase /// configuration. /// </summary> public IDictionary<string, string> HBaseConfiguration { get { return this._hBaseConfiguration; } set { this._hBaseConfiguration = value; } } private HCatalogProperties _hcatalog; /// <summary> /// Optional. Hcatalog integration properties. /// </summary> public HCatalogProperties Hcatalog { get { return this._hcatalog; } set { this._hcatalog = value; } } private IDictionary<string, string> _hdfsConfiguration; /// <summary> /// Optional. Allows user to override default values for Hdfs /// configuration. /// </summary> public IDictionary<string, string> HdfsConfiguration { get { return this._hdfsConfiguration; } set { this._hdfsConfiguration = value; } } private string _headNodeSize; /// <summary> /// Optional. Gets or sets the size of the Head Node. /// </summary> public string HeadNodeSize { get { return this._headNodeSize; } set { this._headNodeSize = value; } } private IDictionary<string, string> _hiveConfiguration; /// <summary> /// Optional. Allows user to override default values for HIVE /// configuration. /// </summary> public IDictionary<string, string> HiveConfiguration { get { return this._hiveConfiguration; } set { this._hiveConfiguration = value; } } private string _hiveCustomLibrariesContainer; /// <summary> /// Optional. The name of the blob container that contains custom jar /// files for HIVE consumption. /// </summary> public string HiveCustomLibrariesContainer { get { return this._hiveCustomLibrariesContainer; } set { this._hiveCustomLibrariesContainer = value; } } private string _linkedServiceName; /// <summary> /// Required. Storage service name. /// </summary> public string LinkedServiceName { get { return this._linkedServiceName; } set { this._linkedServiceName = value; } } private IDictionary<string, string> _mapReduceConfiguration; /// <summary> /// Optional. Allows user to override default values for mapreduce /// configuration. /// </summary> public IDictionary<string, string> MapReduceConfiguration { get { return this._mapReduceConfiguration; } set { this._mapReduceConfiguration = value; } } private IDictionary<string, string> _oozieConfiguration; /// <summary> /// Optional. Allows user to override default values for oozie /// configuration. /// </summary> public IDictionary<string, string> OozieConfiguration { get { return this._oozieConfiguration; } set { this._oozieConfiguration = value; } } private string _oSType; /// <summary> /// Optional. Gets or sets the type of operating system installed on /// cluster nodes. /// </summary> public string OSType { get { return this._oSType; } set { this._oSType = value; } } private IDictionary<string, string> _sparkConfiguration; /// <summary> /// Optional. The Spark service configuration of this HDInsight cluster. /// </summary> public IDictionary<string, string> SparkConfiguration { get { return this._sparkConfiguration; } set { this._sparkConfiguration = value; } } private string _sshPassword; /// <summary> /// Optional. Gets or sets SSH password. /// </summary> public string SshPassword { get { return this._sshPassword; } set { this._sshPassword = value; } } private string _sshPublicKey; /// <summary> /// Optional. Gets or sets the public key to be used for SSH. /// </summary> public string SshPublicKey { get { return this._sshPublicKey; } set { this._sshPublicKey = value; } } private string _sshUserName; /// <summary> /// Optional. Gets or sets SSH user name. /// </summary> public string SshUserName { get { return this._sshUserName; } set { this._sshUserName = value; } } private IDictionary<string, string> _stormConfiguration; /// <summary> /// Optional. Allows user to override default values for Storm /// configuration. /// </summary> public IDictionary<string, string> StormConfiguration { get { return this._stormConfiguration; } set { this._stormConfiguration = value; } } private TimeSpan _timeToLive; /// <summary> /// Required. Time to live. /// </summary> public TimeSpan TimeToLive { get { return this._timeToLive; } set { this._timeToLive = value; } } private string _version; /// <summary> /// Optional. HDInsight version. /// </summary> public string Version { get { return this._version; } set { this._version = value; } } private IDictionary<string, string> _yarnConfiguration; /// <summary> /// Optional. Allows user to override default values for YARN /// configuration. /// </summary> public IDictionary<string, string> YarnConfiguration { get { return this._yarnConfiguration; } set { this._yarnConfiguration = value; } } private string _zookeeperNodeSize; /// <summary> /// Optional. Gets or sets the size of the Zookeeper Node. /// </summary> public string ZookeeperNodeSize { get { return this._zookeeperNodeSize; } set { this._zookeeperNodeSize = value; } } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class. /// </summary> public HDInsightOnDemandLinkedService() { this.AdditionalLinkedServiceNames = new LazyList<string>(); this.CoreConfiguration = new LazyDictionary<string, string>(); this.HBaseConfiguration = new LazyDictionary<string, string>(); this.HdfsConfiguration = new LazyDictionary<string, string>(); this.HiveConfiguration = new LazyDictionary<string, string>(); this.MapReduceConfiguration = new LazyDictionary<string, string>(); this.OozieConfiguration = new LazyDictionary<string, string>(); this.SparkConfiguration = new LazyDictionary<string, string>(); this.StormConfiguration = new LazyDictionary<string, string>(); this.YarnConfiguration = new LazyDictionary<string, string>(); } /// <summary> /// Initializes a new instance of the HDInsightOnDemandLinkedService /// class with required arguments. /// </summary> public HDInsightOnDemandLinkedService(int clusterSize, TimeSpan timeToLive, string linkedServiceName) : this() { if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } this.ClusterSize = clusterSize; this.TimeToLive = timeToLive; this.LinkedServiceName = linkedServiceName; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Linq; using System.Runtime.CompilerServices; using Avalonia.Collections; using Avalonia.Controls.Utils; using Avalonia.VisualTree; using JetBrains.Annotations; namespace Avalonia.Controls { /// <summary> /// Lays out child controls according to a grid. /// </summary> public class Grid : Panel { /// <summary> /// Defines the Column attached property. /// </summary> public static readonly AttachedProperty<int> ColumnProperty = AvaloniaProperty.RegisterAttached<Grid, Control, int>( "Column", validate: ValidateColumn); /// <summary> /// Defines the ColumnSpan attached property. /// </summary> public static readonly AttachedProperty<int> ColumnSpanProperty = AvaloniaProperty.RegisterAttached<Grid, Control, int>("ColumnSpan", 1); /// <summary> /// Defines the Row attached property. /// </summary> public static readonly AttachedProperty<int> RowProperty = AvaloniaProperty.RegisterAttached<Grid, Control, int>( "Row", validate: ValidateRow); /// <summary> /// Defines the RowSpan attached property. /// </summary> public static readonly AttachedProperty<int> RowSpanProperty = AvaloniaProperty.RegisterAttached<Grid, Control, int>("RowSpan", 1); public static readonly AttachedProperty<bool> IsSharedSizeScopeProperty = AvaloniaProperty.RegisterAttached<Grid, Control, bool>("IsSharedSizeScope", false); protected override void OnMeasureInvalidated() { base.OnMeasureInvalidated(); _sharedSizeHost?.InvalidateMeasure(this); } private SharedSizeScopeHost _sharedSizeHost; /// <summary> /// Defines the SharedSizeScopeHost private property. /// The ampersands are used to make accessing the property via xaml inconvenient. /// </summary> internal static readonly AttachedProperty<SharedSizeScopeHost> s_sharedSizeScopeHostProperty = AvaloniaProperty.RegisterAttached<Grid, Control, SharedSizeScopeHost>("&&SharedSizeScopeHost"); private ColumnDefinitions _columnDefinitions; private RowDefinitions _rowDefinitions; static Grid() { AffectsParentMeasure<Grid>(ColumnProperty, ColumnSpanProperty, RowProperty, RowSpanProperty); IsSharedSizeScopeProperty.Changed.AddClassHandler<Control>(IsSharedSizeScopeChanged); } public Grid() { this.AttachedToVisualTree += Grid_AttachedToVisualTree; this.DetachedFromVisualTree += Grid_DetachedFromVisualTree; } /// <summary> /// Gets or sets the columns definitions for the grid. /// </summary> public ColumnDefinitions ColumnDefinitions { get { if (_columnDefinitions == null) { ColumnDefinitions = new ColumnDefinitions(); } return _columnDefinitions; } set { if (_columnDefinitions != null) { throw new NotSupportedException("Reassigning ColumnDefinitions not yet implemented."); } _columnDefinitions = value; _columnDefinitions.TrackItemPropertyChanged(_ => InvalidateMeasure()); _columnDefinitions.CollectionChanged += (_, __) => InvalidateMeasure(); } } /// <summary> /// Gets or sets the row definitions for the grid. /// </summary> public RowDefinitions RowDefinitions { get { if (_rowDefinitions == null) { RowDefinitions = new RowDefinitions(); } return _rowDefinitions; } set { if (_rowDefinitions != null) { throw new NotSupportedException("Reassigning RowDefinitions not yet implemented."); } _rowDefinitions = value; _rowDefinitions.TrackItemPropertyChanged(_ => InvalidateMeasure()); _rowDefinitions.CollectionChanged += (_, __) => InvalidateMeasure(); } } /// <summary> /// Gets the value of the Column attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's column.</returns> public static int GetColumn(AvaloniaObject element) { return element.GetValue(ColumnProperty); } /// <summary> /// Gets the value of the ColumnSpan attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's column span.</returns> public static int GetColumnSpan(AvaloniaObject element) { return element.GetValue(ColumnSpanProperty); } /// <summary> /// Gets the value of the Row attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's row.</returns> public static int GetRow(AvaloniaObject element) { return element.GetValue(RowProperty); } /// <summary> /// Gets the value of the RowSpan attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <returns>The control's row span.</returns> public static int GetRowSpan(AvaloniaObject element) { return element.GetValue(RowSpanProperty); } /// <summary> /// Sets the value of the Column attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The column value.</param> public static void SetColumn(AvaloniaObject element, int value) { element.SetValue(ColumnProperty, value); } /// <summary> /// Sets the value of the ColumnSpan attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The column span value.</param> public static void SetColumnSpan(AvaloniaObject element, int value) { element.SetValue(ColumnSpanProperty, value); } /// <summary> /// Sets the value of the Row attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The row value.</param> public static void SetRow(AvaloniaObject element, int value) { element.SetValue(RowProperty, value); } /// <summary> /// Sets the value of the RowSpan attached property for a control. /// </summary> /// <param name="element">The control.</param> /// <param name="value">The row span value.</param> public static void SetRowSpan(AvaloniaObject element, int value) { element.SetValue(RowSpanProperty, value); } /// <summary> /// Gets the result of the last column measurement. /// Use this result to reduce the arrange calculation. /// </summary> private GridLayout.MeasureResult _columnMeasureCache; /// <summary> /// Gets the result of the last row measurement. /// Use this result to reduce the arrange calculation. /// </summary> private GridLayout.MeasureResult _rowMeasureCache; /// <summary> /// Gets the row layout as of the last measure. /// </summary> private GridLayout _rowLayoutCache; /// <summary> /// Gets the column layout as of the last measure. /// </summary> private GridLayout _columnLayoutCache; /// <summary> /// Measures the grid. /// </summary> /// <param name="constraint">The available size.</param> /// <returns>The desired size of the control.</returns> protected override Size MeasureOverride(Size constraint) { // Situation 1/2: // If the grid doesn't have any column/row definitions, it behaves like a normal panel. // GridLayout supports this situation but we handle this separately for performance. if (ColumnDefinitions.Count == 0 && RowDefinitions.Count == 0) { var maxWidth = 0.0; var maxHeight = 0.0; foreach (var child in Children.OfType<Control>()) { child.Measure(constraint); maxWidth = Math.Max(maxWidth, child.DesiredSize.Width); maxHeight = Math.Max(maxHeight, child.DesiredSize.Height); } maxWidth = Math.Min(maxWidth, constraint.Width); maxHeight = Math.Min(maxHeight, constraint.Height); return new Size(maxWidth, maxHeight); } // Situation 2/2: // If the grid defines some columns or rows. // Debug Tip: // - GridLayout doesn't hold any state, so you can drag the debugger execution // arrow back to any statements and re-run them without any side-effect. var measureCache = new Dictionary<Control, Size>(); var (safeColumns, safeRows) = GetSafeColumnRows(); var columnLayout = new GridLayout(ColumnDefinitions); var rowLayout = new GridLayout(RowDefinitions); // Note: If a child stays in a * or Auto column/row, use constraint to measure it. columnLayout.AppendMeasureConventions(safeColumns, child => MeasureOnce(child, constraint).Width); rowLayout.AppendMeasureConventions(safeRows, child => MeasureOnce(child, constraint).Height); // Calculate measurement. var columnResult = columnLayout.Measure(constraint.Width); var rowResult = rowLayout.Measure(constraint.Height); // Use the results of the measurement to measure the rest of the children. foreach (var child in Children.OfType<Control>()) { var (column, columnSpan) = safeColumns[child]; var (row, rowSpan) = safeRows[child]; var width = Enumerable.Range(column, columnSpan).Select(x => columnResult.LengthList[x]).Sum(); var height = Enumerable.Range(row, rowSpan).Select(x => rowResult.LengthList[x]).Sum(); MeasureOnce(child, new Size(width, height)); } // Cache the measure result and return the desired size. _columnMeasureCache = columnResult; _rowMeasureCache = rowResult; _rowLayoutCache = rowLayout; _columnLayoutCache = columnLayout; if (_sharedSizeHost?.ParticipatesInScope(this) ?? false) { _sharedSizeHost.UpdateMeasureStatus(this, rowResult, columnResult); } return new Size(columnResult.DesiredLength, rowResult.DesiredLength); // Measure each child only once. // If a child has been measured, it will just return the desired size. Size MeasureOnce(Control child, Size size) { if (measureCache.TryGetValue(child, out var desiredSize)) { return desiredSize; } child.Measure(size); desiredSize = child.DesiredSize; measureCache[child] = desiredSize; return desiredSize; } } /// <summary> /// Arranges the grid's children. /// </summary> /// <param name="finalSize">The size allocated to the control.</param> /// <returns>The space taken.</returns> protected override Size ArrangeOverride(Size finalSize) { // Situation 1/2: // If the grid doesn't have any column/row definitions, it behaves like a normal panel. // GridLayout supports this situation but we handle this separately for performance. if (ColumnDefinitions.Count == 0 && RowDefinitions.Count == 0) { foreach (var child in Children.OfType<Control>()) { child.Arrange(new Rect(finalSize)); } return finalSize; } // Situation 2/2: // If the grid defines some columns or rows. // Debug Tip: // - GridLayout doesn't hold any state, so you can drag the debugger execution // arrow back to any statements and re-run them without any side-effect. var (safeColumns, safeRows) = GetSafeColumnRows(); var columnLayout = _columnLayoutCache; var rowLayout = _rowLayoutCache; var rowCache = _rowMeasureCache; var columnCache = _columnMeasureCache; if (_sharedSizeHost?.ParticipatesInScope(this) ?? false) { (rowCache, columnCache) = _sharedSizeHost.HandleArrange(this, _rowMeasureCache, _columnMeasureCache); rowCache = rowLayout.Measure(finalSize.Height, rowCache.LeanLengthList); columnCache = columnLayout.Measure(finalSize.Width, columnCache.LeanLengthList); } // Calculate for arrange result. var columnResult = columnLayout.Arrange(finalSize.Width, columnCache); var rowResult = rowLayout.Arrange(finalSize.Height, rowCache); // Arrange the children. foreach (var child in Children.OfType<Control>()) { var (column, columnSpan) = safeColumns[child]; var (row, rowSpan) = safeRows[child]; var x = Enumerable.Range(0, column).Sum(c => columnResult.LengthList[c]); var y = Enumerable.Range(0, row).Sum(r => rowResult.LengthList[r]); var width = Enumerable.Range(column, columnSpan).Sum(c => columnResult.LengthList[c]); var height = Enumerable.Range(row, rowSpan).Sum(r => rowResult.LengthList[r]); child.Arrange(new Rect(x, y, width, height)); } // Assign the actual width. for (var i = 0; i < ColumnDefinitions.Count; i++) { ColumnDefinitions[i].ActualWidth = columnResult.LengthList[i]; } // Assign the actual height. for (var i = 0; i < RowDefinitions.Count; i++) { RowDefinitions[i].ActualHeight = rowResult.LengthList[i]; } // Return the render size. return finalSize; } /// <summary> /// Tests whether this grid belongs to a shared size scope. /// </summary> /// <returns>True if the grid is registered in a shared size scope.</returns> internal bool HasSharedSizeScope() { return _sharedSizeHost != null; } /// <summary> /// Called when the SharedSizeScope for a given grid has changed. /// Unregisters the grid from it's current scope and finds a new one (if any) /// </summary> /// <remarks> /// This method, while not efficient, correctly handles nested scopes, with any order of scope changes. /// </remarks> internal void SharedScopeChanged() { _sharedSizeHost?.UnegisterGrid(this); _sharedSizeHost = null; var scope = this.GetVisualAncestors().OfType<Control>() .FirstOrDefault(c => c.GetValue(IsSharedSizeScopeProperty)); if (scope != null) { _sharedSizeHost = scope.GetValue(s_sharedSizeScopeHostProperty); _sharedSizeHost.RegisterGrid(this); } InvalidateMeasure(); } /// <summary> /// Callback when a grid is attached to the visual tree. Finds the innermost SharedSizeScope and registers the grid /// in it. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The event arguments.</param> private void Grid_AttachedToVisualTree(object sender, VisualTreeAttachmentEventArgs e) { var scope = new Control[] { this }.Concat(this.GetVisualAncestors().OfType<Control>()) .FirstOrDefault(c => c.GetValue(IsSharedSizeScopeProperty)); if (_sharedSizeHost != null) throw new AvaloniaInternalException("Shared size scope already present when attaching to visual tree!"); if (scope != null) { _sharedSizeHost = scope.GetValue(s_sharedSizeScopeHostProperty); _sharedSizeHost.RegisterGrid(this); } } /// <summary> /// Callback when a grid is detached from the visual tree. Unregisters the grid from its SharedSizeScope if any. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The event arguments.</param> private void Grid_DetachedFromVisualTree(object sender, VisualTreeAttachmentEventArgs e) { _sharedSizeHost?.UnegisterGrid(this); _sharedSizeHost = null; } /// <summary> /// Get the safe column/columnspan and safe row/rowspan. /// This method ensures that none of the children has a column/row outside the bounds of the definitions. /// </summary> [Pure] private (Dictionary<Control, (int index, int span)> safeColumns, Dictionary<Control, (int index, int span)> safeRows) GetSafeColumnRows() { var columnCount = ColumnDefinitions.Count; var rowCount = RowDefinitions.Count; columnCount = columnCount == 0 ? 1 : columnCount; rowCount = rowCount == 0 ? 1 : rowCount; var safeColumns = Children.OfType<Control>().ToDictionary(child => child, child => GetSafeSpan(columnCount, GetColumn(child), GetColumnSpan(child))); var safeRows = Children.OfType<Control>().ToDictionary(child => child, child => GetSafeSpan(rowCount, GetRow(child), GetRowSpan(child))); return (safeColumns, safeRows); } /// <summary> /// Gets the safe row/column and rowspan/columnspan for a specified range. /// The user may assign row/column properties outside the bounds of the row/column count, this method coerces them inside. /// </summary> /// <param name="length">The row or column count.</param> /// <param name="userIndex">The row or column that the user assigned.</param> /// <param name="userSpan">The rowspan or columnspan that the user assigned.</param> /// <returns>The safe row/column and rowspan/columnspan.</returns> [Pure, MethodImpl(MethodImplOptions.AggressiveInlining)] private static (int index, int span) GetSafeSpan(int length, int userIndex, int userSpan) { var index = userIndex; var span = userSpan; if (index < 0) { span = index + span; index = 0; } if (span <= 0) { span = 1; } if (userIndex >= length) { index = length - 1; span = 1; } else if (userIndex + userSpan > length) { span = length - userIndex; } return (index, span); } private static int ValidateColumn(AvaloniaObject o, int value) { if (value < 0) { throw new ArgumentException("Invalid Grid.Column value."); } return value; } private static int ValidateRow(AvaloniaObject o, int value) { if (value < 0) { throw new ArgumentException("Invalid Grid.Row value."); } return value; } /// <summary> /// Called when the value of <see cref="Grid.IsSharedSizeScopeProperty"/> changes for a control. /// </summary> /// <param name="source">The control that triggered the change.</param> /// <param name="arg2">Change arguments.</param> private static void IsSharedSizeScopeChanged(Control source, AvaloniaPropertyChangedEventArgs arg2) { var shouldDispose = (arg2.OldValue is bool d) && d; if (shouldDispose) { var host = source.GetValue(s_sharedSizeScopeHostProperty) as SharedSizeScopeHost; if (host == null) throw new AvaloniaInternalException("SharedScopeHost wasn't set when IsSharedSizeScope was true!"); host.Dispose(); source.ClearValue(s_sharedSizeScopeHostProperty); } var shouldAssign = (arg2.NewValue is bool a) && a; if (shouldAssign) { if (source.GetValue(s_sharedSizeScopeHostProperty) != null) throw new AvaloniaInternalException("SharedScopeHost was already set when IsSharedSizeScope is only now being set to true!"); source.SetValue(s_sharedSizeScopeHostProperty, new SharedSizeScopeHost()); } // if the scope has changed, notify the descendant grids that they need to update. if (source.GetVisualRoot() != null && shouldAssign || shouldDispose) { var participatingGrids = new[] { source }.Concat(source.GetVisualDescendants()).OfType<Grid>(); foreach (var grid in participatingGrids) grid.SharedScopeChanged(); } } } }
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 Postman.WebApi.MsBuildTask.SampleGeneration { /// <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; } } }
/* * Copyright 2011-2015 Numeric Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; namespace KPCodeGen.Core.TextFormatter { public static class Inflector { private static readonly List<InflectorRule> _plurals = new List<InflectorRule>(); private static readonly List<InflectorRule> _singulars = new List<InflectorRule>(); private static readonly List<string> _uncountables = new List<string>(); private static bool _enableInflection; public static bool EnableInflection { get { return _enableInflection; } set { _enableInflection = value; if (value) SetRules(); } } /// <summary> /// Initializes the <see cref="Inflector"/> class. /// </summary> static Inflector() { if (!EnableInflection) return; SetRules(); } private static void SetRules() { _plurals.Clear(); _singulars.Clear(); _uncountables.Clear(); AddPluralRule("$", "s"); AddPluralRule("s$", "s"); AddPluralRule("(ax|test)is$", "$1es"); AddPluralRule("(octop|vir)us$", "$1i"); AddPluralRule("(alias|status)$", "$1es"); AddPluralRule("(bu)s$", "$1ses"); AddPluralRule("(buffal|tomat)o$", "$1oes"); AddPluralRule("([ti])um$", "$1a"); AddPluralRule("sis$", "ses"); AddPluralRule("(?:([^f])fe|([lr])f)$", "$1$2ves"); AddPluralRule("(hive)$", "$1s"); AddPluralRule("([^aeiouy]|qu)y$", "$1ies"); AddPluralRule("(x|ch|ss|sh)$", "$1es"); AddPluralRule("(matr|vert|ind)ix|ex$", "$1ices"); AddPluralRule("([m|l])ouse$", "$1ice"); AddPluralRule("^(ox)$", "$1en"); AddPluralRule("(quiz)$", "$1zes"); AddSingularRule("s$", String.Empty); AddSingularRule("ss$", "ss"); AddSingularRule("(n)ews$", "$1ews"); AddSingularRule("([ti])a$", "$1um"); AddSingularRule("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis"); AddSingularRule("(^analy)ses$", "$1sis"); AddSingularRule("([^f])ves$", "$1fe"); AddSingularRule("(hive)s$", "$1"); AddSingularRule("(tive)s$", "$1"); AddSingularRule("([lr])ves$", "$1f"); AddSingularRule("([^aeiouy]|qu)ies$", "$1y"); AddSingularRule("(s)eries$", "$1eries"); AddSingularRule("(m)ovies$", "$1ovie"); AddSingularRule("(x|ch|ss|sh)es$", "$1"); AddSingularRule("([m|l])ice$", "$1ouse"); AddSingularRule("(bus)es$", "$1"); AddSingularRule("(o)es$", "$1"); AddSingularRule("(shoe)s$", "$1"); AddSingularRule("(cris|ax|test)es$", "$1is"); AddSingularRule("(octop|vir)i$", "$1us"); AddSingularRule("(alias|status)$", "$1"); AddSingularRule("(alias|status)es$", "$1"); AddSingularRule("^(ox)en", "$1"); AddSingularRule("(vert|ind)ices$", "$1ex"); AddSingularRule("(matr)ices$", "$1ix"); AddSingularRule("(quiz)zes$", "$1"); AddIrregularRule("person", "people"); AddIrregularRule("man", "men"); AddIrregularRule("child", "children"); AddIrregularRule("sex", "sexes"); AddIrregularRule("tax", "taxes"); AddIrregularRule("move", "moves"); AddUnknownCountRule("equipment"); AddUnknownCountRule("information"); AddUnknownCountRule("rice"); AddUnknownCountRule("money"); AddUnknownCountRule("species"); AddUnknownCountRule("series"); AddUnknownCountRule("fish"); AddUnknownCountRule("sheep"); } /// <summary> /// Adds the irregular rule. /// </summary> /// <param name="singular">The singular.</param> /// <param name="plural">The plural.</param> private static void AddIrregularRule(string singular, string plural) { AddPluralRule(String.Concat("(", singular[0], ")", singular.Substring(1), "$"), String.Concat("$1", plural.Substring(1))); AddSingularRule(String.Concat("(", plural[0], ")", plural.Substring(1), "$"), String.Concat("$1", singular.Substring(1))); } /// <summary> /// Adds the unknown count rule. /// </summary> /// <param name="word">The word.</param> private static void AddUnknownCountRule(string word) { _uncountables.Add(word.ToLower()); } /// <summary> /// Adds the plural rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddPluralRule(string rule, string replacement) { _plurals.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Adds the singular rule. /// </summary> /// <param name="rule">The rule.</param> /// <param name="replacement">The replacement.</param> private static void AddSingularRule(string rule, string replacement) { _singulars.Add(new InflectorRule(rule, replacement)); } /// <summary> /// Makes the plural. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakePlural(this string word) { if (string.IsNullOrEmpty(word)) return word; return SetRules(_plurals, word); } /// <summary> /// Makes the singular. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeSingular(this string word) { if (string.IsNullOrEmpty(word)) return word; return SetRules(_singulars, word); } /// <summary> /// Applies the rules. /// </summary> /// <param name="rules">The rules.</param> /// <param name="word">The word.</param> /// <returns></returns> private static string SetRules(IList<InflectorRule> rules, string word) { if (string.IsNullOrEmpty(word)) return word; string result = word; if (!_uncountables.Contains(word.ToLower())) { for (int i = rules.Count - 1; i >= 0; i--) { string currentPass = rules[i].Apply(word); if (currentPass != null) { result = currentPass; break; } } } return result; } /// <summary> /// Converts the string to title case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string ToTitleCase(this string word) { if (string.IsNullOrEmpty(word)) return word; return Regex.Replace(ToHumanCase(AddUnderscores(word)), @"\b([a-z])", match => match.Captures[0].Value.ToUpper()); } /// <summary> /// Converts the string to human case. /// </summary> /// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param> /// <returns></returns> public static string ToHumanCase(this string lowercaseAndUnderscoredWord) { return MakeInitialCaps(Regex.Replace(lowercaseAndUnderscoredWord, @"_", " ")); } /// <summary> /// Convert string to proper case /// </summary> /// <param name="sourceString">The source string.</param> /// <returns></returns> public static string ToProper(this string sourceString) { string propertyName = sourceString.ToPascalCase(); return propertyName; } /// <summary> /// Converts the string to pascal case. /// </summary> /// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param> /// <returns></returns> public static string ToPascalCase(this string lowercaseAndUnderscoredWord) { return ToPascalCase(lowercaseAndUnderscoredWord, true); } /// <summary> /// Converts text to pascal case... /// </summary> /// <param name="text">The text.</param> /// <param name="removeUnderscores">if set to <c>true</c> [remove underscores].</param> /// <returns></returns> public static string ToPascalCase(this string text, bool removeUnderscores) { if (String.IsNullOrEmpty(text)) return text; text = text.Replace("_", " "); string joinString = removeUnderscores ? String.Empty : "_"; string[] words = text.Split(' '); if (words.Length > 1) { for (int i = 0; i < words.Length; i++) { words[i] = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(words[i].ToLowerInvariant()); } return String.Join(joinString, words); } return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(words[0].ToLowerInvariant()); } /// <summary> /// Converts the string to camel case. /// </summary> /// <param name="lowercaseAndUnderscoredWord">The lowercase and underscored word.</param> /// <returns></returns> public static string ToCamelCase(this string lowercaseAndUnderscoredWord) { return MakeInitialLowerCase(ToPascalCase(lowercaseAndUnderscoredWord)); } /// <summary> /// Adds the underscores. /// </summary> /// <param name="pascalCasedWord">The pascal cased word.</param> /// <returns></returns> public static string AddUnderscores(this string pascalCasedWord) { return Regex.Replace( Regex.Replace(Regex.Replace(pascalCasedWord, @"([A-Z]+)([A-Z][a-z])", "$1_$2"), @"([a-z\d])([A-Z])", "$1_$2"), @"[-\s]", "_").ToLower(); } /// <summary> /// Makes the initial caps. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialCaps(this string word) { return String.Concat(word.Substring(0, 1).ToUpper(), word.Substring(1).ToLower()); } /// <summary> /// Makes the initial lower case. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public static string MakeInitialLowerCase(this string word) { if (string.IsNullOrEmpty(word)) return word; return String.Concat(word.Substring(0, 1).ToLower(), word.Substring(1)); } /// <summary> /// Adds the ordinal suffix. /// </summary> /// <param name="number">The number.</param> /// <returns></returns> //public static string AddOrdinalSuffix(this string number) //{ // if (number.IsStringNumeric()) // { // int n = int.Parse(number); // int nMod100 = n % 100; // if (nMod100 >= 11 && nMod100 <= 13) // return String.Concat(number, "th"); // switch (n % 10) // { // case 1: // return String.Concat(number, "st"); // case 2: // return String.Concat(number, "nd"); // case 3: // return String.Concat(number, "rd"); // default: // return String.Concat(number, "th"); // } // } // return number; //} /// <summary> /// Converts the underscores to dashes. /// </summary> /// <param name="underscoredWord">The underscored word.</param> /// <returns></returns> public static string ConvertUnderscoresToDashes(this string underscoredWord) { return underscoredWord.Replace('_', '-'); } /// <summary> /// Checks if the first character of a string if capitalized. /// </summary> /// <param name="word"></param> /// <returns></returns> public static bool IsUpperCase(this string word) { return (new Regex("^[A-Z][^\\s]*")).IsMatch(word); } #region Nested type: InflectorRule /// <summary> /// Summary for the InflectorRule class /// </summary> private class InflectorRule { /// <summary> /// /// </summary> public readonly Regex regex; /// <summary> /// /// </summary> public readonly string replacement; /// <summary> /// Initializes a new instance of the <see cref="InflectorRule"/> class. /// </summary> /// <param name="regexPattern">The regex pattern.</param> /// <param name="replacementText">The replacement text.</param> public InflectorRule(string regexPattern, string replacementText) { regex = new Regex(regexPattern, RegexOptions.IgnoreCase); replacement = replacementText; } /// <summary> /// Applies the specified word. /// </summary> /// <param name="word">The word.</param> /// <returns></returns> public string Apply(string word) { if (!regex.IsMatch(word)) return null; string replace = regex.Replace(word, replacement); if (word == word.ToUpper()) replace = replace.ToUpper(); return replace; } } #endregion } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Vanara.Extensions; using Vanara.InteropServices; using static Vanara.PInvoke.D2d1; using static Vanara.PInvoke.Dwrite; namespace Vanara.PInvoke.Tests { public class DirectWriteTests : GenericComTester<IDWriteFactory> { private const string fontDir = @"C:\Temp\Fonts"; protected override IDWriteFactory InitInstance() => DWriteCreateFactory<IDWriteFactory>(); [Test] public void EnumFontsTest() { Instance.GetSystemFontCollection(out var coll); using var pColl = ComReleaserFactory.Create(coll); EnumFonts(pColl.Item); } private static void EnumFonts(IDWriteFontCollection coll) { var count = coll.GetFontFamilyCount(); var locale = System.Globalization.CultureInfo.CurrentCulture.Name; for (var i = 0U; i < count; i++) { try { using var pFontFam = ComReleaserFactory.Create(coll.GetFontFamily(i)); using var pFamNames = ComReleaserFactory.Create(pFontFam.Item.GetFamilyNames()); pFamNames.Item.FindLocaleName(locale, out var index, out var exists); if (!exists) index = 0; var len = pFamNames.Item.GetStringLength(index) + 1; var str = new StringBuilder((int)len); pFamNames.Item.GetString(index, str, len); TestContext.WriteLine(str); } catch (Exception ex) { TestContext.WriteLine("ERROR: " + ex.Message); } } } [Test] public void LoadCustomFontsTest() { var loader = new FontLoader(); Instance.RegisterFontCollectionLoader(loader); try { using var pDir = new SafeCoTaskMemString(fontDir); using var pColl = ComReleaserFactory.Create(Instance.CreateCustomFontCollection(loader, pDir, pDir.Size)); EnumFonts(pColl.Item); } finally { Instance.UnregisterFontCollectionLoader(loader); } } [Test] public void CreateFontFaceTest() { var ldr = new FontLoader(); var pList = Directory.EnumerateFiles(fontDir).Take(1).Select(f => Instance.CreateFontFileReference(f)).ToArray(); try { pList[0].Analyze(out var sup, out var ft, out var fc, out var fcn); TestContext.WriteLine($"Supported={sup}; FileType={ft}; FaceType={fc}; FaceCnt={fcn}"); var pFF = ComReleaserFactory.Create(Instance.CreateFontFace(fc, (uint)pList.Length, pList, 0, DWRITE_FONT_SIMULATIONS.DWRITE_FONT_SIMULATIONS_NONE)); Assert.That(pFF.Item.GetType(), Is.EqualTo(fc)); var ff = new IDWriteFontFile[pList.Length]; var fflen = (uint)ff.Length; Assert.That(() => pFF.Item.GetFiles(ref fflen, ff), Throws.Nothing); ff.WriteValues(); TestContext.WriteLine($"Index in font files: {pFF.Item.GetIndex()}"); TestContext.WriteLine($"Simulations: {pFF.Item.GetSimulations()}"); Assert.That(pFF.Item.IsSymbolFont(), Is.False); Assert.That(() => { pFF.Item.GetMetrics(out var faceMetrics); faceMetrics.WriteValues(); }, Throws.Nothing); var glCnt = (int)pFF.Item.GetGlyphCount(); Assert.That(glCnt, Is.GreaterThan(0)); glCnt = Math.Min(3, glCnt); var glm = new DWRITE_GLYPH_METRICS[glCnt]; var glidx = Enumerable.Range(0, glCnt).Select(i => (ushort)i).ToArray(); Assert.That(() => pFF.Item.GetDesignGlyphMetrics(glidx, (uint)glCnt, glm), Throws.Nothing); glm.WriteValues(); Assert.That(() => { var tag = DWRITE_FONT_FEATURE_TAG.DWRITE_FONT_FEATURE_TAG_DEFAULT; pFF.Item.TryGetFontTable((uint)tag, out var tableData, out var tableSize, out var tableCtx, out var tableExists); TestContext.WriteLine($"Table: {tag} = Sz:{tableSize}, {tableExists}"); pFF.Item.ReleaseFontTable(tableCtx); }, Throws.Nothing); var rParams = Instance.CreateRenderingParams(); pFF.Item.GetRecommendedRenderingMode(9f, 72f, DWRITE_MEASURING_MODE.DWRITE_MEASURING_MODE_NATURAL, rParams).WriteValues(); var hMon = User32.MonitorFromPoint(System.Drawing.Point.Empty, User32.MonitorFlags.MONITOR_DEFAULTTOPRIMARY); rParams = Instance.CreateMonitorRenderingParams(hMon); pFF.Item.GetRecommendedRenderingMode(9f, 72f, DWRITE_MEASURING_MODE.DWRITE_MEASURING_MODE_NATURAL, rParams).WriteValues(); rParams = Instance.CreateCustomRenderingParams(2.2f, 1f, 1f, DWRITE_PIXEL_GEOMETRY.DWRITE_PIXEL_GEOMETRY_BGR, DWRITE_RENDERING_MODE.DWRITE_RENDERING_MODE_ALIASED); pFF.Item.GetRecommendedRenderingMode(9f, 72f, DWRITE_MEASURING_MODE.DWRITE_MEASURING_MODE_NATURAL, rParams).WriteValues(); pFF.Item.GetGdiCompatibleMetrics(9f, 72f).WriteValues(); Assert.That(() => pFF.Item.GetGdiCompatibleGlyphMetrics(9f, 72f, default, true, glidx, (uint)glCnt, glm), Throws.Nothing); glm.WriteValues(); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } } [Test] public void CreateTextFormatTest() { using var pTF = ComReleaserFactory.Create(Instance.CreateTextFormat("Arial", default, DWRITE_FONT_WEIGHT.DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE.DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH.DWRITE_FONT_STRETCH_NORMAL, 11f, "en-us")); Assert.That(pTF.Item.GetFontSize(), Is.GreaterThan(0f)); Assert.That(() => pTF.Item.SetTextAlignment(DWRITE_TEXT_ALIGNMENT.DWRITE_TEXT_ALIGNMENT_CENTER), Throws.Nothing); var sb = new StringBuilder(20); Assert.That(() => pTF.Item.GetLocaleName(sb, (uint)sb.Capacity), Throws.Nothing); Assert.That(sb.ToString(), Is.EqualTo("en-us")); } [Test] public void CreateTypographyTest() { using var pTyp = ComReleaserFactory.Create(Instance.CreateTypography()); var cnt = pTyp.Item.GetFontFeatureCount(); if (cnt > 0) pTyp.Item.GetFontFeature(0).WriteValues(); } [Test] public void GetGdiInteropTest() { Assert.That(() => { using var p = ComReleaserFactory.Create(Instance.GetGdiInterop()); }, Throws.Nothing); } [Test] public void FontFileLoaderTest() { var loader = new FileLoader(); Assert.That(() => Instance.RegisterFontFileLoader(loader), Throws.Nothing); try { } finally { Assert.That(() => Instance.UnregisterFontFileLoader(loader), Throws.Nothing); } } [ComVisible(true)] public class FontLoader : IDWriteFontCollectionLoader { public HRESULT CreateEnumeratorFromKey([In] IDWriteFactory factory, IntPtr collectionKey, uint collectionKeySize, out IDWriteFontFileEnumerator fontFileEnumerator) { fontFileEnumerator = null; if (factory is null || collectionKey == default) return HRESULT.E_INVALIDARG; fontFileEnumerator = new FontEnumerator(factory, StringHelper.GetString(collectionKey, CharSet.Unicode, collectionKeySize)); return HRESULT.S_OK; } } [ComVisible(true)] public class FileLoader : IDWriteFontFileLoader { public FileLoader() { } public HRESULT CreateStreamFromKey([In] IntPtr fontFileReferenceKey, uint fontFileReferenceKeySize, out IDWriteFontFileStream fontFileStream) { fontFileStream = new FileStream(Directory.EnumerateFiles(fontDir).First()); return default; } } [ComVisible(true)] public class FileStream : IDWriteFontFileStream, IDisposable { FileInfo fi; SafeHGlobalHandle mem; public FileStream(string path) { fi = new FileInfo(path); mem = new SafeHGlobalHandle(File.ReadAllBytes(path)); } public HRESULT ReadFileFragment(out IntPtr fragmentStart, ulong fileOffset, ulong fragmentSize, [Out] out IntPtr fragmentContext) { fragmentContext = default; if (fileOffset + fragmentSize >= (ulong)fi.Length) { fragmentStart = default; return HRESULT.E_FAIL; } fragmentStart = ((IntPtr)mem).Offset((long)fileOffset); return default; } public void ReleaseFileFragment([In] IntPtr fragmentContext) { } public HRESULT GetFileSize(out ulong fileSize) { fileSize = (ulong)fi.Length; return default; } public HRESULT GetLastWriteTime(out System.Runtime.InteropServices.ComTypes.FILETIME lastWriteTime) { lastWriteTime = fi.LastWriteTime.ToFileTimeStruct(); return default; } public void Dispose() => ((IDisposable)mem).Dispose(); } [ComVisible(true)] public class FontEnumerator : IDWriteFontFileEnumerator { private IEnumerator<string> enumerator; private IDWriteFactory factory; public FontEnumerator(IDWriteFactory fact, string path) { factory = fact; enumerator = Directory.EnumerateFiles(path).GetEnumerator(); } public HRESULT MoveNext([MarshalAs(UnmanagedType.Bool)] out bool hasCurrentFile) { hasCurrentFile = enumerator.MoveNext(); return HRESULT.S_OK; } public HRESULT GetCurrentFontFile(out IDWriteFontFile fontFile) { try { fontFile = factory.CreateFontFileReference(enumerator.Current); } catch (COMException ex) { fontFile = null; return ex.HResult; } return default; } } } }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Params { /// <java-name> /// org/apache/http/params/HttpConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParamBean", AccessFlags = 33)] public partial class HttpConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(I)V", AccessFlags = 1)] public virtual void SetSoTimeout(int soTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Z)V", AccessFlags = 1)] public virtual void SetTcpNoDelay(bool tcpNoDelay) /* MethodBuilder.Create */ { } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(I)V", AccessFlags = 1)] public virtual void SetSocketBufferSize(int socketBufferSize) /* MethodBuilder.Create */ { } /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(I)V", AccessFlags = 1)] public virtual void SetLinger(int linger) /* MethodBuilder.Create */ { } /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(I)V", AccessFlags = 1)] public virtual void SetConnectionTimeout(int connectionTimeout) /* MethodBuilder.Create */ { } /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Z)V", AccessFlags = 1)] public virtual void SetStaleCheckingEnabled(bool staleCheckingEnabled) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>This class implements an adaptor around the HttpParams interface to simplify manipulation of the HTTP protocol specific parameters. <br></br> Note that the <b>implements</b> relation to CoreProtocolPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0</para><para>CoreProtocolPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpProtocolParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParams", AccessFlags = 49)] public sealed partial class HttpProtocolParams : global::Org.Apache.Http.Params.ICoreProtocolPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpProtocolParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the charset to be used for writing HTTP headers. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getHttpElementCharset /// </java-name> [Dot42.DexImport("getHttpElementCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the charset to be used for writing HTTP headers. </para> /// </summary> /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetHttpElementCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <returns> /// <para>The charset </para> /// </returns> /// <java-name> /// getContentCharset /// </java-name> [Dot42.DexImport("getContentCharset", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the default charset to be used for writing content body, when no charset explicitly specified. </para> /// </summary> /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetContentCharset(global::Org.Apache.Http.Params.IHttpParams @params, string charset) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns protocol version to be used per default.</para><para></para> /// </summary> /// <returns> /// <para>protocol version </para> /// </returns> /// <java-name> /// getVersion /// </java-name> [Dot42.DexImport("getVersion", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/ProtocolVersion;", AccessFlags = 9)] public static global::Org.Apache.Http.ProtocolVersion GetVersion(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.ProtocolVersion); } /// <summary> /// <para>Assigns the protocol version to be used by the HTTP methods that this collection of parameters applies to.</para><para></para> /// </summary> /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/ProtocolVersion;)V", AccessFlags = 9)] public static void SetVersion(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.ProtocolVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// getUserAgent /// </java-name> [Dot42.DexImport("getUserAgent", "(Lorg/apache/http/params/HttpParams;)Ljava/lang/String;", AccessFlags = 9)] public static string GetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Lorg/apache/http/params/HttpParams;Ljava/lang/String;)V", AccessFlags = 9)] public static void SetUserAgent(global::Org.Apache.Http.Params.IHttpParams @params, string useragent) /* MethodBuilder.Create */ { } /// <java-name> /// useExpectContinue /// </java-name> [Dot42.DexImport("useExpectContinue", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool UseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetUseExpectContinue(global::Org.Apache.Http.Params.IHttpParams @params, bool b) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_TIMEOUT </para></para> /// </summary> /// <java-name> /// SO_TIMEOUT /// </java-name> [Dot42.DexImport("SO_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_TIMEOUT = "http.socket.timeout"; /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption. </para><para>This parameter expects a value of type Boolean. </para><para><para>java.net.SocketOptions::TCP_NODELAY </para></para> /// </summary> /// <java-name> /// TCP_NODELAY /// </java-name> [Dot42.DexImport("TCP_NODELAY", "Ljava/lang/String;", AccessFlags = 25)] public const string TCP_NODELAY = "http.tcp.nodelay"; /// <summary> /// <para>Determines the size of the internal socket buffer used to buffer data while receiving / transmitting HTTP messages. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// SOCKET_BUFFER_SIZE /// </java-name> [Dot42.DexImport("SOCKET_BUFFER_SIZE", "Ljava/lang/String;", AccessFlags = 25)] public const string SOCKET_BUFFER_SIZE = "http.socket.buffer-size"; /// <summary> /// <para>Sets SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used. The setting only affects socket close. </para><para>This parameter expects a value of type Integer. </para><para><para>java.net.SocketOptions::SO_LINGER </para></para> /// </summary> /// <java-name> /// SO_LINGER /// </java-name> [Dot42.DexImport("SO_LINGER", "Ljava/lang/String;", AccessFlags = 25)] public const string SO_LINGER = "http.socket.linger"; /// <summary> /// <para>Determines the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// CONNECTION_TIMEOUT /// </java-name> [Dot42.DexImport("CONNECTION_TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string CONNECTION_TIMEOUT = "http.connection.timeout"; /// <summary> /// <para>Determines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STALE_CONNECTION_CHECK /// </java-name> [Dot42.DexImport("STALE_CONNECTION_CHECK", "Ljava/lang/String;", AccessFlags = 25)] public const string STALE_CONNECTION_CHECK = "http.connection.stalecheck"; /// <summary> /// <para>Determines the maximum line length limit. If set to a positive value, any HTTP line exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_LINE_LENGTH /// </java-name> [Dot42.DexImport("MAX_LINE_LENGTH", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_LINE_LENGTH = "http.connection.max-line-length"; /// <summary> /// <para>Determines the maximum HTTP header count allowed. If set to a positive value, the number of HTTP headers received from the data stream exceeding this limit will cause an IOException. A negative or zero value will effectively disable the check. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_HEADER_COUNT /// </java-name> [Dot42.DexImport("MAX_HEADER_COUNT", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_HEADER_COUNT = "http.connection.max-header-count"; } /// <summary> /// <para>Defines parameter names for connections in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreConnectionPNames", AccessFlags = 1537)] public partial interface ICoreConnectionPNames /* scope: __dot42__ */ { } /// <java-name> /// org/apache/http/params/HttpProtocolParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpProtocolParamBean", AccessFlags = 33)] public partial class HttpProtocolParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpProtocolParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setHttpElementCharset /// </java-name> [Dot42.DexImport("setHttpElementCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetHttpElementCharset(string httpElementCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setContentCharset /// </java-name> [Dot42.DexImport("setContentCharset", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetContentCharset(string contentCharset) /* MethodBuilder.Create */ { } /// <java-name> /// setVersion /// </java-name> [Dot42.DexImport("setVersion", "(Lorg/apache/http/HttpVersion;)V", AccessFlags = 1)] public virtual void SetVersion(global::Org.Apache.Http.HttpVersion version) /* MethodBuilder.Create */ { } /// <java-name> /// setUserAgent /// </java-name> [Dot42.DexImport("setUserAgent", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetUserAgent(string userAgent) /* MethodBuilder.Create */ { } /// <java-name> /// setUseExpectContinue /// </java-name> [Dot42.DexImport("setUseExpectContinue", "(Z)V", AccessFlags = 1)] public virtual void SetUseExpectContinue(bool useExpectContinue) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpProtocolParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class ICoreProtocolPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the protocol version used per default. </para><para>This parameter expects a value of type org.apache.http.ProtocolVersion. </para> /// </summary> /// <java-name> /// PROTOCOL_VERSION /// </java-name> [Dot42.DexImport("PROTOCOL_VERSION", "Ljava/lang/String;", AccessFlags = 25)] public const string PROTOCOL_VERSION = "http.protocol.version"; /// <summary> /// <para>Defines the charset to be used for encoding HTTP protocol elements. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_ELEMENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_ELEMENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_ELEMENT_CHARSET = "http.protocol.element-charset"; /// <summary> /// <para>Defines the charset to be used per default for encoding content body. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// HTTP_CONTENT_CHARSET /// </java-name> [Dot42.DexImport("HTTP_CONTENT_CHARSET", "Ljava/lang/String;", AccessFlags = 25)] public const string HTTP_CONTENT_CHARSET = "http.protocol.content-charset"; /// <summary> /// <para>Defines the content of the <code>User-Agent</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// USER_AGENT /// </java-name> [Dot42.DexImport("USER_AGENT", "Ljava/lang/String;", AccessFlags = 25)] public const string USER_AGENT = "http.useragent"; /// <summary> /// <para>Defines the content of the <code>Server</code> header. </para><para>This parameter expects a value of type String. </para> /// </summary> /// <java-name> /// ORIGIN_SERVER /// </java-name> [Dot42.DexImport("ORIGIN_SERVER", "Ljava/lang/String;", AccessFlags = 25)] public const string ORIGIN_SERVER = "http.origin-server"; /// <summary> /// <para>Defines whether responses with an invalid <code>Transfer-Encoding</code> header should be rejected. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// STRICT_TRANSFER_ENCODING /// </java-name> [Dot42.DexImport("STRICT_TRANSFER_ENCODING", "Ljava/lang/String;", AccessFlags = 25)] public const string STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding"; /// <summary> /// <para>Activates 'Expect: 100-continue' handshake for the entity enclosing methods. The purpose of the 'Expect: 100-continue' handshake to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. </para><para>The use of the 'Expect: 100-continue' handshake can result in noticable peformance improvement for entity enclosing requests (such as POST and PUT) that require the target server's authentication. </para><para>'Expect: 100-continue' handshake should be used with caution, as it may cause problems with HTTP servers and proxies that do not support HTTP/1.1 protocol. </para><para>This parameter expects a value of type Boolean. </para> /// </summary> /// <java-name> /// USE_EXPECT_CONTINUE /// </java-name> [Dot42.DexImport("USE_EXPECT_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string USE_EXPECT_CONTINUE = "http.protocol.expect-continue"; /// <summary> /// <para>Defines the maximum period of time in milliseconds the client should spend waiting for a 100-continue response. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// WAIT_FOR_CONTINUE /// </java-name> [Dot42.DexImport("WAIT_FOR_CONTINUE", "Ljava/lang/String;", AccessFlags = 25)] public const string WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue"; } /// <summary> /// <para>Defines parameter names for protocol execution in HttpCore.</para><para><para></para><title>Revision:</title><para>576077 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/CoreProtocolPNames /// </java-name> [Dot42.DexImport("org/apache/http/params/CoreProtocolPNames", AccessFlags = 1537)] public partial interface ICoreProtocolPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Represents a collection of HTTP protocol and framework parameters.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpParams", AccessFlags = 1537)] public partial interface IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Obtains the value of the given parameter.</para><para><para>setParameter(String, Object) </para></para> /// </summary> /// <returns> /// <para>an object that represents the value of the parameter, <code>null</code> if the parameter is not set or if it is explicitly set to <code>null</code></para> /// </returns> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] object GetParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns the value to the parameter with the given name.</para><para></para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Creates a copy of these parameters.</para><para></para> /// </summary> /// <returns> /// <para>a new set of parameters holding the same values as this one </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool RemoveParameter(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Long parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setLongParameter(String, long) </para></para> /// </summary> /// <returns> /// <para>a Long that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1025)] long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Long to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns an Integer parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setIntParameter(String, int) </para></para> /// </summary> /// <returns> /// <para>a Integer that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1025)] int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns an Integer to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Double parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setDoubleParameter(String, double) </para></para> /// </summary> /// <returns> /// <para>a Double that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1025)] double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Double to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns a Boolean parameter value with the given name. If the parameter is not explicitly set, the default value is returned.</para><para><para>setBooleanParameter(String, boolean) </para></para> /// </summary> /// <returns> /// <para>a Boolean that represents the value of the parameter.</para> /// </returns> /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1025)] bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ ; /// <summary> /// <para>Assigns a Boolean to the parameter with the given name</para><para></para> /// </summary> /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is set to <code>true</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is set to value <code>true</code>, <code>false</code> if it is not set or set to <code>false</code> </para> /// </returns> /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterTrue(string name) /* MethodBuilder.Create */ ; /// <summary> /// <para>Checks if a boolean parameter is not set or <code>false</code>.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the parameter is either not set or set to value <code>false</code>, <code>false</code> if it is set to <code>true</code> </para> /// </returns> /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1025)] bool IsParameterFalse(string name) /* MethodBuilder.Create */ ; } /// <summary> /// <para>HttpParams implementation that delegates resolution of a parameter to the given default HttpParams instance if the parameter is not present in the local one. The state of the local collection can be mutated, whereas the default collection is treated as read-only.</para><para><para></para><para></para><title>Revision:</title><para>610763 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/DefaultedHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/DefaultedHttpParams", AccessFlags = 49)] public sealed partial class DefaultedHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public DefaultedHttpParams(global::Org.Apache.Http.Params.IHttpParams local, global::Org.Apache.Http.Params.IHttpParams defaults) /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of the local collection with the same default </para> /// </summary> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Retrieves the value of the parameter from the local collection and, if the parameter is not set locally, delegates its resolution to the default collection. </para> /// </summary> /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Attempts to remove the parameter from the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Sets the parameter in the local collection. This method <b>does not</b> modify the default collection. </para> /// </summary> /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDefaults /// </java-name> [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public global::Org.Apache.Http.Params.IHttpParams GetDefaults() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal DefaultedHttpParams() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getDefaults /// </java-name> public global::Org.Apache.Http.Params.IHttpParams Defaults { [Dot42.DexImport("getDefaults", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] get{ return GetDefaults(); } } } /// <java-name> /// org/apache/http/params/HttpAbstractParamBean /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpAbstractParamBean", AccessFlags = 1057)] public abstract partial class HttpAbstractParamBean /* scope: __dot42__ */ { /// <java-name> /// params /// </java-name> [Dot42.DexImport("params", "Lorg/apache/http/params/HttpParams;", AccessFlags = 20)] protected internal readonly global::Org.Apache.Http.Params.IHttpParams Params; [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public HttpAbstractParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal HttpAbstractParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>An adaptor for accessing connection parameters in HttpParams. <br></br> Note that the <b>implements</b> relation to CoreConnectionPNames is for compatibility with existing application code only. References to the parameter names should use the interface, not this class.</para><para><para></para><para></para><title>Revision:</title><para>576089 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/HttpConnectionParams /// </java-name> [Dot42.DexImport("org/apache/http/params/HttpConnectionParams", AccessFlags = 49)] public sealed partial class HttpConnectionParams : global::Org.Apache.Http.Params.ICoreConnectionPNames /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal HttpConnectionParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds </para> /// </returns> /// <java-name> /// getSoTimeout /// </java-name> [Dot42.DexImport("getSoTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the default socket timeout (<code>SO_TIMEOUT</code>) in milliseconds which is the timeout for waiting for data. A timeout value of zero is interpreted as an infinite timeout. This value is used when no socket timeout is set in the method parameters.</para><para></para> /// </summary> /// <java-name> /// setSoTimeout /// </java-name> [Dot42.DexImport("setSoTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSoTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests if Nagle's algorithm is to be used.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if the Nagle's algorithm is to NOT be used (that is enable TCP_NODELAY), <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// getTcpNoDelay /// </java-name> [Dot42.DexImport("getTcpNoDelay", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool GetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. When applications wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the cost of an increase in bandwidth consumption.</para><para></para> /// </summary> /// <java-name> /// setTcpNoDelay /// </java-name> [Dot42.DexImport("setTcpNoDelay", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetTcpNoDelay(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } /// <java-name> /// getSocketBufferSize /// </java-name> [Dot42.DexImport("getSocketBufferSize", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setSocketBufferSize /// </java-name> [Dot42.DexImport("setSocketBufferSize", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetSocketBufferSize(global::Org.Apache.Http.Params.IHttpParams @params, int size) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns linger-on-close timeout. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <returns> /// <para>the linger-on-close timeout </para> /// </returns> /// <java-name> /// getLinger /// </java-name> [Dot42.DexImport("getLinger", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetLinger(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Returns linger-on-close timeout. This option disables/enables immediate return from a close() of a TCP Socket. Enabling this option with a non-zero Integer timeout means that a close() will block pending the transmission and acknowledgement of all data written to the peer, at which point the socket is closed gracefully. Value <code>0</code> implies that the option is disabled. Value <code>-1</code> implies that the JRE default is used.</para><para></para> /// </summary> /// <java-name> /// setLinger /// </java-name> [Dot42.DexImport("setLinger", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetLinger(global::Org.Apache.Http.Params.IHttpParams @params, int value) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getConnectionTimeout /// </java-name> [Dot42.DexImport("getConnectionTimeout", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default value is zero.</para><para></para> /// </summary> /// <java-name> /// setConnectionTimeout /// </java-name> [Dot42.DexImport("setConnectionTimeout", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetConnectionTimeout(global::Org.Apache.Http.Params.IHttpParams @params, int timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Tests whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <returns> /// <para><code>true</code> if stale connection check is to be used, <code>false</code> otherwise. </para> /// </returns> /// <java-name> /// isStaleCheckingEnabled /// </java-name> [Dot42.DexImport("isStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;)Z", AccessFlags = 9)] public static bool IsStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Defines whether stale connection check is to be used. Disabling stale connection check may result in slight performance improvement at the risk of getting an I/O error when executing a request over a connection that has been closed at the server side.</para><para></para> /// </summary> /// <java-name> /// setStaleCheckingEnabled /// </java-name> [Dot42.DexImport("setStaleCheckingEnabled", "(Lorg/apache/http/params/HttpParams;Z)V", AccessFlags = 9)] public static void SetStaleCheckingEnabled(global::Org.Apache.Http.Params.IHttpParams @params, bool value) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Abstract base class for parameter collections. Type specific setters and getters are mapped to the abstract, generic getters and setters.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>542224 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/AbstractHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/AbstractHttpParams", AccessFlags = 1057)] public abstract partial class AbstractHttpParams : global::Org.Apache.Http.Params.IHttpParams /* scope: __dot42__ */ { /// <summary> /// <para>Instantiates parameters. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 4)] protected internal AbstractHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getLongParameter /// </java-name> [Dot42.DexImport("getLongParameter", "(Ljava/lang/String;J)J", AccessFlags = 1)] public virtual long GetLongParameter(string name, long defaultValue) /* MethodBuilder.Create */ { return default(long); } /// <java-name> /// setLongParameter /// </java-name> [Dot42.DexImport("setLongParameter", "(Ljava/lang/String;J)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetLongParameter(string name, long value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getIntParameter /// </java-name> [Dot42.DexImport("getIntParameter", "(Ljava/lang/String;I)I", AccessFlags = 1)] public virtual int GetIntParameter(string name, int defaultValue) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setIntParameter /// </java-name> [Dot42.DexImport("setIntParameter", "(Ljava/lang/String;I)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetIntParameter(string name, int value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getDoubleParameter /// </java-name> [Dot42.DexImport("getDoubleParameter", "(Ljava/lang/String;D)D", AccessFlags = 1)] public virtual double GetDoubleParameter(string name, double defaultValue) /* MethodBuilder.Create */ { return default(double); } /// <java-name> /// setDoubleParameter /// </java-name> [Dot42.DexImport("setDoubleParameter", "(Ljava/lang/String;D)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetDoubleParameter(string name, double value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// getBooleanParameter /// </java-name> [Dot42.DexImport("getBooleanParameter", "(Ljava/lang/String;Z)Z", AccessFlags = 1)] public virtual bool GetBooleanParameter(string name, bool defaultValue) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// setBooleanParameter /// </java-name> [Dot42.DexImport("setBooleanParameter", "(Ljava/lang/String;Z)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public virtual global::Org.Apache.Http.Params.IHttpParams SetBooleanParameter(string name, bool value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// isParameterTrue /// </java-name> [Dot42.DexImport("isParameterTrue", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterTrue(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterFalse /// </java-name> [Dot42.DexImport("isParameterFalse", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool IsParameterFalse(string name) /* MethodBuilder.Create */ { return default(bool); } [Dot42.DexImport("org/apache/http/params/HttpParams", "getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1025)] public virtual object GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(object); } [Dot42.DexImport("org/apache/http/params/HttpParams", "setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)] public virtual global::Org.Apache.Http.Params.IHttpParams Copy() /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(global::Org.Apache.Http.Params.IHttpParams); } [Dot42.DexImport("org/apache/http/params/HttpParams", "removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1025)] public virtual bool RemoveParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */ { return default(bool); } } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters. Protocol parameters may be linked together to form a hierarchy. If a particular parameter value has not been explicitly defined in the collection itself, its value will be drawn from the parent collection of parameters.</para><para><para></para><para></para><title>Revision:</title><para>610464 </para></para> /// </summary> /// <java-name> /// org/apache/http/params/BasicHttpParams /// </java-name> [Dot42.DexImport("org/apache/http/params/BasicHttpParams", AccessFlags = 49)] public sealed partial class BasicHttpParams : global::Org.Apache.Http.Params.AbstractHttpParams, global::Java.Io.ISerializable, global::Java.Lang.ICloneable /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public BasicHttpParams() /* MethodBuilder.Create */ { } /// <java-name> /// getParameter /// </java-name> [Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/Object;", AccessFlags = 1)] public override object GetParameter(string name) /* MethodBuilder.Create */ { return default(object); } /// <java-name> /// setParameter /// </java-name> [Dot42.DexImport("setParameter", "(Ljava/lang/String;Ljava/lang/Object;)Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams SetParameter(string name, object value) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <summary> /// <para>Removes the parameter with the specified name.</para><para></para> /// </summary> /// <returns> /// <para>true if the parameter existed and has been removed, false else. </para> /// </returns> /// <java-name> /// removeParameter /// </java-name> [Dot42.DexImport("removeParameter", "(Ljava/lang/String;)Z", AccessFlags = 1)] public override bool RemoveParameter(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Assigns the value to all the parameter with the given names</para><para></para> /// </summary> /// <java-name> /// setParameters /// </java-name> [Dot42.DexImport("setParameters", "([Ljava/lang/String;Ljava/lang/Object;)V", AccessFlags = 1)] public void SetParameters(string[] names, object value) /* MethodBuilder.Create */ { } /// <java-name> /// isParameterSet /// </java-name> [Dot42.DexImport("isParameterSet", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSet(string name) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isParameterSetLocally /// </java-name> [Dot42.DexImport("isParameterSetLocally", "(Ljava/lang/String;)Z", AccessFlags = 1)] public bool IsParameterSetLocally(string name) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Removes all parameters from this collection. </para> /// </summary> /// <java-name> /// clear /// </java-name> [Dot42.DexImport("clear", "()V", AccessFlags = 1)] public void Clear() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates a copy of these parameters. The implementation here instantiates BasicHttpParams, then calls copyParams(HttpParams) to populate the copy.</para><para></para> /// </summary> /// <returns> /// <para>a new set of params holding a copy of the <b>local</b> parameters in this object. </para> /// </returns> /// <java-name> /// copy /// </java-name> [Dot42.DexImport("copy", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1)] public override global::Org.Apache.Http.Params.IHttpParams Copy() /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Params.IHttpParams); } /// <java-name> /// clone /// </java-name> [Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)] public object Clone() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Copies the locally defined parameters to the argument parameters. This method is called from copy().</para><para></para> /// </summary> /// <java-name> /// copyParams /// </java-name> [Dot42.DexImport("copyParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 4)] internal void CopyParams(global::Org.Apache.Http.Params.IHttpParams target) /* MethodBuilder.Create */ { } } }
/* Copyright (c) 2012 Eran Meir Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Text; using C5; namespace Sufa { [Serializable] public class SuffixArray { private const int EOC = int.MaxValue; private int[] m_sa; private int[] m_isa; private int[] m_lcp; private C5.HashDictionary<char, int> m_chainHeadsDict = new HashDictionary<char, int>(new CharComparer()); private List<Chain> m_chainStack = new List<Chain>(); private ArrayList<Chain> m_subChains = new ArrayList<Chain>(); private int m_nextRank = 1; private string m_str; public int Length { get { return m_sa.Length; } } public int this[int index] { get { return m_sa[index]; } } public int[] Lcp { get { return m_lcp; } } public string Str { get { return m_str; } } /// /// <summary> /// Build a suffix array from string str /// </summary> /// <param name="str">A string for which to build a suffix array with LCP information</param> /// <param name="buildLcps">Also build LCP array</param> public SuffixArray(string str) : this(str, true) { } /// /// <summary> /// Build a suffix array from string str /// </summary> /// <param name="str">A string for which to build a suffix array</param> /// <param name="buildLcps">Also calculate LCP information</param> public SuffixArray(string str, bool buildLcps) { m_str = str; if (m_str == null) { m_str = ""; } m_sa = new int[m_str.Length]; m_isa = new int[m_str.Length]; FormInitialChains(); BuildSuffixArray(); if (buildLcps) BuildLcpArray(); } /// /// <summary>Find the index of a substring </summary> /// <param name="substr">Substring to look for</param> /// <returns>First index in the original string. -1 if not found</returns> public int IndexOf(string substr) { int l = 0; int r = m_sa.Length; int m = -1; if ((substr == null) || (substr.Length == 0)) { return -1; } // Binary search for substring while (r > l) { m = (l + r) / 2; if (m_str.Substring(m_sa[m]).CompareTo(substr) < 0) { l = m + 1; } else { r = m; } } if ((l == r) && (l < m_str.Length) && (m_str.Substring(m_sa[l]).StartsWith(substr))) { return m_sa[l]; } else { return -1; } } private void FormInitialChains() { // Link all suffixes that have the same first character FindInitialChains(); SortAndPushSubchains(); } private void FindInitialChains() { // Scan the string left to right, keeping rightmost occurences of characters as the chain heads for (int i = 0; i < m_str.Length; i++) { if (m_chainHeadsDict.Contains(m_str[i])) { m_isa[i] = m_chainHeadsDict[m_str[i]]; } else { m_isa[i] = EOC; } m_chainHeadsDict[m_str[i]] = i; } // Prepare chains to be pushed to stack foreach (int headIndex in m_chainHeadsDict.Values) { Chain newChain = new Chain(m_str); newChain.head = headIndex; newChain.length = 1; m_subChains.Add(newChain); } } private void SortAndPushSubchains() { m_subChains.Sort(); for (int i = m_subChains.Count - 1; i >= 0; i--) { m_chainStack.Add(m_subChains[i]); } } private void BuildSuffixArray() { while (m_chainStack.Count > 0) { // Pop chain Chain chain = m_chainStack[m_chainStack.Count - 1]; m_chainStack.RemoveAt(m_chainStack.Count - 1); if (m_isa[chain.head] == EOC) { // Singleton (A chain that contain only 1 suffix) RankSuffix(chain.head); } else { //RefineChains(chain); RefineChainWithInductionSorting(chain); } } } private void RefineChains(Chain chain) { m_chainHeadsDict.Clear(); m_subChains.Clear(); while (chain.head != EOC) { int nextIndex = m_isa[chain.head]; if (chain.head + chain.length > m_str.Length - 1) { RankSuffix(chain.head); } else { ExtendChain(chain); } chain.head = nextIndex; } // Keep stack sorted SortAndPushSubchains(); } private void ExtendChain(Chain chain) { char sym = m_str[chain.head + chain.length]; if (m_chainHeadsDict.Contains(sym)) { // Continuation of an existing chain, this is the leftmost // occurence currently known (others may come up later) m_isa[m_chainHeadsDict[sym]] = chain.head; m_isa[chain.head] = EOC; } else { // This is the beginning of a new subchain m_isa[chain.head] = EOC; Chain newChain = new Chain(m_str); newChain.head = chain.head; newChain.length = chain.length + 1; m_subChains.Add(newChain); } // Save index in case we find a continuation of this chain m_chainHeadsDict[sym] = chain.head; } private void RefineChainWithInductionSorting(Chain chain) { // TODO - refactor/beautify some ArrayList<SuffixRank> notedSuffixes = new ArrayList<SuffixRank>(); m_chainHeadsDict.Clear(); m_subChains.Clear(); while (chain.head != EOC) { int nextIndex = m_isa[chain.head]; if (chain.head + chain.length > m_str.Length - 1) { // If this substring reaches end of string it cannot be extended. // At this point it's the first in lexicographic order so it's safe // to just go ahead and rank it. RankSuffix(chain.head); } else if (m_isa[chain.head + chain.length] < 0) { SuffixRank sr = new SuffixRank(); sr.head = chain.head; sr.rank = -m_isa[chain.head + chain.length]; notedSuffixes.Add(sr); } else { ExtendChain(chain); } chain.head = nextIndex; } // Keep stack sorted SortAndPushSubchains(); SortAndRankNotedSuffixes(notedSuffixes); } private void SortAndRankNotedSuffixes(ArrayList<SuffixRank> notedSuffixes) { notedSuffixes.Sort(new SuffixRankComparer()); // Rank sorted noted suffixes for (int i = 0; i < notedSuffixes.Count; ++i) { RankSuffix(notedSuffixes[i].head); } } private void RankSuffix(int index) { // We use the ISA to hold both ranks and chain links, so we differentiate by setting // the sign. m_isa[index] = -m_nextRank; m_sa[m_nextRank - 1] = index; m_nextRank++; } private void BuildLcpArray() { m_lcp = new int[m_sa.Length + 1]; m_lcp[0] = m_lcp[m_sa.Length] = 0; for (int i = 1; i < m_sa.Length; i++) { m_lcp[i] = CalcLcp(m_sa[i - 1], m_sa[i]); } } private int CalcLcp(int i, int j) { int lcp; int maxIndex = m_str.Length - Math.Max(i, j); // Out of bounds prevention for (lcp = 0; (lcp < maxIndex) && (m_str[i + lcp] == m_str[j + lcp]); lcp++) ; return lcp; } } #region HelperClasses [Serializable] internal class Chain : IComparable<Chain> { public int head; public int length; private string m_str; public Chain(string str) { m_str = str; } public int CompareTo(Chain other) { return m_str.Substring(head, length).CompareTo(m_str.Substring(other.head, other.length)); } public override string ToString() { return m_str.Substring(head, length); } } [Serializable] internal class CharComparer : System.Collections.Generic.EqualityComparer<char> { public override bool Equals(char x, char y) { return x.Equals(y); } public override int GetHashCode(char obj) { return obj.GetHashCode(); } } [Serializable] internal struct SuffixRank { public int head; public int rank; } [Serializable] internal class SuffixRankComparer : IComparer<SuffixRank> { public bool Equals(SuffixRank x, SuffixRank y) { return x.rank.Equals(y.rank); } public int Compare(SuffixRank x, SuffixRank y) { return x.rank.CompareTo(y.rank); } } #endregion }
/* * C# port of Mozilla Character Set Detector * https://code.google.com/p/chardetsharp/ * * Original Mozilla License Block follows * */ #region License Block // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // The Original Code is Mozilla Universal charset detector code. // // The Initial Developer of the Original Code is // Netscape Communications Corporation. // Portions created by the Initial Developer are Copyright (C) 2001 // the Initial Developer. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms of // either the GNU General Public License Version 2 or later (the "GPL"), or // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), // in which case the provisions of the GPL or the LGPL are applicable instead // of those above. If you wish to allow use of your version of this file only // under the terms of either the GPL or the LGPL, and not to allow others to // use your version of this file under the terms of the MPL, indicate your // decision by deleting the provisions above and replace them with the notice // and other provisions required by the GPL or the LGPL. If you do not delete // the provisions above, a recipient may use your version of this file under // the terms of any one of the MPL, the GPL or the LGPL. #endregion namespace Cloney.Core.CharsetDetection { internal partial class SequenceModel { //***************************************************************** // 255: Control characters that usually does not exist in any text // 254: Carriage/Return // 253: symbol (punctuation) that does not belong to word // 252: 0 - 9 //***************************************************************** static readonly byte[] Latin2_HungarianCharToOrderMap = new byte[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47, 46, 71, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253, 253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8, 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253, 159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174, 175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190, 191,192,193,194,195,196,197, 75,198,199,200,201,202,203,204,205, 79,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220, 221, 51, 81,222, 78,223,224,225,226, 44,227,228,229, 61,230,231, 232,233,234, 58,235, 66, 59,236,237,238, 60, 69, 63,239,240,241, 82, 14, 74,242, 70, 80,243, 72,244, 15, 83, 77, 84, 30, 76, 85, 245,246,247, 25, 73, 42, 24,248,249,250, 31, 56, 29,251,252,253, }; static readonly byte[] win1250HungarianCharToOrderMap = new byte[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47, 46, 72, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253, 253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8, 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253, 161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176, 177,178,179,180, 78,181, 69,182,183,184,185,186,187,188,189,190, 191,192,193,194,195,196,197, 76,198,199,200,201,202,203,204,205, 81,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220, 221, 51, 83,222, 80,223,224,225,226, 44,227,228,229, 61,230,231, 232,233,234, 58,235, 66, 59,236,237,238, 60, 70, 63,239,240,241, 84, 14, 75,242, 71, 82,243, 73,244, 15, 85, 79, 86, 30, 77, 87, 245,246,247, 25, 74, 42, 24,248,249,250, 31, 56, 29,251,252,253, }; //Model Table: //total sequences: 100% //first 512 sequences: 94.7368% //first 1024 sequences:5.2623% //rest sequences: 0.8894% //negative sequences: 0.0009% static readonly byte[] HungarianLangModel = new byte[] { 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,2,3,3,1,1,2,2,2,2,2,1,2, 3,2,2,3,3,3,3,3,2,3,3,3,3,3,3,1,2,3,3,3,3,2,3,3,1,1,3,3,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0, 3,2,1,3,3,3,3,3,2,3,3,3,3,3,1,1,2,3,3,3,3,3,3,3,1,1,3,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,1,1,2,3,3,3,1,3,3,3,3,3,1,3,3,2,2,0,3,2,3, 0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,3,3,2,3,3,2,2,3,2,3,2,0,3,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,1,2,3,2,2,3,1,2,3,3,2,2,0,3,3,3, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,3,0,2,3,2, 0,0,0,1,1,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,2,1,3,2,2,3,2,1,3,2,2,1,0,3,3,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,2,2,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,3,2,2,3,1,1,3,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,1,3,3,3,3,3,2,2,1,3,3,3,0,1,1,2, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,2,0,3,2,3, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,1,3,2,2,2,3,1,1,3,3,1,1,0,3,3,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,1,2,3,2,2,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,2,2,3,1,3,3,2,2,1,3,3,3,1,1,3,1,2,3,2,3,2,2,2,1,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,2,2,3,2,1,0,3,2,0,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,1,0,3,3,3,3,0,2,3,0,0,2,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,2,2,3,3,2,2,2,2,3,3,0,1,2,3,2,3,2,2,3,2,1,2,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0, 3,3,3,3,3,3,1,2,3,3,3,2,1,2,3,3,2,2,2,3,2,3,3,1,3,3,1,1,0,2,3,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,1,2,2,2,2,3,3,3,1,1,1,3,3,1,1,3,1,1,3,2,1,2,3,1,1,0,2,2,2, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,1,2,1,1,3,3,1,1,1,1,3,3,1,1,2,2,1,2,1,1,2,2,1,1,0,2,2,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,1,1,2,1,1,3,3,1,0,1,1,3,3,2,0,1,1,2,3,1,0,2,2,1,0,0,1,3,2, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,2,1,3,3,3,3,3,1,2,3,2,3,3,2,1,1,3,2,3,2,1,2,2,0,1,2,1,0,0,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,2,2,2,2,3,1,2,2,1,1,3,3,0,3,2,1,2,3,2,1,3,3,1,1,0,2,1,3, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,3,3,2,2,2,3,2,3,3,3,2,1,1,3,3,1,1,1,2,2,3,2,3,2,2,2,1,0,2,2,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 1,0,0,3,3,3,3,3,0,0,3,3,2,3,0,0,0,2,3,3,1,0,1,2,0,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,2,3,3,3,3,3,1,2,3,3,2,2,1,1,0,3,3,2,2,1,2,2,1,0,2,2,0,1,1,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,2,2,1,3,1,2,3,3,2,2,1,1,2,2,1,1,1,1,3,2,1,1,1,1,2,1,0,1,2,1, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 2,3,3,1,1,1,1,1,3,3,3,0,1,1,3,3,1,1,1,1,1,2,2,0,3,1,1,2,0,2,1,1, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0, 3,1,0,1,2,1,2,2,0,1,2,3,1,2,0,0,0,2,1,1,1,1,1,2,0,0,1,1,0,0,0,0, 1,2,1,2,2,2,1,2,1,2,0,2,0,2,2,1,1,2,1,1,2,1,1,1,0,1,0,0,0,1,1,0, 1,1,1,2,3,2,3,3,0,1,2,2,3,1,0,1,0,2,1,2,2,0,1,1,0,0,1,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,3,3,2,2,1,0,0,3,2,3,2,0,0,0,1,1,3,0,0,1,1,0,0,2,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,2,2,3,3,1,0,1,3,2,3,1,1,1,0,1,1,1,1,1,3,1,0,0,2,2,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,1,2,2,2,1,0,1,2,3,3,2,0,0,0,2,1,1,1,2,1,1,1,0,1,1,1,0,0,0, 1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,2,1,1,1,1,1,1,0,1,1,1,0,0,1,1, 3,2,2,1,0,0,1,1,2,2,0,3,0,1,2,1,1,0,0,1,1,1,0,1,1,1,1,0,2,1,1,1, 2,2,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,1,1,2,3,1,1,1,1,1,1,1,1,1,0,1, 2,3,3,0,1,0,0,0,3,3,1,0,0,1,2,2,1,0,0,0,0,2,0,0,1,1,1,0,2,1,1,1, 2,1,1,1,1,1,1,2,1,1,0,1,1,0,1,1,1,0,1,2,1,1,0,1,1,1,1,1,1,1,0,1, 2,3,3,0,1,0,0,0,2,2,0,0,0,0,1,2,2,0,0,0,0,1,0,0,1,1,0,0,2,0,1,0, 2,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1, 3,2,2,0,1,0,1,0,2,3,2,0,0,1,2,2,1,0,0,1,1,1,0,0,2,1,0,1,2,2,1,1, 2,1,1,1,1,1,1,2,1,1,1,1,1,1,0,2,1,0,1,1,0,1,1,1,0,1,1,2,1,1,0,1, 2,2,2,0,0,1,0,0,2,2,1,1,0,0,2,1,1,0,0,0,1,2,0,0,2,1,0,0,2,1,1,1, 2,1,1,1,1,2,1,2,1,1,1,2,2,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1, 1,2,3,0,0,0,1,0,3,2,1,0,0,1,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,2,1, 1,1,0,0,0,1,0,1,1,1,1,1,2,0,0,1,0,0,0,2,0,0,1,1,1,1,1,1,1,1,0,1, 3,0,0,2,1,2,2,1,0,0,2,1,2,2,0,0,0,2,1,1,1,0,1,1,0,0,1,1,2,0,0,0, 1,2,1,2,2,1,1,2,1,2,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,0,0,1, 1,3,2,0,0,0,1,0,2,2,2,0,0,0,2,2,1,0,0,0,0,3,1,1,1,1,0,0,2,1,1,1, 2,1,0,1,1,1,0,1,1,1,1,1,1,1,0,2,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1, 2,3,2,0,0,0,1,0,2,2,0,0,0,0,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,1,0, 2,1,1,1,1,2,1,2,1,2,0,1,1,1,0,2,1,1,1,2,1,1,1,1,0,1,1,1,1,1,0,1, 3,1,1,2,2,2,3,2,1,1,2,2,1,1,0,1,0,2,2,1,1,1,1,1,0,0,1,1,0,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,0,0,0,0,0,2,2,0,0,0,0,2,2,1,0,0,0,1,1,0,0,1,2,0,0,2,1,1,1, 2,2,1,1,1,2,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,1,1,0,1,2,1,1,1,0,1, 1,0,0,1,2,3,2,1,0,0,2,0,1,1,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0, 1,2,1,2,1,2,1,1,1,2,0,2,1,1,1,0,1,2,0,0,1,1,1,0,0,0,0,0,0,0,0,0, 2,3,2,0,0,0,0,0,1,1,2,1,0,0,1,1,1,0,0,0,0,2,0,0,1,1,0,0,2,1,1,1, 2,1,1,1,1,1,1,2,1,0,1,1,1,1,0,2,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1, 1,2,2,0,1,1,1,0,2,2,2,0,0,0,3,2,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0, 1,1,0,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,0,0,1,1,1,0,1,0,1, 2,1,0,2,1,1,2,2,1,1,2,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,0,0,0, 1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,0, 1,2,3,0,0,0,1,0,2,2,0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,2,0,1,0, 2,1,1,1,1,1,0,2,0,0,0,1,2,1,1,1,1,0,1,2,0,1,0,1,0,1,1,1,0,1,0,1, 2,2,2,0,0,0,1,0,2,1,2,0,0,0,1,1,2,0,0,0,0,1,0,0,1,1,0,0,2,1,0,1, 2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1, 1,2,2,0,0,0,1,0,2,2,2,0,0,0,1,1,0,0,0,0,0,1,1,0,2,0,0,1,1,1,0,1, 1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1, 1,0,0,1,0,1,2,1,0,0,1,1,1,2,0,0,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0, 0,2,1,2,1,1,1,1,1,2,0,2,0,1,1,0,1,2,1,0,1,1,1,0,0,0,0,0,0,1,0,0, 2,1,1,0,1,2,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,2,1,0,1, 2,2,1,1,1,1,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,0,1,0,1,1,1,1,1,0,1, 1,2,2,0,0,0,0,0,1,1,0,0,0,0,2,1,0,0,0,0,0,2,0,0,2,2,0,0,2,0,0,1, 2,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1, 1,1,2,0,0,3,1,0,2,1,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,1,0, 1,2,1,0,1,1,1,2,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,1,0,0, 2,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,2,0,0,0, 2,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,1,0,1, 2,1,1,1,2,1,1,1,0,1,1,2,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,0,1,1,1,1,1,0,0,1,1,2,1,0,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,0,0, 1,2,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0, 2,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,2,0,0,1,0,0,1,0,1,0,0,0, 0,1,1,1,1,1,1,1,1,2,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,1,0,0,2,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0, 0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0, 0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,1,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0, 2,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,1,1,1,1,0,1,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0, }; public static readonly SequenceModel Latin2HungarianModel = new SequenceModel( Latin2_HungarianCharToOrderMap, HungarianLangModel, 0.947368f, true, "ISO-8859-2" ); public static readonly SequenceModel Win1250HungarianModel = new SequenceModel( win1250HungarianCharToOrderMap, HungarianLangModel, 0.947368f, true, "windows-1250" ); } }
using System; using System.ComponentModel; using System.IO; using System.Text; using System.Windows.Forms; using FileHelpers; namespace FileHelpersSamples { /// <summary> /// Process a number of records showing times /// of the various engines. /// </summary> public class frmTimming : frmFather { private Button button1; private Button cmdCreateFile; private NumericUpDown txtRecords; private Label label2; private Label label1; private Label lblSize; private Button cmdRun; private Label lblTime; private Label label4; private Label label3; private Label lblTimeAsync; /// <summary> /// Required designer variable. /// </summary> private Container components = null; public frmTimming() { // // Required for Windows Form Designer support // InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cmdCreateFile = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.cmdRun = new System.Windows.Forms.Button(); this.txtRecords = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.lblSize = new System.Windows.Forms.Label(); this.lblTime = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.lblTimeAsync = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize) (this.txtRecords)).BeginInit(); this.SuspendLayout(); // // pictureBox3 // // // cmdCreateFile // this.cmdCreateFile.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)), ((System.Byte) (0)), ((System.Byte) (110))); this.cmdCreateFile.Font = new System.Drawing.Font("Tahoma", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.cmdCreateFile.ForeColor = System.Drawing.Color.Gainsboro; this.cmdCreateFile.Location = new System.Drawing.Point(288, 72); this.cmdCreateFile.Name = "cmdCreateFile"; this.cmdCreateFile.Size = new System.Drawing.Size(168, 32); this.cmdCreateFile.TabIndex = 4; this.cmdCreateFile.Text = "Create Temp File ->"; this.cmdCreateFile.Click += new System.EventHandler(this.cmdCreateFile_Click); // // button1 // this.button1.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)), ((System.Byte) (0)), ((System.Byte) (110))); this.button1.Font = new System.Drawing.Font("Tahoma", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.button1.ForeColor = System.Drawing.Color.Gainsboro; this.button1.Location = new System.Drawing.Point(128, 232); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(192, 32); this.button1.TabIndex = 6; this.button1.Text = "Exit"; this.button1.Click += new System.EventHandler(this.CloseButton_Click); // // cmdRun // this.cmdRun.BackColor = System.Drawing.Color.FromArgb(((System.Byte) (0)), ((System.Byte) (0)), ((System.Byte) (110))); this.cmdRun.Enabled = false; this.cmdRun.Font = new System.Drawing.Font("Tahoma", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.cmdRun.ForeColor = System.Drawing.Color.Gainsboro; this.cmdRun.Location = new System.Drawing.Point(288, 160); this.cmdRun.Name = "cmdRun"; this.cmdRun.Size = new System.Drawing.Size(168, 32); this.cmdRun.TabIndex = 7; this.cmdRun.Text = "Run Test ->"; this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click); // // txtRecords // this.txtRecords.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.txtRecords.Increment = new System.Decimal(new int[] { 1000, 0, 0, 0 }); this.txtRecords.Location = new System.Drawing.Point(184, 77); this.txtRecords.Maximum = new System.Decimal(new int[] { 10000000, 0, 0, 0 }); this.txtRecords.Name = "txtRecords"; this.txtRecords.Size = new System.Drawing.Size(88, 23); this.txtRecords.TabIndex = 8; this.txtRecords.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.txtRecords.Value = new System.Decimal(new int[] { 10000, 0, 0, 0 }); this.txtRecords.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtRecords_KeyDown); this.txtRecords.ValueChanged += new System.EventHandler(this.txtRecords_ValueChanged); // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(16, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 16); this.label2.TabIndex = 9; this.label2.Text = "Number of records"; // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(16, 112); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 16); this.label1.TabIndex = 10; this.label1.Text = "File Size:"; // // lblSize // this.lblSize.BackColor = System.Drawing.Color.Transparent; this.lblSize.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.lblSize.ForeColor = System.Drawing.Color.White; this.lblSize.Location = new System.Drawing.Point(152, 112); this.lblSize.Name = "lblSize"; this.lblSize.Size = new System.Drawing.Size(120, 16); this.lblSize.TabIndex = 11; this.lblSize.TextAlign = System.Drawing.ContentAlignment.TopRight; // // lblTime // this.lblTime.BackColor = System.Drawing.Color.Transparent; this.lblTime.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.lblTime.ForeColor = System.Drawing.Color.White; this.lblTime.Location = new System.Drawing.Point(136, 168); this.lblTime.Name = "lblTime"; this.lblTime.Size = new System.Drawing.Size(136, 16); this.lblTime.TabIndex = 13; this.lblTime.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label4 // this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.label4.ForeColor = System.Drawing.Color.White; this.label4.Location = new System.Drawing.Point(8, 168); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(96, 16); this.label4.TabIndex = 12; this.label4.Text = "Process Time:"; // // label3 // this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(8, 192); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(136, 16); this.label3.TabIndex = 14; this.label3.Text = "Async Process Time:"; // // lblTimeAsync // this.lblTimeAsync.BackColor = System.Drawing.Color.Transparent; this.lblTimeAsync.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0))); this.lblTimeAsync.ForeColor = System.Drawing.Color.White; this.lblTimeAsync.Location = new System.Drawing.Point(128, 192); this.lblTimeAsync.Name = "lblTimeAsync"; this.lblTimeAsync.Size = new System.Drawing.Size(144, 16); this.lblTimeAsync.TabIndex = 15; this.lblTimeAsync.TextAlign = System.Drawing.ContentAlignment.TopRight; // // frmTimming // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(466, 304); this.Controls.Add(this.lblTimeAsync); this.Controls.Add(this.label3); this.Controls.Add(this.lblTime); this.Controls.Add(this.label4); this.Controls.Add(this.lblSize); this.Controls.Add(this.label1); this.Controls.Add(this.label2); this.Controls.Add(this.txtRecords); this.Controls.Add(this.cmdRun); this.Controls.Add(this.button1); this.Controls.Add(this.cmdCreateFile); this.MaximizeBox = false; this.Name = "frmTimming"; this.Text = "FileHelpers Library - Time And Stress Tests"; this.Closed += new System.EventHandler(this.frmTimming_Closed); this.Controls.SetChildIndex(this.cmdCreateFile, 0); this.Controls.SetChildIndex(this.button1, 0); this.Controls.SetChildIndex(this.cmdRun, 0); this.Controls.SetChildIndex(this.txtRecords, 0); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.lblSize, 0); this.Controls.SetChildIndex(this.label4, 0); this.Controls.SetChildIndex(this.lblTime, 0); this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.lblTimeAsync, 0); ((System.ComponentModel.ISupportInitialize) (this.txtRecords)).EndInit(); this.ResumeLayout(false); } #endregion private void CloseButton_Click(object sender, EventArgs e) { this.Close(); } /// <summary> /// Created sample data for processing /// </summary> private string mSourceString; /// <summary> /// Create a set of data for time testing /// </summary> private void cmdCreateFile_Click(object sender, EventArgs e) { cmdCreateFile.Enabled = false; cmdRun.Enabled = false; this.Cursor = Cursors.WaitCursor; mSourceString = TestData.CreateDelimitedString((int) txtRecords.Value); lblSize.Text = (mSourceString.Length/1024).ToString() + " Kb"; this.Cursor = Cursors.Default; cmdCreateFile.Enabled = true; cmdRun.Enabled = true; } /// <summary> /// Run the timing test for reading the records /// </summary> private void cmdRun_Click(object sender, EventArgs e) { cmdCreateFile.Enabled = false; cmdRun.Enabled = false; this.Cursor = Cursors.WaitCursor; lblTimeAsync.Text = ""; lblTime.Text = ""; Application.DoEvents(); RunTest(); RunTestAsync(); this.Cursor = Cursors.Default; cmdCreateFile.Enabled = true; cmdRun.Enabled = true; } private void RunTest() { long start = DateTime.Now.Ticks; FileHelperEngine engine = new FileHelperEngine(typeof (OrdersVerticalBar)); engine.ReadString(mSourceString); long end = DateTime.Now.Ticks; TimeSpan span = new TimeSpan(end - start); lblTime.Text = Math.Round(span.TotalSeconds, 4).ToString() + " sec."; Application.DoEvents(); } private void RunTestAsync() { long start = DateTime.Now.Ticks; FileHelperAsyncEngine engine = new FileHelperAsyncEngine(typeof (OrdersVerticalBar)); engine.BeginReadString(mSourceString); while (engine.ReadNext() != null) {} long end = DateTime.Now.Ticks; TimeSpan span = new TimeSpan(end - start); lblTimeAsync.Text = Math.Round(span.TotalSeconds, 4).ToString() + " sec."; Application.DoEvents(); } /// <summary> /// On close check for my temp file and delete it /// </summary> private void frmTimming_Closed(object sender, EventArgs e) { if (File.Exists("tempFile.tmp")) File.Delete("tempFile.tmp"); } private void txtRecords_ValueChanged(object sender, EventArgs e) { ResetButtons(); } private void ResetButtons() { cmdRun.Enabled = false; lblSize.Text = ""; lblTimeAsync.Text = ""; lblTime.Text = ""; } private void txtRecords_KeyDown(object sender, KeyEventArgs e) { ResetButtons(); } } }
#region License, Terms and Conditions // // Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono // Written by Atif Aziz ([email protected]) // Copyright (c) 2005 Atif Aziz. All rights reserved. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the Free // Software Foundation; either version 2.1 of the License, or (at your option) // any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more // details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #endregion namespace EZOper.NetSiteUtilities.Jayrock { #region Imports using System; using System.Collections; #endregion /// <summary> /// An unordered collection of name/value pairs. /// </summary> /// <remarks> /// <para> /// Althought the collection should be considered unordered by the user, /// the implementation does internally try to remember the order in which /// the keys were added in order facilitate human-readability as in when /// an instance is rendered as text.</para> /// <para> /// Public Domain 2002 JSON.org, ported to C# by Are Bjolseth (teleplan.no) /// and re-adapted by Atif Aziz (www.raboof.com)</para> /// </remarks> [ Serializable ] public class JsonObject : DictionaryBase, IJsonImportable, IJsonExportable { private ArrayList _nameIndexList; [ NonSerialized ] private IList _readOnlyNameIndexList; public JsonObject() {} /// <summary> /// Construct a JObject from a IDictionary /// </summary> public JsonObject(IDictionary members) { // FIXME: Use IDictionaryEnumerator.Entry instead and enumerate manually (faster and more robust). // See comment in DictionaryExporter for details. foreach (DictionaryEntry entry in members) { if (entry.Key == null) throw new InvalidMemberException(); InnerHashtable.Add(entry.Key.ToString(), entry.Value); } _nameIndexList = new ArrayList(members.Keys); } public JsonObject(string[] keys, object[] values) { int keyCount = keys == null ? 0 : keys.Length; int valueCount = values == null ? 0 : values.Length; int count = Math.Max(keyCount, valueCount); string key = string.Empty; for (int i = 0; i < count; i++) { if (i < keyCount) key = Mask.NullString(keys[i]); Accumulate(key, i < valueCount ? values[i] : null); } } public virtual object this[string key] { get { return InnerHashtable[key]; } set { Put(key, value); } } public virtual bool HasMembers { get { return Count > 0; } } private ArrayList NameIndexList { get { if (_nameIndexList == null) _nameIndexList = new ArrayList(); return _nameIndexList; } } /// <summary> /// Accumulate values under a key. It is similar to the Put method except /// that if there is already an object stored under the key then a /// JArray is stored under the key to hold all of the accumulated values. /// If there is already a JArray, then the new value is appended to it. /// In contrast, the Put method replaces the previous value. /// </summary> public virtual JsonObject Accumulate(string name, object value) { if (name == null) throw new ArgumentNullException("name"); object current = InnerHashtable[name]; if (current == null) { Put(name, value); } else { IList values = current as IList; if (values != null) { values.Add(value); } else { values = new JsonArray(); values.Add(current); values.Add(value); Put(name, values); } } return this; } /// <summary> /// Put a key/value pair in the JObject. If the value is null, /// then the key will be removed from the JObject if it is present. /// </summary> public virtual JsonObject Put(string name, object value) { if (name == null) throw new ArgumentNullException("name"); Dictionary[name] = value; return this; } public virtual bool Contains(string name) { if (name == null) throw new ArgumentNullException("name"); return Dictionary.Contains(name); } public virtual void Remove(string name) { if (name == null) throw new ArgumentNullException("name"); Dictionary.Remove(name); } public virtual ICollection Names { get { if (_readOnlyNameIndexList == null) _readOnlyNameIndexList = ArrayList.ReadOnly(NameIndexList); return _readOnlyNameIndexList; } } /// <summary> /// Produce a JArray containing the names of the elements of this /// JObject. /// </summary> public virtual JsonArray GetNamesArray() { JsonArray names = new JsonArray(); ListNames(names); return names; } public virtual void ListNames(IList list) { if (list == null) throw new ArgumentNullException("list"); foreach (string name in NameIndexList) list.Add(name); } /// <summary> /// Overridden to return a JSON formatted object as a string. /// </summary> public override string ToString() { JsonTextWriter writer = new JsonTextWriter(); Export(writer); return writer.ToString(); } public void Export(JsonWriter writer) { Export(new ExportContext(), writer); } void IJsonExportable.Export(ExportContext context, JsonWriter writer) { Export(context, writer); } protected virtual void Export(ExportContext context, JsonWriter writer) { if (context == null) throw new ArgumentNullException("context"); if (writer == null) throw new ArgumentNullException("writer"); writer.WriteStartObject(); foreach (string name in NameIndexList) { writer.WriteMember(name); context.Export(InnerHashtable[name], writer); } writer.WriteEndObject(); } /// <remarks> /// This method is not exception-safe. If an error occurs while /// reading then the object may be partially imported. /// </remarks> public void Import(JsonReader reader) { Import(new ImportContext(), reader); } void IJsonImportable.Import(ImportContext context, JsonReader reader) { Import(context, reader); } protected virtual void Import(ImportContext context, JsonReader reader) { if (context == null) throw new ArgumentNullException("context"); if (reader == null) throw new ArgumentNullException("reader"); // FIXME: Consider making this method exception-safe. // Right now this is a problem because of reliance on // DictionaryBase. Clear(); reader.ReadToken(JsonTokenClass.Object); while (reader.TokenClass != JsonTokenClass.EndObject) Put(reader.ReadMember(), context.Import(reader)); reader.Read(); } protected override void OnValidate(object key, object value) { base.OnValidate(key, value); if (key == null) throw new ArgumentNullException("key"); if (!(key is string)) throw new ArgumentException("key", string.Format("The key cannot be of the supplied type {0}. It must be typed System.String.", key.GetType().FullName)); } protected override void OnInsert(object key, object value) { // // NOTE: OnInsert leads one to believe that keys are ordered in the // base dictionary in that they can be inserted somewhere in the // middle. However, the base implementation only calls OnInsert // during the Add operation, so we known it is safe here to simply // add the new key at the end of the name list. // NameIndexList.Add(key); } protected override void OnSet(object key, object oldValue, object newValue) { // // NOTE: OnSet is called when the base dictionary is modified via // the indexer. We need to trap this and detect when a new key is // being added via the indexer. If the old value is null for the // key, then there is a big chance it is a new key. But just to be // sure, we also check out key index if it does not already exist. // Finally, we just delegate to OnInsert. In effect, we're // converting OnSet to OnInsert where needed. Ideally, the base // implementation would have done this for. // if (oldValue == null && !NameIndexList.Contains(key)) OnInsert(key, newValue); } protected override void OnRemove(object key, object value) { NameIndexList.Remove(key); } protected override void OnClear() { NameIndexList.Clear(); } } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Runtime.InteropServices; /// <summary> /// ModifyRecipientRow request buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ModifyRecipientRow : ISerializable { /// <summary> /// This value specifies the ID of the recipient row. /// </summary> public uint RowId; /// <summary> /// 8-bit enumeration. The possible values for this enumeration are specified in [MS-OXCMSG]. /// This enumeration specifies the type of recipient. /// </summary> public byte RecipientType; /// <summary> /// This value specifies the size of the RecipientRow field. /// </summary> public ushort RecipientRowSize; /// <summary> /// RecipientRow structure. This field is present when the RecipientRowSize field is non-zero and is not present otherwise. /// The format of the RecipientRow structure is specified in [MS-OXCDATA]. /// The size of this field, in bytes, is specified by the RecipientRowSize field. /// </summary> public byte[] RecptRow; /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public byte[] Serialize() { int index = 0; byte[] serializedBuffer = new byte[this.Size()]; Array.Copy(BitConverter.GetBytes((uint)this.RowId), 0, serializedBuffer, index, sizeof(uint)); index += 4; serializedBuffer[index++] = this.RecipientType; Array.Copy(BitConverter.GetBytes((ushort)this.RecipientRowSize), 0, serializedBuffer, index, sizeof(ushort)); index += 2; Array.Copy(this.RecptRow, 0, serializedBuffer, index, this.RecipientRowSize); index += this.RecipientRowSize; return serializedBuffer; } /// <summary> /// Return the size of ModifyRecipientRow request buffer structure. /// </summary> /// <returns>The size of ModifyRecipientRow request buffer structure.</returns> public int Size() { // 7 indicates sizeof (UInt16) + sizeof (UInt32) + sizeof (byte) int size = sizeof(byte) * 7; if (this.RecipientRowSize > 0) { size += this.RecipientRowSize; } return size; } } /// <summary> /// RopModifyRecipients request buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopModifyRecipientsRequest : ISerializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0x0E. /// </summary> public byte RopId; /// <summary> /// This value specifies the logon associated with this operation. /// </summary> public byte LogonId; /// <summary> /// This index specifies the location in the Server Object Handle Table where the handle for the input Server Object is stored. /// </summary> public byte InputHandleIndex; /// <summary> /// This value specifies the number of structures in the RecipientColumns field. /// </summary> public ushort ColumnCount; /// <summary> /// Array of PropertyTag structures. The number of structures contained in this field is specified by the ColumnCount field. /// The format of the PropertyTag structure is specified in [MS-OXCDATA]. This field specifies the property values that can be included for each recipient row. /// </summary> public PropertyTag[] RecipientColumns; /// <summary> /// This value specifies the number of rows in the RecipientRows field. /// </summary> public ushort RowCount; /// <summary> /// List of ModifyRecipientRow structures. The number of structures contained in this field is specified by the RowCount field. /// </summary> public ModifyRecipientRow[] RecipientRows; /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public byte[] Serialize() { int index = 0; byte[] serializedBuffer = new byte[this.Size()]; serializedBuffer[index++] = this.RopId; serializedBuffer[index++] = this.LogonId; serializedBuffer[index++] = this.InputHandleIndex; Array.Copy(BitConverter.GetBytes((short)this.ColumnCount), 0, serializedBuffer, index, sizeof(ushort)); index += 2; if (this.ColumnCount > 0) { IntPtr requestBuffer = new IntPtr(); requestBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PropertyTag))); try { Context.Instance.Init(); foreach (PropertyTag propTag in this.RecipientColumns) { Marshal.StructureToPtr(propTag, requestBuffer, true); Marshal.Copy(requestBuffer, serializedBuffer, index, Marshal.SizeOf(typeof(PropertyTag))); index += Marshal.SizeOf(typeof(PropertyTag)); // Insert properties into Context Context.Instance.Properties.Add(new Property((PropertyType)propTag.PropertyType)); } } finally { Marshal.FreeHGlobal(requestBuffer); } } Array.Copy(BitConverter.GetBytes((short)this.RowCount), 0, serializedBuffer, index, sizeof(ushort)); index += 2; for (int i = 0; i < this.RowCount; i++) { Array.Copy(this.RecipientRows[i].Serialize(), 0, serializedBuffer, index, this.RecipientRows[i].Size()); index += this.RecipientRows[i].Size(); } return serializedBuffer; } /// <summary> /// Return the size of RopModifyRecipients request buffer structure. /// </summary> /// <returns>The size of RopModifyRecipients request buffer structure.</returns> public int Size() { // 7 indicates sizeof (byte) * 3 + sizeof (UInt16)*2 int size = sizeof(byte) * 7; if (this.ColumnCount > 0) { size += this.RecipientColumns.Length * Marshal.SizeOf(typeof(PropertyTag)); } if (this.RowCount > 0) { for (int i = 0; i < this.RowCount; i++) { size += this.RecipientRows[i].Size(); } } return size; } } /// <summary> /// RopModifyRecipients response buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopModifyRecipientsResponse : IDeserializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0x0E. /// </summary> public byte RopId; /// <summary> /// This index MUST be set to the InputHandleIndex specified in the request. /// </summary> public byte InputHandleIndex; /// <summary> /// This value specifies the status of the remote operation. /// </summary> public uint ReturnValue; /// <summary> /// Deserialize the ROP response buffer. /// </summary> /// <param name="ropBytes">ROPs bytes in response.</param> /// <param name="startIndex">The start index of this ROP.</param> /// <returns>The size of response buffer structure.</returns> public int Deserialize(byte[] ropBytes, int startIndex) { IntPtr responseBuffer = new IntPtr(); responseBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(this)); try { Marshal.Copy(ropBytes, startIndex, responseBuffer, Marshal.SizeOf(this)); this = (RopModifyRecipientsResponse)Marshal.PtrToStructure(responseBuffer, typeof(RopModifyRecipientsResponse)); return Marshal.SizeOf(this); } finally { Marshal.FreeHGlobal(responseBuffer); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyInteger { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class IntModelExtensions { /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetNull(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetNullAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetInvalid(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetInvalidAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetOverflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetOverflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static int? GetUnderflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<int?> GetUnderflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetOverflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetOverflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static long? GetUnderflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<long?> GetUnderflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMax64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMax64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> public static void PutMin64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMin64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(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.Runtime.CompilerServices; namespace System.Buffers.Reader { public ref struct BufferReader { private SequencePosition _currentPosition; private SequencePosition _nextPosition; [MethodImpl(MethodImplOptions.AggressiveInlining)] private BufferReader(in ReadOnlySequence<byte> buffer) { CurrentSegmentIndex = 0; ConsumedBytes = 0; Sequence = buffer; _currentPosition = Sequence.Start; _nextPosition = _currentPosition; if (buffer.TryGet(ref _nextPosition, out ReadOnlyMemory<byte> memory, true)) { End = false; CurrentSegment = memory.Span; if (CurrentSegment.Length == 0) { // No space in the first span, move to one with space GetNextSegment(); } } else { // No space in any spans and at end of sequence End = true; CurrentSegment = default; } } /// <summary> /// Create a <see cref="BufferReader" over the given <see cref="ReadOnlySequence{byte}"/>./> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static BufferReader Create(in ReadOnlySequence<byte> buffer) { return new BufferReader(buffer); } /// <summary> /// True when there is no more data in the <see cref="Sequence"/>. /// </summary> public bool End { get; private set; } /// <summary> /// The underlying <see cref="ReadOnlySequence{byte}"/> for the reader. /// </summary> public ReadOnlySequence<byte> Sequence { get; } /// <summary> /// The current position in the <see cref="Sequence"/>. /// </summary> public SequencePosition Position => Sequence.GetPosition(CurrentSegmentIndex, _currentPosition); /// <summary> /// The current segment in the <see cref="Sequence"/>. /// </summary> public ReadOnlySpan<byte> CurrentSegment { get; private set; } /// <summary> /// The index in the <see cref="CurrentSegment"/>. /// </summary> public int CurrentSegmentIndex { get; private set; } /// <summary> /// The unread portion of the <see cref="CurrentSegment"/>. /// </summary> public ReadOnlySpan<byte> UnreadSegment => CurrentSegment.Slice(CurrentSegmentIndex); /// <summary> /// The total number of bytes processed by the reader. /// </summary> public int ConsumedBytes { get; private set; } /// <summary> /// Peeks at the next byte value without advancing the reader. /// </summary> /// <returns>The next byte or -1 if at the end of the buffer.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Peek() { return End ? -1 : CurrentSegment[CurrentSegmentIndex]; } /// <summary> /// Read the next byte value. /// </summary> /// <returns>The next byte or -1 if at the end of the buffer.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Read() { if (End) { return -1; } byte value = CurrentSegment[CurrentSegmentIndex]; CurrentSegmentIndex++; ConsumedBytes++; if (CurrentSegmentIndex >= CurrentSegment.Length) { GetNextSegment(); } return value; } /// <summary> /// Get the next segment with available space, if any. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] private void GetNextSegment() { SequencePosition previousNextPosition = _nextPosition; while (Sequence.TryGet(ref _nextPosition, out ReadOnlyMemory<byte> memory, advance: true)) { _currentPosition = previousNextPosition; CurrentSegment = memory.Span; CurrentSegmentIndex = 0; if (CurrentSegment.Length > 0) { return; } } End = true; } /// <summary> /// Move the reader ahead the specified number of bytes. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Advance(int byteCount) { if (byteCount == 0) { return; } if (byteCount < 0 || End) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } ConsumedBytes += byteCount; if ((CurrentSegmentIndex + byteCount) < CurrentSegment.Length) { CurrentSegmentIndex += byteCount; } else { // Current segment doesn't have enough space, scan forward through segments AdvanceNextSegment(byteCount); } } [MethodImpl(MethodImplOptions.NoInlining)] private void AdvanceNextSegment(int byteCount) { while (!End && byteCount > 0) { if ((CurrentSegmentIndex + byteCount) < CurrentSegment.Length) { CurrentSegmentIndex += byteCount; byteCount = 0; break; } int remaining = (CurrentSegment.Length - CurrentSegmentIndex); CurrentSegmentIndex += remaining; byteCount -= remaining; GetNextSegment(); } if (byteCount > 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } } internal static int Peek(in BufferReader buffer, Span<byte> destination) { ReadOnlySpan<byte> firstSpan = buffer.UnreadSegment; if (firstSpan.Length > destination.Length) { firstSpan.Slice(0, destination.Length).CopyTo(destination); return destination.Length; } else if (firstSpan.Length == destination.Length) { firstSpan.CopyTo(destination); return destination.Length; } else { firstSpan.CopyTo(destination); int copied = firstSpan.Length; SequencePosition next = buffer._nextPosition; while (buffer.Sequence.TryGet(ref next, out ReadOnlyMemory<byte> nextSegment, true)) { ReadOnlySpan<byte> nextSpan = nextSegment.Span; if (nextSpan.Length > 0) { int toCopy = Math.Min(nextSpan.Length, destination.Length - copied); nextSpan.Slice(0, toCopy).CopyTo(destination.Slice(copied)); copied += toCopy; if (copied >= destination.Length) break; } } return copied; } } } }
// 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 gcsv = Google.Cloud.Shell.V1; using sys = System; namespace Google.Cloud.Shell.V1 { /// <summary>Resource name for the <c>Environment</c> resource.</summary> public sealed partial class EnvironmentName : gax::IResourceName, sys::IEquatable<EnvironmentName> { /// <summary>The possible contents of <see cref="EnvironmentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>users/{user}/environments/{environment}</c>.</summary> UserEnvironment = 1, } private static gax::PathTemplate s_userEnvironment = new gax::PathTemplate("users/{user}/environments/{environment}"); /// <summary>Creates a <see cref="EnvironmentName"/> 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="EnvironmentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EnvironmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EnvironmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EnvironmentName"/> with the pattern <c>users/{user}/environments/{environment}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EnvironmentName"/> constructed from the provided ids.</returns> public static EnvironmentName FromUserEnvironment(string userId, string environmentId) => new EnvironmentName(ResourceNameType.UserEnvironment, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>users/{user}/environments/{environment}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>users/{user}/environments/{environment}</c>. /// </returns> public static string Format(string userId, string environmentId) => FormatUserEnvironment(userId, environmentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>users/{user}/environments/{environment}</c>. /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>users/{user}/environments/{environment}</c>. /// </returns> public static string FormatUserEnvironment(string userId, string environmentId) => s_userEnvironment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary>Parses the given resource name string into a new <see cref="EnvironmentName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>users/{user}/environments/{environment}</c></description></item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName) => Parse(environmentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EnvironmentName"/> 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>users/{user}/environments/{environment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">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="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName, bool allowUnparsed) => TryParse(environmentName, allowUnparsed, out EnvironmentName 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="EnvironmentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>users/{user}/environments/{environment}</c></description></item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EnvironmentName"/>, 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 environmentName, out EnvironmentName result) => TryParse(environmentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> 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>users/{user}/environments/{environment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">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="EnvironmentName"/>, 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 environmentName, bool allowUnparsed, out EnvironmentName result) { gax::GaxPreconditions.CheckNotNull(environmentName, nameof(environmentName)); gax::TemplatedResourceName resourceName; if (s_userEnvironment.TryParseName(environmentName, out resourceName)) { result = FromUserEnvironment(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(environmentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EnvironmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string userId = null) { Type = type; UnparsedResource = unparsedResourceName; EnvironmentId = environmentId; UserId = userId; } /// <summary> /// Constructs a new instance of a <see cref="EnvironmentName"/> class from the component parts of pattern /// <c>users/{user}/environments/{environment}</c> /// </summary> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> public EnvironmentName(string userId, string environmentId) : this(ResourceNameType.UserEnvironment, userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))) { } /// <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>Environment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>User</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string UserId { 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.UserEnvironment: return s_userEnvironment.Expand(UserId, EnvironmentId); 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 EnvironmentName); /// <inheritdoc/> public bool Equals(EnvironmentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EnvironmentName a, EnvironmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EnvironmentName a, EnvironmentName b) => !(a == b); } public partial class Environment { /// <summary> /// <see cref="gcsv::EnvironmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::EnvironmentName EnvironmentName { get => string.IsNullOrEmpty(Name) ? null : gcsv::EnvironmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetEnvironmentRequest { /// <summary> /// <see cref="gcsv::EnvironmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcsv::EnvironmentName EnvironmentName { get => string.IsNullOrEmpty(Name) ? null : gcsv::EnvironmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Drawing; using System.Drawing.Drawing2D; using PdfSharp.Drawing; namespace Trizbort { /// <summary> /// A palette of drawing tools such as brushes, pens and fonts. /// </summary> /// <remarks> /// Centralising such tools in one place avoids tedious management /// of their lifetimes and avoids creating them until necessary, /// and then only once. /// </remarks> internal class Palette : IDisposable { public void Dispose() { foreach (var item in m_items) { item.Dispose(); } } public Pen Pen(Color color) { return Pen(color, Settings.LineWidth); } public Pen Pen(Color color, float width) { var pen = new Pen(color, width); pen.StartCap = LineCap.Round; pen.EndCap = LineCap.Round; m_items.Add(pen); return pen; } public Brush Brush(Color color) { var brush = new SolidBrush(color); m_items.Add(brush); return brush; } public XBrush Gradient(Rect rect, Color color1, Color color2) { var brush = new XLinearGradientBrush(rect.ToRectangleF(), color1, color2, XLinearGradientMode.ForwardDiagonal); //m_items.Add(brush); return brush; } public Font Font(string familyName, float emSize) { var font = new Font(familyName, emSize, FontStyle.Regular, GraphicsUnit.World); m_items.Add(font); return font; } public Font Font(Font prototype, FontStyle newStyle) { var font = new Font(prototype, newStyle); m_items.Add(font); return font; } public XGraphicsPath Path() { var path = new XGraphicsPath(); //m_items.Add(path); return path; } public Pen LinePen { get { if (m_linePen == null) { m_linePen = Pen(Settings.Color[Colors.Line]); } return m_linePen; } } public Pen DashedLinePen { get { if (m_dashedLinePen == null) { m_dashedLinePen = Pen(Settings.Color[Colors.Line]); m_dashedLinePen.DashStyle = DashStyle.Dot; } return m_dashedLinePen; } } public Pen SelectedLinePen { get { if (m_selectedLinePen == null) { m_selectedLinePen = Pen(Settings.Color[Colors.SelectedLine]); } return m_selectedLinePen; } } public Pen SelectedDashedLinePen { get { if (m_selectedDashedLinePen == null) { m_selectedDashedLinePen = Pen(Settings.Color[Colors.SelectedLine]); m_selectedDashedLinePen.DashStyle = DashStyle.Dot; } return m_selectedDashedLinePen; } } public Pen HoverLinePen { get { if (m_hoverLinePen == null) { m_hoverLinePen = Pen(Settings.Color[Colors.HoverLine]); } return m_hoverLinePen; } } public Pen HoverDashedLinePen { get { if (m_hoverDashedLinePen == null) { m_hoverDashedLinePen = Pen(Settings.Color[Colors.HoverLine]); m_hoverDashedLinePen.DashStyle = DashStyle.Dot; } return m_hoverDashedLinePen; } } public Pen GetLinePen(bool selected, bool hover, bool dashed) { if (selected) { return dashed ? SelectedDashedLinePen : SelectedLinePen; } else if (hover) { return dashed ? HoverDashedLinePen : HoverLinePen; } return dashed ? DashedLinePen : LinePen; } public Brush GetLineBrush(bool selected, bool hover) { if (selected) { return SelectedLineBrush; } else if (hover) { return HoverLineBrush; } return LineBrush; } public Brush LineBrush { get { if (m_lineBrush == null) { m_lineBrush = Brush(Settings.Color[Colors.Line]); } return m_lineBrush; } } public Brush SelectedLineBrush { get { if (m_selectedLineBrush == null) { m_selectedLineBrush = Brush(Settings.Color[Colors.SelectedLine]); } return m_selectedLineBrush; } } public Brush HoverLineBrush { get { if (m_hoverLineBrush == null) { m_hoverLineBrush = Brush(Settings.Color[Colors.HoverLine]); } return m_hoverLineBrush; } } public Pen BorderPen { get { if (m_borderPen == null) { m_borderPen = Pen(Settings.Color[Colors.Border]); } return m_borderPen; } } public Pen LargeTextPen { get { if (m_largeTextPen == null) { m_largeTextPen = Pen(Settings.Color[Colors.LargeText]); } return m_largeTextPen; } } public Pen FillPen { get { if (m_fillPen == null) { m_fillPen = Pen(Settings.Color[Colors.Fill]); } return m_fillPen; } } public Pen GridPen { get { if (m_gridPen == null) { m_gridPen = Pen(Settings.Color[Colors.Grid], 0); } return m_gridPen; } } public Brush CanvasBrush { get { if (m_canvasBrush == null) { m_canvasBrush = Brush(Settings.Color[Colors.Canvas]); } return m_canvasBrush; } } public Brush BorderBrush { get { if (m_borderBrush == null) { m_borderBrush = Brush(Settings.Color[Colors.Border]); } return m_borderBrush; } } public Brush FillBrush { get { if (m_fillBrush == null) { m_fillBrush = Brush(Settings.Color[Colors.Fill]); } return m_fillBrush; } } public Brush LargeTextBrush { get { if (m_largeTextBrush == null) { m_largeTextBrush = Brush(Settings.Color[Colors.LargeText]); } return m_largeTextBrush; } } public Brush SmallTextBrush { get { if (m_smallTextBrush == null) { m_smallTextBrush = Brush(Settings.Color[Colors.SmallText]); } return m_smallTextBrush; } } public Brush LineTextBrush { get { if (m_lineTextBrush == null) { m_lineTextBrush = Brush(Settings.Color[Colors.LineText]); } return m_lineTextBrush; } } public Brush MarqueeFillBrush { get { if (m_marqueeFillBrush == null) { m_marqueeFillBrush = Brush(Color.FromArgb(80, Settings.Color[Colors.Border])); } return m_marqueeFillBrush; } } public Pen MarqueeBorderPen { get { if (m_marqueeBorderPen == null) { m_marqueeBorderPen = Pen(Color.FromArgb(120, Settings.Color[Colors.Border]), 0); } return m_marqueeBorderPen; } } public Pen ResizeBorderPen { get { if (m_resizeBorderPen == null) { m_resizeBorderPen = Pen(Color.FromArgb(64, Color.SteelBlue), 6); //m_resizeBorderPen.DashStyle = DashStyle.Dot; } return m_resizeBorderPen; } } private List<IDisposable> m_items = new List<IDisposable>(); private Pen m_linePen; private Pen m_dashedLinePen; private Pen m_selectedLinePen; private Pen m_selectedDashedLinePen; private Pen m_hoverLinePen; private Pen m_hoverDashedLinePen; private Brush m_lineBrush; private Brush m_selectedLineBrush; private Brush m_hoverLineBrush; private Pen m_borderPen; private Pen m_largeTextPen; private Pen m_fillPen; private Pen m_gridPen; private Brush m_borderBrush; private Brush m_fillBrush; private Brush m_canvasBrush; private Brush m_largeTextBrush; private Brush m_smallTextBrush; private Brush m_lineTextBrush; private Brush m_marqueeFillBrush; private Pen m_marqueeBorderPen; private Pen m_resizeBorderPen; } }
using System; using System.IO; using System.Text; namespace Hydna.Net { /// <summary> /// Represents a Channel which can be used bi-directional data /// between client and a Hydna server. /// </summary> public class Channel : IDisposable { /// <summary> /// Indiciates the maximum size that could be sent over the /// network in one chunk. /// </summary> public const int PayloadMaxSize = Frame.PayloadMaxSize; /// <summary> /// Open is triggered once that channel is open. /// </summary> public event EventHandler<ChannelEventArgs> Open { add { _openInvoker += value; } remove { _openInvoker -= value; } } /// <summary> /// Data is triggered once that channel recevies data. /// </summary> public event EventHandler<ChannelDataEventArgs> Data { add { _dataInvoker += value; } remove { _dataInvoker -= value; } } /// <summary> /// Signal is triggered once that channel recevies a signal. /// </summary> public event EventHandler<ChannelEventArgs> Signal { add { _signalInvoker += value; } remove { _signalInvoker -= value; } } /// <summary> /// Close is triggered once that channel is closed. /// </summary> public event EventHandler<ChannelCloseEventArgs> Closed { add { _closedInvoker += value; } remove { _closedInvoker -= value; } } internal byte[] token = null; internal ContentType ctoken = ContentType.Utf; internal byte[] outro = null; internal ContentType coutro = ContentType.Utf; private uint _ptr = 0; private Uri _uri = null; private ChannelMode _mode = ChannelMode.Listen; private ChannelState _state = ChannelState.Closed; EventHandler<ChannelEventArgs> _openInvoker; EventHandler<ChannelDataEventArgs> _dataInvoker; EventHandler<ChannelEventArgs> _signalInvoker; EventHandler<ChannelCloseEventArgs> _closedInvoker; private Connection _connection; void IDisposable.Dispose() { try { Close(); } catch (Exception) { } } /// <summary> /// Initializes a new instance of the Channel class. /// </summary> public Channel () { } /// <summary> /// Gets the absolute <b>path</b> for this channel /// </summary> /// <value>The <b>path</b> if connecting/connected; otherwise /// <b>null</b> </value> public string AbsolutePath { get { return _uri == null ? null : _uri.AbsolutePath; } } /// <summary> /// Gets a value indicating what mode that this channel instance /// is opened in. /// </summary> /// <value>A value indiciating the channel mode</value> public ChannelMode Mode { get { return _mode; } } /// <summary> /// Gets a value indicating whether this channel is readable. /// </summary> /// <value><c>true</c> if data is recieved on this Channel instance; /// otherwise, <c>false</c>.</value> public bool Readable { get { return _state == ChannelState.Open && (_mode & ChannelMode.Read) == ChannelMode.Read; } } /// <summary> /// Gets a value indicating whether this channel can send data. /// </summary> /// <value><c>true</c> if data can be sent over this Channel instance; /// otherwise, <c>false</c>.</value> public bool Writable { get { return _state == ChannelState.Open && (_mode & ChannelMode.Write) == ChannelMode.Write; } } /// <summary> /// Gets a value indicating whether this channel can emit signals. /// </summary> /// <value><c>true</c> if signals can be emitted over this Channel /// instance; otherwise, <c>false</c>.</value> public bool Emittable { get { return _state == ChannelState.Open && (_mode & ChannelMode.Emit) == ChannelMode.Emit; } } /// <summary> /// Gets the <c>uri</c> for this channel instance. /// </summary> /// <value>The <c>uri</c> which this channel instance is /// connecting/conntected to; otherwise <c>null</c></value> public Uri Uri { get { return _uri; } } /// <summary> /// Gets the <c>state</c> for this channel instance. /// </summary> /// <value>The current <c>state</c></value> public ChannelState State { get { return _state; } } /// <summary> /// Connect to a remote server at specified <c>url</c>, in mode /// <c>read</c>. /// </summary> /// <param name="url">The <c>url</c> (e.g. public.hydna.net)</param> public void Connect (string url) { Connect(url, ChannelMode.Read); } /// <summary> /// Connect to a remote server at specified <c>url</c>, in specified /// <c>mode</c>. /// </summary> /// <param name="url">The <c>url</c> (e.g. public.hydna.net)</param> /// <param name="mode">The <c>mode</c> to open channel in.</param> public void Connect (string url, ChannelMode mode) { Uri uri; if (url == null) { throw new ArgumentNullException("url", "Expected an Url"); } if (url.Contains("://") == false) { UriBuilder builder = new UriBuilder("http://" + url); uri = builder.Uri; } else { uri = new Uri(url); } Connect(uri, mode); } /// <summary> /// Connect to a remote server at specified <c>uri</c>, in mode /// <c>read</c>. /// </summary> /// <param name="uri">The <c>uri</c> to server</param> public void Connect (Uri uri) { Connect(uri, ChannelMode.Read); } /// <summary> /// Connect to a remote server at specified <c>uri</c>, in specified /// <c>mode</c>. /// </summary> /// <param name="uri">The <c>uri</c> to server</param> /// <param name="mode">The <c>mode</c> to open channel in.</param> public void Connect (Uri uri, ChannelMode mode) { if (_state != ChannelState.Closed) { throw new Exception("Channel is already connecting/connected"); } if (uri == null) { throw new ArgumentNullException("uri", "Expected an Uri"); } if (uri.Scheme != "http" && uri.Scheme != "https") { throw new ArgumentException("uri", "Unsupported Scheme"); } if (uri.Scheme == "https" && Connection.hasTlsSupport == false) { throw new ArgumentException("uri", "TLS is not supported"); } if (uri.Query != null && uri.Query.Length > 0) { token = Encoding.UTF8.GetBytes(uri.Query.Substring(1)); } _mode = mode; _uri = uri; try { _connection = Connection.create(this, uri); } catch (Exception ex) { token = null; _mode = ChannelMode.Listen; throw ex; } _state = ChannelState.Connecting; } /// <summary> /// Sends an UTF8 encoded string to this channel instance. /// </summary> /// <param name="data">The <c>string</c> that should be sent</param> public void Send(string data) { Send(data, DeliveryPriority.Guaranteed); } /// <summary> /// Sends an UTF8 encoded string to this channel instance, with /// specified priority. /// </summary> /// <param name="data">The <c>string</c> that should be sent</param> /// <param name="priority">The priority of this message</param> public void Send(string data, DeliveryPriority prio) { if (data == null) { throw new ArgumentNullException("data", "Cannot be null"); } byte[] buffer = Encoding.UTF8.GetBytes(data); Send(ContentType.Utf, buffer, prio); } /// <summary> /// Sends binary data to this channel instance. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// written to the channel.</param> public void Send(byte[] buffer) { Send(buffer, DeliveryPriority.Guaranteed); } /// <summary> /// Sends binary data to this channel instance. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// written to the channel.</param> /// <param name="offset">The zero-based location in buffer at which to /// begin reading bytes to be written to the channel.</param> /// <param name="count">A value that specifies the number of bytes to /// read from buffer.</param> public void Send(byte[] buffer, int offset, int count) { Send(buffer, offset, count, DeliveryPriority.Guaranteed); } /// <summary> /// Sends binary data to this channel instance, with specified /// priority. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// written to the channel.</param> /// <param name="priority">The priority of this message</param> public void Send(byte[] buffer, DeliveryPriority prio) { Send(ContentType.Binary, buffer, prio); } /// <summary> /// Sends binary data to this channel instance, with specified /// priority. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// written to the channel.</param> /// <param name="offset">The zero-based location in buffer at which to /// begin reading bytes to be written to the channel.</param> /// <param name="count">A value that specifies the number of bytes to /// read from buffer.</param> /// <param name="priority">The priority of this message</param> public void Send(byte[] buffer, int offset, int count, DeliveryPriority prio) { if (offset < 0 || offset + count > buffer.Length) { throw new ArgumentException("Index out of bounds"); } byte[] clone = new byte[count - offset]; Buffer.BlockCopy(buffer, offset, clone, 0, count); Send(ContentType.Binary, clone, prio); } void Send(ContentType ctype, byte[] buffer, DeliveryPriority prio) { if (_state != ChannelState.Open) { throw new InvalidOperationException("Channel is not open"); } if (Writable == false) { throw new InvalidOperationException("Channel is not writable"); } if (buffer == null) { throw new ArgumentNullException("buffer", "Cannot be null"); } if (buffer.Length > Frame.PayloadMaxSize) { throw new ArgumentException("buffer", "Data buffer is to large"); } Frame frame = Frame.Create(_ptr, prio, ctype, buffer); _connection.Send(frame); } /// <summary> /// Emitts a signal to the channel /// </summary> /// <param name="data">A string that supplies the data to be /// emitted to the channel.</param> public void Emit(string data) { if (data == null) { throw new ArgumentNullException("data", "Cannot be null"); } byte[] buffer = Encoding.UTF8.GetBytes(data); Emit(ContentType.Utf, buffer); } /// <summary> /// Emitts a signal to the channel /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// emitted to the channel.</param> public void Emit(byte[] buffer) { Emit(ContentType.Binary, buffer); } /// <summary> /// Emitts a signal to the channel /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// emitted to the channel.</param> /// <param name="offset">The zero-based location in buffer at which to /// begin reading bytes to be written to the channel.</param> /// <param name="count">A value that specifies the number of bytes to /// read from buffer.</param> public void Emit(byte[] buffer, int offset, int count) { if (offset < 0 || offset + count > buffer.Length) { throw new ArgumentException("Index out of bounds"); } byte[] clone = new byte[count - offset]; Buffer.BlockCopy(buffer, offset, clone, 0, count); Emit(ContentType.Binary, clone); } void Emit(ContentType ctype, byte[] buffer) { if (_state != ChannelState.Open) { throw new InvalidOperationException("Channel is not open"); } if (Emittable == false) { throw new InvalidOperationException("Channel is not writable"); } if (buffer == null) { throw new ArgumentNullException("buffer", "Cannot be null"); } if (buffer.Length > Frame.PayloadMaxSize) { throw new ArgumentException("buffer", "Data buffer is to large"); } Frame end = Frame.Create(_ptr, SignalFlag.Emit, ctype, buffer); _connection.Send(end); } /// <summary> /// Closes the channel by sending an end signal to the remote /// connection. The event Close is triggered once that channel is /// completely closed. /// </summary> public void Close() { Close(ContentType.Utf, null); } /// <summary> /// Closes the channel by sending an end signal, with specified string, /// to the remote connection. The event Close is triggered once that /// channel is completely closed. /// </summary> /// <param name="data">A string that supplies the data to be /// emitted to the channel.</param> public void Close(string data) { if (data == null) { throw new ArgumentNullException("data", "Cannot be null"); } byte[] buffer = Encoding.UTF8.GetBytes(data); Close(ContentType.Utf, buffer); } /// <summary> /// Closes the channel by sending an end signal, with specified data, /// to the remote connection. The event Close is triggered once that /// channel is completely closed. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// emitted to the channel.</param> public void Close(byte[] buffer) { Close(ContentType.Binary, buffer); } /// <summary> /// Closes the channel by sending an end signal, with specified data, /// to the remote connection. The event Close is triggered once that /// channel is completely closed. /// </summary> /// <param name="buffer">A Byte array that supplies the bytes to be /// emitted to the channel.</param> /// <param name="offset">The zero-based location in buffer at which to /// begin reading bytes to be written to the channel.</param> /// <param name="count">A value that specifies the number of bytes to /// read from buffer.</param> public void Close(byte[] buffer, int offset, int count) { if (offset < 0 || offset + count > buffer.Length) { throw new ArgumentException("Index out of bounds"); } byte[] clone = new byte[count - offset]; Buffer.BlockCopy(buffer, offset, clone, 0, count); Close(ContentType.Binary, clone); } void Close(ContentType ctype, byte[] buffer) { if (_connection == null || _state == ChannelState.Closed || _state == ChannelState.Closing) { throw new InvalidOperationException("Channel is already closed"); } if (buffer != null && buffer.Length > Frame.PayloadMaxSize) { throw new ArgumentException("buffer", "Data buffer is to large"); } ChannelState oldState = _state; _state = ChannelState.Closing; if (oldState == ChannelState.Connecting || oldState == ChannelState.Resolved) { // Open request is not responded to yet. Wait to send // ENDSIG until we get an OPENRESP. coutro = ctype; outro = buffer; return; } Frame end = Frame.Create(_ptr, SignalFlag.End, ctype, buffer); _connection.Send(end); } internal uint Ptr { get { return _ptr; } } internal void handleResolved(uint ptr) { _ptr = ptr; _state = ChannelState.Resolved; } internal void handleOpen(Frame frame) { if (_state == ChannelState.Closing) { // User has called close before it was open. Send // the pending ENDSIG. Frame end = Frame.Create(_ptr, SignalFlag.End, coutro, outro); outro = null; _connection.Send(end); return; } _state = ChannelState.Open; if (_openInvoker == null) return; ChannelEventArgs e; e = new ChannelEventArgs(frame.ContentType, frame.Payload); _openInvoker(this, e); } internal void handleData(Frame frame) { if (_dataInvoker == null) return; ChannelDataEventArgs e; e = new ChannelDataEventArgs(frame.ContentType, frame.Payload, frame.PriorityFlag); _dataInvoker(this, e); } internal void handleSignal(Frame frame) { if (_signalInvoker == null) return; ChannelEventArgs e; e = new ChannelEventArgs(frame.ContentType, frame.Payload); _signalInvoker(this, e); } internal void handleClose(Frame frame) { handleClose(frame, "Unknown reason"); } internal void handleClose(string reason) { handleClose(null, reason); } internal void handleClose(Frame frame, string reason) { if (_state == ChannelState.Closed) { return; } _state = ChannelState.Closed; _ptr = 0; if (_closedInvoker == null) return; ChannelCloseEventArgs e; if (frame == null) { e = new ChannelCloseEventArgs(false, false, reason); } else { bool wasDenied = frame.OpCode == OpCode.Open; bool wasClean = wasDenied ? false : frame.SignalFlag == SignalFlag.End; e = new ChannelCloseEventArgs(frame.ContentType, frame.Payload, wasDenied, wasClean, reason); } _closedInvoker(this, e); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.VisualTree; namespace Avalonia.Input.Navigation { /// <summary> /// The implementation for default tab navigation. /// </summary> internal static class TabNavigation { /// <summary> /// Gets the next control in the specified tab direction. /// </summary> /// <param name="element">The element.</param> /// <param name="direction">The tab direction. Must be Next or Previous.</param> /// <param name="outsideElement"> /// If true will not descend into <paramref name="element"/> to find next control. /// </param> /// <returns> /// The next element in the specified direction, or null if <paramref name="element"/> /// was the last in the requested direction. /// </returns> public static IInputElement GetNextInTabOrder( IInputElement element, NavigationDirection direction, bool outsideElement = false) { Contract.Requires<ArgumentNullException>(element != null); Contract.Requires<ArgumentException>( direction == NavigationDirection.Next || direction == NavigationDirection.Previous); var container = element.GetVisualParent<IInputElement>(); if (container != null) { var mode = KeyboardNavigation.GetTabNavigation((InputElement)container); switch (mode) { case KeyboardNavigationMode.Continue: return GetNextInContainer(element, container, direction, outsideElement) ?? GetFirstInNextContainer(element, element, direction); case KeyboardNavigationMode.Cycle: return GetNextInContainer(element, container, direction, outsideElement) ?? GetFocusableDescendant(container, direction); case KeyboardNavigationMode.Contained: return GetNextInContainer(element, container, direction, outsideElement); default: return GetFirstInNextContainer(element, container, direction); } } else { return GetFocusableDescendants(element, direction).FirstOrDefault(); } } /// <summary> /// Gets the first or last focusable descendant of the specified element. /// </summary> /// <param name="container">The element.</param> /// <param name="direction">The direction to search.</param> /// <returns>The element or null if not found.##</returns> private static IInputElement GetFocusableDescendant(IInputElement container, NavigationDirection direction) { return direction == NavigationDirection.Next ? GetFocusableDescendants(container, direction).FirstOrDefault() : GetFocusableDescendants(container, direction).LastOrDefault(); } /// <summary> /// Gets the focusable descendants of the specified element. /// </summary> /// <param name="element">The element.</param> /// <param name="direction">The tab direction. Must be Next or Previous.</param> /// <returns>The element's focusable descendants.</returns> private static IEnumerable<IInputElement> GetFocusableDescendants(IInputElement element, NavigationDirection direction) { var mode = KeyboardNavigation.GetTabNavigation((InputElement)element); if (mode == KeyboardNavigationMode.None) { yield break; } var children = element.GetVisualChildren().OfType<IInputElement>(); if (mode == KeyboardNavigationMode.Once) { var active = KeyboardNavigation.GetTabOnceActiveElement((InputElement)element); if (active != null) { yield return active; yield break; } else { children = children.Take(1); } } foreach (var child in children) { var customNext = GetCustomNext(child, direction); if (customNext.handled) { yield return customNext.next; } else { if (child.CanFocus()) { yield return child; } if (child.CanFocusDescendants()) { foreach (var descendant in GetFocusableDescendants(child, direction)) { yield return descendant; } } } } } /// <summary> /// Gets the next item that should be focused in the specified container. /// </summary> /// <param name="element">The starting element/</param> /// <param name="container">The container.</param> /// <param name="direction">The direction.</param> /// <param name="outsideElement"> /// If true will not descend into <paramref name="element"/> to find next control. /// </param> /// <returns>The next element, or null if the element is the last.</returns> private static IInputElement GetNextInContainer( IInputElement element, IInputElement container, NavigationDirection direction, bool outsideElement) { if (direction == NavigationDirection.Next && !outsideElement) { var descendant = GetFocusableDescendants(element, direction).FirstOrDefault(); if (descendant != null) { return descendant; } } if (container != null) { var navigable = container as INavigableContainer; // TODO: Do a spatial search here if the container doesn't implement // INavigableContainer. if (navigable != null) { while (element != null) { element = navigable.GetControl(direction, element); if (element != null && element.CanFocus()) { break; } } } else { // TODO: Do a spatial search here if the container doesn't implement // INavigableContainer. element = null; } if (element != null && direction == NavigationDirection.Previous) { var descendant = GetFocusableDescendants(element, direction).LastOrDefault(); if (descendant != null) { return descendant; } } return element; } return null; } /// <summary> /// Gets the first item that should be focused in the next container. /// </summary> /// <param name="element">The element being navigated away from.</param> /// <param name="container">The container.</param> /// <param name="direction">The direction of the search.</param> /// <returns>The first element, or null if there are no more elements.</returns> private static IInputElement GetFirstInNextContainer( IInputElement element, IInputElement container, NavigationDirection direction) { var parent = container.GetVisualParent<IInputElement>(); IInputElement next = null; if (parent != null) { if (direction == NavigationDirection.Previous && parent.CanFocus()) { return parent; } var siblings = parent.GetVisualChildren() .OfType<IInputElement>() .Where(FocusExtensions.CanFocusDescendants); var sibling = direction == NavigationDirection.Next ? siblings.SkipWhile(x => x != container).Skip(1).FirstOrDefault() : siblings.TakeWhile(x => x != container).LastOrDefault(); if (sibling != null) { var customNext = GetCustomNext(sibling, direction); if (customNext.handled) { return customNext.next; } if (sibling.CanFocus()) { next = sibling; } else { next = direction == NavigationDirection.Next ? GetFocusableDescendants(sibling, direction).FirstOrDefault() : GetFocusableDescendants(sibling, direction).LastOrDefault(); } } if (next == null) { next = GetFirstInNextContainer(element, parent, direction); } } else { next = direction == NavigationDirection.Next ? GetFocusableDescendants(container, direction).FirstOrDefault() : GetFocusableDescendants(container, direction).LastOrDefault(); } return next; } private static (bool handled, IInputElement next) GetCustomNext(IInputElement element, NavigationDirection direction) { if (element is ICustomKeyboardNavigation custom) { return custom.GetNext(element, direction); } return (false, null); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; namespace Http { public class Response : IResponse { public int status = 200; public string message = "OK"; public byte[] bytes; List<byte[]> chunks; Dictionary<string, List<string>> headers = new Dictionary<string, List<string>>(); public string Text { get { if (bytes == null) return ""; return System.Text.UTF8Encoding.UTF8.GetString(bytes); } } void AddHeader(string name, string value) { name = name.ToLower().Trim(); value = value.Trim(); if (!headers.ContainsKey(name)) headers[name] = new List<string>(); headers[name].Add(value); } public List<string> GetHeaders(string name) { name = name.ToLower().Trim(); if (!headers.ContainsKey(name)) headers[name] = new List<string>(); return headers[name]; } public string GetHeader(string name) { name = name.ToLower().Trim(); if (!headers.ContainsKey(name)) return string.Empty; return headers[name][headers[name].Count - 1]; } public Response() { //ReadFromStream (stream); } string ReadLine(Stream stream) { var line = new List<byte>(); while (true) { byte c = (byte)stream.ReadByte(); if (c == Request.EOL[1]) break; line.Add(c); } var s = ASCIIEncoding.ASCII.GetString(line.ToArray()).Trim(); return s; } string[] ReadKeyValue(Stream stream) { string line = ReadLine(stream); if (line == "") return null; else { var split = line.IndexOf(':'); if (split == -1) return null; var parts = new string[2]; parts[0] = line.Substring(0, split).Trim(); parts[1] = line.Substring(split + 1).Trim(); return parts; } } public byte[] TakeChunk() { byte[] b = null; lock (chunks) { if (chunks.Count > 0) { b = chunks[0]; chunks.RemoveAt(0); return b; } } return b; } public void ReadFromStream(Stream inputStream) { //var inputStream = new BinaryReader(inputStream); var top = ReadLine(inputStream).Split(new char[] { ' ' }); var output = new MemoryStream(); if (!int.TryParse(top[1], out status)) throw new HTTPException("Bad Status Code"); message = string.Join(" ", top, 2, top.Length - 2); headers.Clear(); while (true) { // Collect Headers string[] parts = ReadKeyValue(inputStream); if (parts == null) break; AddHeader(parts[0], parts[1]); } if (GetHeader("transfer-encoding") == "chunked") { chunks = new List<byte[]>(); while (true) { // Collect Body string hexLength = ReadLine(inputStream); //Console.WriteLine("HexLength:" + hexLength); if (hexLength == "0") { lock (chunks) { chunks.Add(new byte[] { }); } break; } int length = int.Parse(hexLength, NumberStyles.AllowHexSpecifier); for (int i = 0; i < length; i++) output.WriteByte((byte)inputStream.ReadByte()); lock (chunks) { //if (GetHeader ("content-encoding").Contains ("gzip")) // chunks.Add (UnZip(output)); //else chunks.Add(output.ToArray()); } output.SetLength(0); //forget the CRLF. inputStream.ReadByte(); inputStream.ReadByte(); } while (true) { //Collect Trailers string[] parts = ReadKeyValue(inputStream); if (parts == null) break; AddHeader(parts[0], parts[1]); } var unchunked = new List<byte>(); foreach (var i in chunks) { unchunked.AddRange(i); } bytes = unchunked.ToArray(); } else { // Read Body int contentLength = 0; try { contentLength = int.Parse(GetHeader("content-length")); } catch { contentLength = 0; } for (int i = 0; i < contentLength; i++) output.WriteByte((byte)inputStream.ReadByte()); //if (GetHeader ("content-encoding").Contains ("gzip")) { // bytes = UnZip(output); //} else { bytes = output.ToArray(); //} } } //byte[] UnZip(MemoryStream output) { // var cms = new MemoryStream (); // output.Seek (0, SeekOrigin.Begin); // using (var gz = new GZipStream (output, CompressionMode.Decompress)) { // var buf = new byte[1024]; // int byteCount = 0; // while ((byteCount = gz.Read (buf, 0, buf.Length)) > 0) { // cms.Write (buf, 0, byteCount); // } // } // return cms.ToArray (); //} public string ReadAsString() { return this.Text; } Stream _stream; public Stream GetResponseStream() { if (_stream == null) { _stream = new MemoryStream(bytes); } return _stream; } public void Close() { } public void EnsureSuccessStatusCode() { if (this.status > 399) { throw new HTTPException((HttpStatusCode)this.status); } } } }
//------------------------------------------------------------------------------ // <copyright file="PeerEndPoint.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.PeerToPeer.Collaboration { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Runtime.InteropServices; using System.Net.Sockets; using System.ComponentModel; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Security.Permissions; /// <summary> /// This is the event args class we give back when /// we have have a name changed event fired by native /// </summary> public class NameChangedEventArgs : EventArgs { private PeerEndPoint m_peerEndPoint; private PeerContact m_peerContact; private string m_name; internal NameChangedEventArgs(PeerEndPoint peerEndPoint, PeerContact peerContact, string name) { m_peerEndPoint = peerEndPoint; m_peerContact = peerContact; m_name = name; } public PeerEndPoint PeerEndPoint { get{ return m_peerEndPoint; } } public PeerContact PeerContact { get{ return m_peerContact; } } public string Name { get{ return m_name; } } } /// <summary> /// PeerEndpoint class encapsulates the functionality of an /// endpoint in the peer collaboration scope. /// </summary> [Serializable] public class PeerEndPoint : IDisposable, IEquatable<PeerEndPoint>, ISerializable { private string m_endPointName; private IPEndPoint m_endPoint; private ISynchronizeInvoke m_synchronizingObject; public PeerEndPoint() { } public PeerEndPoint(IPEndPoint endPoint):this(endPoint, null) { } public PeerEndPoint(IPEndPoint endPoint, string endPointName) { if (endPoint == null){ throw new ArgumentNullException("endPoint"); } // // Validate that this is an IPv6 address // if ((m_endPoint != null) && (m_endPoint.AddressFamily != AddressFamily.InterNetworkV6)){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerEndPoint Endpoint set parameter is not IPv6."); throw new ArgumentException("endPoint", SR.GetString(SR.Collab_EndPointNotIPv6Error)); } m_endPoint = endPoint; m_endPointName = endPointName; } /// <summary> /// Constructor to enable serialization /// </summary> [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] protected PeerEndPoint(SerializationInfo serializationInfo, StreamingContext streamingContext) { m_endPointName = serializationInfo.GetString("_EndPointName"); m_endPoint = (IPEndPoint)serializationInfo.GetValue("_EndPoint", typeof(IPEndPoint)); } public string Name { get { return m_endPointName; } set { m_endPointName = value; } } public IPEndPoint EndPoint { get { return m_endPoint; } set { // // Validate that this is an IPv6 address // if ((m_endPoint != null) && (m_endPoint.AddressFamily != AddressFamily.InterNetworkV6)){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerEndPoint Endpoint set parameter is not IPv6."); throw new PeerToPeerException(SR.GetString(SR.Collab_EndPointNotIPv6Error)); } m_endPoint = value; } } /// <summary> /// Gets and set the object used to marshall event handlers calls for stand alone /// events /// </summary> [Browsable(false), DefaultValue(null), Description(SR.SynchronizingObject)] public ISynchronizeInvoke SynchronizingObject { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_synchronizingObject; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_synchronizingObject = value; } } private event EventHandler<NameChangedEventArgs> m_nameChanged; public event EventHandler<NameChangedEventArgs> NameChanged { // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.Initialize():System.Void" Ring="1" /> // <ReferencesCritical Name="Method: AddNameChanged(EventHandler`1<System.Net.PeerToPeer.Collaboration.NameChangedEventArgs>):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] add{ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); CollaborationHelperFunctions.Initialize(); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); AddNameChanged(value); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.Initialize():System.Void" Ring="1" /> // <ReferencesCritical Name="Method: RemoveNameChanged(EventHandler`1<System.Net.PeerToPeer.Collaboration.NameChangedEventArgs>):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] remove{ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); CollaborationHelperFunctions.Initialize(); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); RemoveNameChanged(value); } } #region Name changed event variables private object m_lockNameChangedEvent; private object LockNameChangedEvent { get{ if (m_lockNameChangedEvent == null){ object o = new object(); Interlocked.CompareExchange(ref m_lockNameChangedEvent, o, null); } return m_lockNameChangedEvent; } } private RegisteredWaitHandle m_regNameChangedWaitHandle; private AutoResetEvent m_nameChangedEvent; private SafeCollabEvent m_safeNameChangedEvent; #endregion // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <ReferencesCritical Name="Method: NameChangedCallback(Object, Boolean):Void" Ring="1" /> // <ReferencesCritical Name="Field: m_safeNameChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void AddNameChanged(EventHandler<NameChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Entering AddNameChanged()."); // // Register a wait handle if one has not been registered already // lock (LockNameChangedEvent){ if (m_nameChanged == null){ m_nameChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // m_regNameChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(m_nameChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(NameChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.EndPointChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( m_nameChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safeNameChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_NameChangedRegFailed), errorCode); } } m_nameChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddNameChanged() successful."); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeNameChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void RemoveNameChanged(EventHandler<NameChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveNameChanged() called."); lock (LockNameChangedEvent){ m_nameChanged -= callback; if (m_nameChanged == null){ CollaborationHelperFunctions.CleanEventVars(ref m_regNameChangedWaitHandle, ref m_safeNameChangedEvent, ref m_nameChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean NameChanged variables successful."); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveNameChanged() successful."); } // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: m_safeNameChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(System.Net.PeerToPeer.Collaboration.PEER_CONTACT):System.Net.PeerToPeer.Collaboration.PeerContact" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] private void NameChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "NameChangedCallback() called."); if (m_Disposed) return; while (true){ NameChangedEventArgs nameChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockNameChangedEvent) { if (m_safeNameChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safeNameChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetNameChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.EndPointChanged){ PEER_EVENT_ENDPOINT_CHANGED_DATA epData = ped.endpointChangedData; PeerEndPoint peerEndPoint = null; if (epData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(epData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } if ((peerEndPoint != null) && Equals(peerEndPoint)){ PeerContact peerContact = null; if (epData.pContact != IntPtr.Zero){ PEER_CONTACT pc = (PEER_CONTACT)Marshal.PtrToStructure(epData.pContact, typeof(PEER_CONTACT)); peerContact = CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(pc); } nameChangedArgs = new NameChangedEventArgs(peerEndPoint, peerContact, peerEndPoint.Name); } } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if (nameChangedArgs != null){ OnNameChanged(nameChangedArgs); // // Change the name with the new name // Name = nameChangedArgs.PeerEndPoint.Name; } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving NameChangedCallback()."); } protected void OnNameChanged(NameChangedEventArgs nameChangedArgs) { EventHandler<NameChangedEventArgs> handlerCopy = m_nameChanged; if (handlerCopy != null){ if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) SynchronizingObject.BeginInvoke(handlerCopy, new object[] { this, nameChangedArgs }); else handlerCopy(this, nameChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the name changed event callback."); } } public bool Equals(PeerEndPoint other) { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); // // Equality means same ipendpoints // if (other != null){ return other.EndPoint.Equals(EndPoint); } return false; } public override bool Equals(object obj) { PeerEndPoint comparandPeerEndPoint = obj as PeerEndPoint; if (comparandPeerEndPoint != null){ return comparandPeerEndPoint.EndPoint.Equals(EndPoint); } return false; } public new static bool Equals(object objA, object objB) { PeerEndPoint comparandPeerEndPoint1 = objA as PeerEndPoint; PeerEndPoint comparandPeerEndPoint2 = objB as PeerEndPoint; if ((comparandPeerEndPoint1 != null) && (comparandPeerEndPoint2 != null)){ return comparandPeerEndPoint1.EndPoint.Equals(comparandPeerEndPoint2.EndPoint); } return false; } public override int GetHashCode() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return EndPoint.GetHashCode(); } public override string ToString() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_endPointName; } private bool m_Disposed; // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: Dispose(Boolean):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeNameChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] protected virtual void Dispose(bool disposing) { if (!m_Disposed){ CollaborationHelperFunctions.CleanEventVars(ref m_regNameChangedWaitHandle, ref m_safeNameChangedEvent, ref m_nameChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean NameChanged variables successful."); } m_Disposed = true; } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="GetObjectData(SerializationInfo, StreamingContext):Void" /> // </SecurityKernel> [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.Net.dll is still using pre-v4 security model and needs this demand")] [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } /// <summary> /// This is made virtual so that derived types can be implemented correctly /// </summary> [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("_EndPointName", m_endPointName); info.AddValue("_EndPoint", m_endPoint); } internal void TracePeerEndPoint() { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Contents of the PeerEndPoint"); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tEndPoint: {0}", (EndPoint != null? EndPoint.ToString(): null)); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tDescription: {0}", Name); } } /// <summary> /// Represents a collection of PeerEndPoints /// </summary> [Serializable] public class PeerEndPointCollection : Collection<PeerEndPoint>, IEquatable<PeerEndPointCollection> { internal PeerEndPointCollection() { } protected override void SetItem(int index, PeerEndPoint item) { // // Null peerendpoints not allowed // if (item == null){ throw new ArgumentNullException("item"); } base.SetItem(index, item); } protected override void InsertItem(int index, PeerEndPoint item) { // // Null peerendpoints not allowed // if (item == null){ throw new ArgumentNullException("item"); } base.InsertItem(index, item); } public override string ToString() { bool first = true; StringBuilder builder = new StringBuilder(); foreach (PeerEndPoint peerEndPoint in this){ if (!first){ builder.Append(", "); } else{ first = false; } builder.Append(peerEndPoint.ToString()); } return builder.ToString(); } public bool Equals(PeerEndPointCollection other) { bool equal = false; if (other != null){ foreach (PeerEndPoint peerEndPoint1 in other) foreach (PeerEndPoint peerEndPoint2 in this) if (!peerEndPoint1.Equals(peerEndPoint2)){ return equal; } equal = true; } return equal; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond.Expressions { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; public class ObjectParser : IParser { static readonly MethodInfo moveNext = Reflection.MethodInfoOf((IEnumerator e) => e.MoveNext()); static readonly ConstructorInfo arraySegmentCtor = typeof(ArraySegment<byte>).GetConstructor(typeof(byte[])); delegate Expression ContainerItemHandler(Expression value, Expression next, Expression count); readonly ParameterExpression objParam; readonly TypeAlias typeAlias; readonly Expression value; readonly Type schemaType; readonly Type objectType; readonly int hierarchyDepth; public ObjectParser(Type type) { typeAlias = new TypeAlias(type); value = objParam = Expression.Parameter(typeof(object), "obj"); objectType = schemaType = type; hierarchyDepth = type.GetHierarchyDepth(); } ObjectParser(ObjectParser that, Expression value, Type schemaType) { typeAlias = that.typeAlias; objParam = that.objParam; this.value = value; this.schemaType = schemaType; objectType = value.Type; hierarchyDepth = schemaType.GetHierarchyDepth(); } public ParameterExpression ReaderParam { get { return objParam; } } public Expression ReaderValue { get { return value; } } public int HierarchyDepth { get { return hierarchyDepth; } } public bool IsBonded { get { return schemaType.IsBonded(); } } public Expression Apply(ITransform transform) { var structVar = Expression.Variable(objectType, objectType.Name); var body = new List<Expression> { Expression.Assign(structVar, Expression.Convert(objParam, objectType)), transform.Begin }; var baseType = schemaType.GetBaseSchemaType(); if (baseType != null) { var baseObject = Expression.Convert(structVar, objectType.GetBaseSchemaType()); body.Add(transform.Base(new ObjectParser(this, baseObject, baseType))); } // Performs left outer join of object fields with transform fields. // The result contains entry for each schema field. For fields not handled // by the transform default to Skip. body.AddRange( from objectField in schemaType.GetSchemaFields() join transfromField in transform.Fields on objectField.Id equals transfromField.Id into fields from knownField in fields.DefaultIfEmpty() select Field(transform, structVar, objectField.Id, objectField, knownField)); body.Add(transform.End); return Expression.Block( new [] { structVar }, body); } Expression Field(ITransform transform, Expression structVar, UInt16 id, ISchemaField schemaField, IField field) { var fieldSchemaType = schemaField.GetSchemaType(); var fieldId = Expression.Constant(id); var fieldType = Expression.Constant(fieldSchemaType.GetBondDataType()); var fieldValue = DataExpression.PropertyOrField(structVar, schemaField.Name); var parser = new ObjectParser(this, fieldValue, fieldSchemaType); var processField = field != null ? field.Value(parser, fieldType) : transform.UnknownField(parser, fieldType, fieldId) ?? Expression.Empty(); var omitField = field != null ? field.Omitted : Expression.Empty(); Expression cannotOmit; if (fieldSchemaType.IsBondStruct() || fieldSchemaType.IsBonded() || schemaField.GetModifier() != Modifier.Optional) { cannotOmit = Expression.Constant(true); } else { var defaultValue = schemaField.GetDefaultValue(); if (fieldSchemaType.IsBondBlob()) { cannotOmit = Expression.NotEqual( typeAlias.Convert(fieldValue, fieldSchemaType), Expression.Default(typeof(ArraySegment<byte>))); } else if (fieldSchemaType.IsBondContainer()) { cannotOmit = defaultValue == null ? Expression.NotEqual(fieldValue, Expression.Constant(null)) : Expression.NotEqual(ContainerCount(fieldValue), Expression.Constant(0)); } else { cannotOmit = Expression.NotEqual(fieldValue, Expression.Constant(defaultValue)); } } return PrunedExpression.IfThenElse(cannotOmit, processField, omitField); } public Expression Container(BondDataType? expectedType, ContainerHandler handler) { if (schemaType.IsBondNullable()) return Nullable(handler); if (schemaType.IsBondBlob()) return BlobContainer(handler); var itemType = schemaType.GetValueType(); ContainerItemHandler itemHandler = (item, next, count) => handler( new ObjectParser(this, item, itemType), Expression.Constant(itemType.GetBondDataType()), next, count); if (value.Type.IsArray) return ArrayContainer(itemHandler); if (value.Type.IsGenericType()) { if (typeof(IList<>).MakeGenericType(value.Type.GetGenericArguments()[0]).IsAssignableFrom(value.Type)) return ListContainer(itemHandler); if (typeof(LinkedList<>) == value.Type.GetGenericTypeDefinition()) return LinkedListContainer(itemHandler); } return EnumerableContainer(itemHandler); } public Expression Map(BondDataType? expectedKeyType, BondDataType? expectedValueType, MapHandler handler) { Debug.Assert(schemaType.IsBondMap()); var itemType = schemaType.GetKeyValueType(); return EnumerableContainer((item, next, count) => handler( new ObjectParser(this, Expression.Property(item, "Key"), itemType.Key), new ObjectParser(this, Expression.Property(item, "Value"), itemType.Value), Expression.Constant(itemType.Key.GetBondDataType()), Expression.Constant(itemType.Value.GetBondDataType()), next, Expression.Empty(), count)); } public Expression Scalar(Expression valueType, BondDataType expectedType, ValueHandler handler) { Debug.Assert(expectedType == schemaType.GetBondDataType()); return handler(typeAlias.Convert(value, schemaType)); } public Expression Bonded(ValueHandler handler) { if (schemaType.IsBonded()) { return handler(value); } var bondedType = typeof(Bonded<>).MakeGenericType(objectType); var bondedCtor = bondedType.GetConstructor(objectType); return handler(Expression.New(bondedCtor, value)); } public Expression Blob(Expression count) { if (schemaType.IsBondBlob()) return typeAlias.Convert(value, schemaType); if (objectType == typeof(byte[])) return Expression.New(arraySegmentCtor, value); // TODO: convert List<sbyte> to ArraySegment<byte> for faster serialization? return null; } public Expression Skip(Expression valueType) { return Expression.Empty(); } public override bool Equals(object that) { Debug.Assert(that is ObjectParser); return schemaType.IsBondStruct() && schemaType == (that as ObjectParser).schemaType; } public override int GetHashCode() { return schemaType.GetHashCode(); } static Expression ContainerCount(Expression container) { if (container.Type.IsArray) return Expression.ArrayLength(container); if (container.Type.IsBondBlob()) return Expression.Property(container, "Count"); return Expression.Property(container, container.Type.GetDeclaredProperty(typeof(ICollection<>), "Count", typeof(int))); } Expression EnumerableContainer(ContainerItemHandler handler) { Debug.Assert(schemaType.IsBondContainer()); var methodGetEnumerator = value.Type.GetMethod(typeof(IEnumerable<>), "GetEnumerator"); Debug.Assert(methodGetEnumerator != null, "Container must provide GetEnumerator method"); var enumerator = Expression.Variable(methodGetEnumerator.ReturnType, "enumerator"); var item = Expression.Property(enumerator, "Current"); var next = Expression.Call(enumerator, moveNext); return Expression.Block( new[] { enumerator }, Expression.Assign(enumerator, Expression.Call(value, methodGetEnumerator)), handler(item, next, ContainerCount(value))); } Expression ListContainer(ContainerItemHandler handler) { Debug.Assert(schemaType.IsBondContainer()); var count = Expression.Variable(typeof(int), "count"); var index = Expression.Variable(typeof(int), "index"); var item = Expression.Property(value, "Item", new Expression[] { index }); var next = Expression.LessThan(Expression.PreIncrementAssign(index), count); return Expression.Block( new[] { index, count }, Expression.Assign(index, Expression.Constant(-1)), Expression.Assign(count, ContainerCount(value)), handler(item, next, count)); } Expression ArrayContainer(ContainerItemHandler handler) { Debug.Assert(schemaType.IsBondContainer()); var count = Expression.Variable(typeof(int), "count"); var index = Expression.Variable(typeof(int), "index"); var item = Expression.ArrayAccess(value, new Expression[] { index }); var next = Expression.LessThan(Expression.PreIncrementAssign(index), count); return Expression.Block( new[] { index, count }, Expression.Assign(index, Expression.Constant(-1)), Expression.Assign(count, Expression.ArrayLength(value)), handler(item, next, count)); } Expression LinkedListContainer(ContainerItemHandler handler) { Debug.Assert(schemaType.IsBondContainer()); var nodeType = typeof(LinkedListNode<>).MakeGenericType(value.Type.GetGenericArguments()[0]); var node = Expression.Variable(nodeType, "node"); var item = Expression.Property(node, "Value"); var next = Expression.NotEqual( Expression.Condition( Expression.Equal(node, Expression.Constant(null)), Expression.Assign(node, Expression.Property(value, "First")), Expression.Assign(node, Expression.Property(node, "Next"))), Expression.Constant(null)); return Expression.Block( new[] { node }, Expression.Assign(node, Expression.Constant(null, nodeType)), handler(item, next, ContainerCount(value))); } Expression Nullable(ContainerHandler handler) { Debug.Assert(schemaType.IsBondNullable()); var valueType = schemaType.GetValueType(); var count = Expression.Variable(typeof(int), "count"); var nullableValue = valueType.IsBondBlob() ? Expression.Property(typeAlias.Convert(value, valueType), "Array") : value; var notNull = Expression.NotEqual(nullableValue, Expression.Constant(null)); var loop = handler( new ObjectParser(this, value, valueType), Expression.Constant(valueType.GetBondDataType()), Expression.NotEqual(Expression.PostDecrementAssign(count), Expression.Constant(0)), count); return Expression.Block( new[] { count }, Expression.Assign(count, Expression.Condition(notNull, Expression.Constant(1), Expression.Constant(0))), loop); } Expression BlobContainer(ContainerHandler handler) { Debug.Assert(schemaType.IsBondBlob()); var arraySegment = Expression.Variable(typeof(ArraySegment<byte>), "arraySegment"); var count = Expression.Variable(typeof(int), "count"); var index = Expression.Variable(typeof(int), "index"); var end = Expression.Variable(typeof(int), "end"); var blob = typeAlias.Convert(value, schemaType); var item = Expression.ArrayIndex(Expression.Property(arraySegment, "Array"), Expression.PostIncrementAssign(index)); var loop = handler( new ObjectParser(this, item, typeof(sbyte)), Expression.Constant(BondDataType.BT_INT8), Expression.LessThan(index, end), count); return Expression.Block( new[] { arraySegment, count, index, end }, Expression.Assign(arraySegment, blob), Expression.Assign(index, Expression.Property(arraySegment, "Offset")), Expression.Assign(count, Expression.Property(arraySegment, "Count")), Expression.Assign(end, Expression.Add(index, count)), loop); } } }
/* * TestEmit.cs - Test class "System.Reflection" invoke methods. * * Copyright (C) 2004 Southern Storm Software, Pty Ltd. * * Authors : Thong Nguyen ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using CSUnit; using System; using System.IO; using System.Reflection; public class TestInvoke : TestCase { public TestInvoke(String name) : base(name) { } // Set up for the tests. protected override void Setup() { } // Clean up after the tests. protected override void Cleanup() { } public struct Point { public int X; public int Y; public Point(int x, int y) { this.X = x; this.Y = y; } public override string ToString() { return String.Format("Point({0}, {1})", X, Y); } } public int FooWithInt(int x) { return x + 1; } public double FooWithDouble(double x) { return x + 1; } public Point FooWithPoint(Point p) { return new Point(p.X + 1, p.Y + 1); } public string FooWithString(string s) { return s.ToLower(); } public int FooWithIntByRef(ref int x) { x++; return x; } public double FooWithDoubleByRef(ref double x) { x++; return x; } public Point FooWithPointByRef(ref Point p) { p.X++; p.Y++; return p; } public string FooWithStringByRef(ref string s) { s = s.ToLower(); return s; } public void DoTest(string methodName, object arg, object expectedResult) { object retval; MethodInfo method; object[] args = new object[1]; method = typeof(TestInvoke).GetMethod(methodName); args[0] = arg; retval = method.Invoke(this, args); AssertEquals(String.Format("{0}=={1}", expectedResult, retval), expectedResult, retval); } public void TestInvokeWithInt() { DoTest("FooWithInt", 10, 11); } public void TestInvokeWithDouble() { DoTest("FooWithDouble", 10.31415926, 11.31415926); } public void TestInvokeWithPoint() { DoTest("FooWithPoint", new Point(10, 20), new Point(11, 21)); } public void TestInvokeWithString() { DoTest("FooWithString", "POKWER", "pokwer"); } public void DoTestByRef(string methodName, object arg, object expectedResult, bool refShouldEqual) { object retval; MethodInfo method; object[] args = new object[1]; method = typeof(TestInvoke).GetMethod(methodName); args[0] = arg; retval = method.Invoke(this, args); AssertEquals("Check result", expectedResult, retval); if (refShouldEqual) { Assert("Check byref param refs=(1)", Object.ReferenceEquals(arg, args[0])); } else { Assert("Check byref param refs=(2)", !Object.ReferenceEquals(arg, args[0])); } AssertEquals("Check byref param value", expectedResult, args[0]); } public void TestInvokeWithIntByRef() { DoTestByRef("FooWithIntByRef", 10, 11, true); } public void TestInvokeWithDoubleByRef() { DoTestByRef("FooWithDoubleByRef", 10.31415926, 11.31415926, true); } public void TestInvokeWithPointByRef() { DoTestByRef("FooWithPointByRef", new Point(10, 20), new Point(11, 21), true); } public void TestInvokeWithStringByRef() { DoTestByRef("FooWithStringByRef", "POKWER", "pokwer", false); } public int InvokeValueTypeParamAsNull(int x) { AssertEquals("x=0", 0, x); return x + 1; } public void TestInvokeValueTypeParamAsNull() { object result; object[] args = new object[1]; MethodInfo method = typeof(TestInvoke).GetMethod("InvokeValueTypeParamAsNull"); result = method.Invoke(this, args); AssertEquals("result=1", 1, result); } public int InvokeValueTypeRefParamAsNull(ref int x) { x++; return x; } public void TestInvokeValueTypeRefParamAsNull() { object result; object[] args = new object[1]; MethodInfo method = typeof(TestInvoke).GetMethod("InvokeValueTypeRefParamAsNull"); result = method.Invoke(this, args); AssertEquals("result=1", 1, result); AssertEquals("args[0]=1", 1, args[0]); } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; /// <summary> /// Filters buffered log entries based on a set of conditions that are evaluated on a group of events. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/PostFilteringWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// PostFilteringWrapper must be used with some type of buffering target or wrapper, such as /// AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. /// </remarks> /// <example> /// <p> /// This example works like this. If there are no Warn,Error or Fatal messages in the buffer /// only Info messages are written to the file, but if there are any warnings or errors, /// the output includes detailed trace (levels &gt;= Debug). You can plug in a different type /// of buffering wrapper (such as ASPNetBufferingWrapper) to achieve different /// functionality. /// </p> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" /> /// </example> [Target("PostFilteringWrapper", IsWrapper = true)] public class PostFilteringTargetWrapper : WrapperTargetBase { private static object boxedTrue = true; /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper(Target wrappedTarget) : this(null, wrappedTarget) { } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public PostFilteringTargetWrapper(string name, Target wrappedTarget) { Name = name; WrappedTarget = wrappedTarget; Rules = new List<FilteringRule>(); } /// <summary> /// Gets or sets the default filter to be applied when no specific rule matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> public ConditionExpression DefaultFilter { get; set; } /// <summary> /// Gets the collection of filtering rules. The rules are processed top-down /// and the first rule that matches determines the filtering condition to /// be applied to log events. /// </summary> /// <docgen category='Filtering Rules' order='10' /> [ArrayParameter(typeof(FilteringRule), "when")] public IList<FilteringRule> Rules { get; private set; } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse) { OptimizeBufferReuse = GetType() == typeof(PostFilteringTargetWrapper); // Class not sealed, reduce breaking changes } } /// <inheritdoc/> protected override void Write(AsyncLogEventInfo logEvent) { Write((IList<AsyncLogEventInfo>)new[] { logEvent }); // Single LogEvent should also work } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected override void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Evaluates all filtering rules to find the first one that matches. /// The matching rule determines the filtering condition to be applied /// to all items in a buffer. If no condition matches, default filter /// is applied to the array of log events. /// </summary> /// <param name="logEvents">Array of log events to be post-filtered.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { InternalLogger.Trace("PostFilteringWrapper(Name={0}): Running on {1} events", Name, logEvents.Count); var resultFilter = EvaluateAllRules(logEvents) ?? DefaultFilter; if (resultFilter == null) { WrappedTarget.WriteAsyncLogEvents(logEvents); } else { InternalLogger.Trace("PostFilteringWrapper(Name={0}): Filter to apply: {1}", Name, resultFilter); var resultBuffer = logEvents.Filter(resultFilter, (logEvent, filter) => ApplyFilter(logEvent, filter)); InternalLogger.Trace("PostFilteringWrapper(Name={0}): After filtering: {1} events.", Name, resultBuffer.Count); if (resultBuffer.Count > 0) { InternalLogger.Trace("PostFilteringWrapper(Name={0}): Sending to {1}", Name, WrappedTarget); WrappedTarget.WriteAsyncLogEvents(resultBuffer); } } } private static bool ApplyFilter(AsyncLogEventInfo logEvent, ConditionExpression resultFilter) { object v = resultFilter.Evaluate(logEvent.LogEvent); if (boxedTrue.Equals(v)) { return true; } else { logEvent.Continuation(null); return false; } } /// <summary> /// Evaluate all the rules to get the filtering condition /// </summary> /// <param name="logEvents"></param> /// <returns></returns> private ConditionExpression EvaluateAllRules(IList<AsyncLogEventInfo> logEvents) { if (Rules.Count == 0) return null; for (int i = 0; i < logEvents.Count; ++i) { for (int j = 0; j < Rules.Count; ++j) { var rule = Rules[j]; object v = rule.Exists.Evaluate(logEvents[i].LogEvent); if (boxedTrue.Equals(v)) { InternalLogger.Trace("PostFilteringWrapper(Name={0}): Rule matched: {1}", Name, rule.Exists); return rule.Filter; } } } return null; } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.MultiTenancy { public sealed class MultiTenancyTests : IClassFixture<IntegrationTestContext<TestableStartup<MultiTenancyDbContext>, MultiTenancyDbContext>> { private static readonly Guid ThisTenantId = RouteTenantProvider.TenantRegistry["nld"]; private static readonly Guid OtherTenantId = RouteTenantProvider.TenantRegistry["ita"]; private readonly IntegrationTestContext<TestableStartup<MultiTenancyDbContext>, MultiTenancyDbContext> _testContext; private readonly MultiTenancyFakers _fakers = new(); public MultiTenancyTests(IntegrationTestContext<TestableStartup<MultiTenancyDbContext>, MultiTenancyDbContext> testContext) { _testContext = testContext; testContext.UseController<WebShopsController>(); testContext.UseController<WebProductsController>(); testContext.ConfigureServicesBeforeStartup(services => { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped<ITenantProvider, RouteTenantProvider>(); }); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceService<MultiTenantResourceService<WebShop>>(); services.AddResourceService<MultiTenantResourceService<WebProduct>>(); }); var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.UseRelativeLinks = true; } [Fact] public async Task Get_primary_resources_hides_other_tenants() { // Arrange List<WebShop> shops = _fakers.WebShop.Generate(2); shops[0].TenantId = OtherTenantId; shops[1].TenantId = ThisTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebShop>(); dbContext.WebShops.AddRange(shops); await dbContext.SaveChangesAsync(); }); const string route = "/nld/shops"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(shops[1].StringId); } [Fact] public async Task Filter_on_primary_resources_hides_other_tenants() { // Arrange List<WebShop> shops = _fakers.WebShop.Generate(2); shops[0].TenantId = OtherTenantId; shops[0].Products = _fakers.WebProduct.Generate(1); shops[1].TenantId = ThisTenantId; shops[1].Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebShop>(); dbContext.WebShops.AddRange(shops); await dbContext.SaveChangesAsync(); }); const string route = "/nld/shops?filter=has(products)"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(shops[1].StringId); } [Fact] public async Task Get_primary_resources_with_include_hides_other_tenants() { // Arrange List<WebShop> shops = _fakers.WebShop.Generate(2); shops[0].TenantId = OtherTenantId; shops[0].Products = _fakers.WebProduct.Generate(1); shops[1].TenantId = ThisTenantId; shops[1].Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebShop>(); dbContext.WebShops.AddRange(shops); await dbContext.SaveChangesAsync(); }); const string route = "/nld/shops?include=products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Type.Should().Be("webShops"); responseDocument.Data.ManyValue[0].Id.Should().Be(shops[1].StringId); responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Type.Should().Be("webProducts"); responseDocument.Included[0].Id.Should().Be(shops[1].Products[0].StringId); } [Fact] public async Task Cannot_get_primary_resource_by_ID_from_other_tenant() { // Arrange WebShop shop = _fakers.WebShop.Generate(); shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(shop); await dbContext.SaveChangesAsync(); }); string route = $"/nld/shops/{shop.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{shop.StringId}' does not exist."); } [Fact] public async Task Cannot_get_secondary_resources_from_other_parent_tenant() { // Arrange WebShop shop = _fakers.WebShop.Generate(); shop.TenantId = OtherTenantId; shop.Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(shop); await dbContext.SaveChangesAsync(); }); string route = $"/nld/shops/{shop.StringId}/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{shop.StringId}' does not exist."); } [Fact] public async Task Cannot_get_secondary_resource_from_other_parent_tenant() { // Arrange WebProduct product = _fakers.WebProduct.Generate(); product.Shop = _fakers.WebShop.Generate(); product.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(product); await dbContext.SaveChangesAsync(); }); string route = $"/nld/products/{product.StringId}/shop"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webProducts' with ID '{product.StringId}' does not exist."); } [Fact] public async Task Cannot_get_ToMany_relationship_for_other_parent_tenant() { // Arrange WebShop shop = _fakers.WebShop.Generate(); shop.TenantId = OtherTenantId; shop.Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(shop); await dbContext.SaveChangesAsync(); }); string route = $"/nld/shops/{shop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{shop.StringId}' does not exist."); } [Fact] public async Task Cannot_get_ToOne_relationship_for_other_parent_tenant() { // Arrange WebProduct product = _fakers.WebProduct.Generate(); product.Shop = _fakers.WebShop.Generate(); product.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(product); await dbContext.SaveChangesAsync(); }); string route = $"/nld/products/{product.StringId}/relationships/shop"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webProducts' with ID '{product.StringId}' does not exist."); } [Fact] public async Task Can_create_resource() { // Arrange string newShopUrl = _fakers.WebShop.Generate().Url; var requestBody = new { data = new { type = "webShops", attributes = new { url = newShopUrl } } }; const string route = "/nld/shops"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["url"].Should().Be(newShopUrl); responseDocument.Data.SingleValue.Relationships.Should().NotBeNull(); int newShopId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { WebShop shopInDatabase = await dbContext.WebShops.IgnoreQueryFilters().FirstWithIdAsync(newShopId); shopInDatabase.Url.Should().Be(newShopUrl); shopInDatabase.TenantId.Should().Be(ThisTenantId); }); } [Fact] public async Task Cannot_create_resource_with_ToMany_relationship_to_other_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; string newShopUrl = _fakers.WebShop.Generate().Url; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webShops", attributes = new { url = newShopUrl }, relationships = new { products = new { data = new[] { new { type = "webProducts", id = existingProduct.StringId } } } } } }; const string route = "/nld/shops"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webProducts' with ID '{existingProduct.StringId}' in relationship 'products' does not exist."); } [Fact] public async Task Cannot_create_resource_with_ToOne_relationship_to_other_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; string newProductName = _fakers.WebProduct.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(existingShop); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webProducts", attributes = new { name = newProductName }, relationships = new { shop = new { data = new { type = "webShops", id = existingShop.StringId } } } } }; const string route = "/nld/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webShops' with ID '{existingShop.StringId}' in relationship 'shop' does not exist."); } [Fact] public async Task Can_update_resource() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = ThisTenantId; string newProductName = _fakers.WebProduct.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webProducts", id = existingProduct.StringId, attributes = new { name = newProductName } } }; string route = $"/nld/products/{existingProduct.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WebProduct productInDatabase = await dbContext.WebProducts.IgnoreQueryFilters().FirstWithIdAsync(existingProduct.Id); productInDatabase.Name.Should().Be(newProductName); productInDatabase.Price.Should().Be(existingProduct.Price); }); } [Fact] public async Task Cannot_update_resource_from_other_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; string newProductName = _fakers.WebProduct.Generate().Name; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webProducts", id = existingProduct.StringId, attributes = new { name = newProductName } } }; string route = $"/nld/products/{existingProduct.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webProducts' with ID '{existingProduct.StringId}' does not exist."); } [Fact] public async Task Cannot_update_resource_with_ToMany_relationship_to_other_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = ThisTenantId; WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingShop, existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webShops", id = existingShop.StringId, relationships = new { products = new { data = new[] { new { type = "webProducts", id = existingProduct.StringId } } } } } }; string route = $"/nld/shops/{existingShop.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webProducts' with ID '{existingProduct.StringId}' in relationship 'products' does not exist."); } [Fact] public async Task Cannot_update_resource_with_ToOne_relationship_to_other_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = ThisTenantId; WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingProduct, existingShop); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webProducts", id = existingProduct.StringId, relationships = new { shop = new { data = new { type = "webShops", id = existingShop.StringId } } } } }; string route = $"/nld/products/{existingProduct.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webShops' with ID '{existingShop.StringId}' in relationship 'shop' does not exist."); } [Fact] public async Task Cannot_update_ToMany_relationship_for_other_parent_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; existingShop.Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(existingShop); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = Array.Empty<object>() }; string route = $"/nld/shops/{existingShop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{existingShop.StringId}' does not exist."); } [Fact] public async Task Cannot_update_ToMany_relationship_to_other_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = ThisTenantId; WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingShop, existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "webProducts", id = existingProduct.StringId } } }; string route = $"/nld/shops/{existingShop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webProducts' with ID '{existingProduct.StringId}' in relationship 'products' does not exist."); } [Fact] public async Task Cannot_update_ToOne_relationship_for_other_parent_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/nld/products/{existingProduct.StringId}/relationships/shop"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webProducts' with ID '{existingProduct.StringId}' does not exist."); } [Fact] public async Task Cannot_update_ToOne_relationship_to_other_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = ThisTenantId; WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingProduct, existingShop); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "webShops", id = existingShop.StringId } }; string route = $"/nld/products/{existingProduct.StringId}/relationships/shop"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webShops' with ID '{existingShop.StringId}' in relationship 'shop' does not exist."); } [Fact] public async Task Cannot_add_to_ToMany_relationship_for_other_parent_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = ThisTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingShop, existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "webProducts", id = existingProduct.StringId } } }; string route = $"/nld/shops/{existingShop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{existingShop.StringId}' does not exist."); } [Fact] public async Task Cannot_add_to_ToMany_relationship_with_other_tenant() { WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = ThisTenantId; WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.AddInRange(existingShop, existingProduct); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "webProducts", id = existingProduct.StringId } } }; string route = $"/nld/shops/{existingShop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be($"Related resource of type 'webProducts' with ID '{existingProduct.StringId}' in relationship 'products' does not exist."); } [Fact] public async Task Cannot_remove_from_ToMany_relationship_for_other_parent_tenant() { // Arrange WebShop existingShop = _fakers.WebShop.Generate(); existingShop.TenantId = OtherTenantId; existingShop.Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebShops.Add(existingShop); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "webProducts", id = existingShop.Products[0].StringId } } }; string route = $"/nld/shops/{existingShop.StringId}/relationships/products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webShops' with ID '{existingShop.StringId}' does not exist."); } [Fact] public async Task Can_delete_resource() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = ThisTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); string route = $"/nld/products/{existingProduct.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { WebProduct productInDatabase = await dbContext.WebProducts.IgnoreQueryFilters().FirstWithIdOrDefaultAsync(existingProduct.Id); productInDatabase.Should().BeNull(); }); } [Fact] public async Task Cannot_delete_resource_from_other_tenant() { // Arrange WebProduct existingProduct = _fakers.WebProduct.Generate(); existingProduct.Shop = _fakers.WebShop.Generate(); existingProduct.Shop.TenantId = OtherTenantId; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.WebProducts.Add(existingProduct); await dbContext.SaveChangesAsync(); }); string route = $"/nld/products/{existingProduct.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("The requested resource does not exist."); error.Detail.Should().Be($"Resource of type 'webProducts' with ID '{existingProduct.StringId}' does not exist."); } [Fact] public async Task Renders_links_with_tenant_route_parameter() { // Arrange WebShop shop = _fakers.WebShop.Generate(); shop.TenantId = ThisTenantId; shop.Products = _fakers.WebProduct.Generate(1); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<WebShop>(); dbContext.WebShops.Add(shop); await dbContext.SaveChangesAsync(); }); const string route = "/nld/shops?include=products"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().Be(route); responseDocument.Links.Last.Should().BeNull(); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string shopLink = $"/nld/shops/{shop.StringId}"; responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Links.Self.Should().Be(shopLink); responseDocument.Data.ManyValue[0].Relationships["products"].Links.Self.Should().Be($"{shopLink}/relationships/products"); responseDocument.Data.ManyValue[0].Relationships["products"].Links.Related.Should().Be($"{shopLink}/products"); string productLink = $"/nld/products/{shop.Products[0].StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(productLink); responseDocument.Included[0].Relationships["shop"].Links.Self.Should().Be($"{productLink}/relationships/shop"); responseDocument.Included[0].Relationships["shop"].Links.Related.Should().Be($"{productLink}/shop"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.ServiceModel.Syndication { using System.ServiceModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Xml; // NOTE: This class implements Clone so if you add any members, please update the copy ctor public class SyndicationFeed : IExtensibleSyndicationObject { private Collection<SyndicationPerson> _authors; private Uri _baseUri; private Collection<SyndicationCategory> _categories; private Collection<SyndicationPerson> _contributors; private TextSyndicationContent _copyright; private TextSyndicationContent _description; private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject(); private string _generator; private string _id; private Uri _imageUrl; private TextSyndicationContent _imageTitle; private Uri _imageLink; private IEnumerable<SyndicationItem> _items; private string _language; private DateTimeOffset _lastUpdatedTime; private Collection<SyndicationLink> _links; private TextSyndicationContent _title; // optional RSS tags private SyndicationLink _documentation; private int _timeToLive; private Collection<int> _skipHours; private Collection<string> _skipDays; private SyndicationTextInput _textInput; private Uri _iconImage; public Uri IconImage { get { return _iconImage; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _iconImage = value; } } internal SyndicationTextInput TextInput { get { return _textInput; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _textInput = value; } } public SyndicationLink Documentation { get { return _documentation; } set { _documentation = value; } } public int TimeToLive { get { return _timeToLive; } set { _timeToLive = value; } } public Collection<int> SkipHours { get { if (_skipHours == null) _skipHours = new Collection<int>(); return _skipHours; } } public Collection<string> SkipDays { get { if (_skipDays == null) _skipDays = new Collection<string>(); return _skipDays; } } //====================================== public SyndicationFeed() : this((IEnumerable<SyndicationItem>)null) { } public SyndicationFeed(IEnumerable<SyndicationItem> items) : this(null, null, null, items) { } public SyndicationFeed(string title, string description, Uri feedAlternateLink) : this(title, description, feedAlternateLink, null) { } public SyndicationFeed(string title, string description, Uri feedAlternateLink, IEnumerable<SyndicationItem> items) : this(title, description, feedAlternateLink, null, DateTimeOffset.MinValue, items) { } public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime) : this(title, description, feedAlternateLink, id, lastUpdatedTime, null) { } public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable<SyndicationItem> items) { if (title != null) { _title = new TextSyndicationContent(title); } if (description != null) { _description = new TextSyndicationContent(description); } if (feedAlternateLink != null) { Links.Add(SyndicationLink.CreateAlternateLink(feedAlternateLink)); } _id = id; _lastUpdatedTime = lastUpdatedTime; _items = items; } protected SyndicationFeed(SyndicationFeed source, bool cloneItems) { if (source == null) { throw new ArgumentNullException(nameof(source)); } _authors = FeedUtils.ClonePersons(source._authors); _categories = FeedUtils.CloneCategories(source._categories); _contributors = FeedUtils.ClonePersons(source._contributors); _copyright = FeedUtils.CloneTextContent(source._copyright); _description = FeedUtils.CloneTextContent(source._description); _extensions = source._extensions.Clone(); _generator = source._generator; _id = source._id; _imageUrl = source._imageUrl; _language = source._language; _lastUpdatedTime = source._lastUpdatedTime; _links = FeedUtils.CloneLinks(source._links); _title = FeedUtils.CloneTextContent(source._title); _baseUri = source._baseUri; IList<SyndicationItem> srcList = source._items as IList<SyndicationItem>; if (srcList != null) { Collection<SyndicationItem> tmp = new NullNotAllowedCollection<SyndicationItem>(); for (int i = 0; i < srcList.Count; ++i) { tmp.Add((cloneItems) ? srcList[i].Clone() : srcList[i]); } _items = tmp; } else { if (cloneItems) { throw new InvalidOperationException(SR.UnbufferedItemsCannotBeCloned); } _items = source._items; } } public Dictionary<XmlQualifiedName, string> AttributeExtensions { get { return _extensions.AttributeExtensions; } } public Collection<SyndicationPerson> Authors { get { if (_authors == null) { _authors = new NullNotAllowedCollection<SyndicationPerson>(); } return _authors; } } public Uri BaseUri { get { return _baseUri; } set { _baseUri = value; } } public Collection<SyndicationCategory> Categories { get { if (_categories == null) { _categories = new NullNotAllowedCollection<SyndicationCategory>(); } return _categories; } } public Collection<SyndicationPerson> Contributors { get { if (_contributors == null) { _contributors = new NullNotAllowedCollection<SyndicationPerson>(); } return _contributors; } } public TextSyndicationContent Copyright { get { return _copyright; } set { _copyright = value; } } public TextSyndicationContent Description { get { return _description; } set { _description = value; } } public SyndicationElementExtensionCollection ElementExtensions { get { return _extensions.ElementExtensions; } } public string Generator { get { return _generator; } set { _generator = value; } } public string Id { get { return _id; } set { _id = value; } } public Uri ImageUrl { get { return _imageUrl; } set { _imageUrl = value; } } public TextSyndicationContent ImageTitle { get { return _imageTitle; } set { _imageTitle = value; } } public Uri ImageLink { get { return _imageLink; } set { _imageLink = value; } } public IEnumerable<SyndicationItem> Items { get { if (_items == null) { _items = new NullNotAllowedCollection<SyndicationItem>(); } return _items; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _items = value; } } public string Language { get { return _language; } set { _language = value; } } public DateTimeOffset LastUpdatedTime { get { return _lastUpdatedTime; } set { _lastUpdatedTime = value; } } public Collection<SyndicationLink> Links { get { if (_links == null) { _links = new NullNotAllowedCollection<SyndicationLink>(); } return _links; } } public TextSyndicationContent Title { get { return _title; } set { _title = value; } } //// Custom Parsing public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter formatter, CancellationToken ct) { return await LoadAsync(reader, formatter, new Atom10FeedFormatter(), ct); } public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Atom10FeedFormatter formatter, CancellationToken ct) { return await LoadAsync(reader, new Rss20FeedFormatter(), formatter, ct); } public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter Rssformatter, Atom10FeedFormatter Atomformatter, CancellationToken ct) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } reader = XmlReaderWrapper.CreateFromReader(reader); Atom10FeedFormatter atomSerializer = Atomformatter; if (atomSerializer.CanRead(reader)) { await atomSerializer.ReadFromAsync(reader, new CancellationToken()); return atomSerializer.Feed; } Rss20FeedFormatter rssSerializer = Rssformatter; if (rssSerializer.CanRead(reader)) { await rssSerializer.ReadFromAsync(reader, new CancellationToken()); return rssSerializer.Feed; } throw new XmlException(SR.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)); } //================================= public static SyndicationFeed Load(XmlReader reader) { return Load<SyndicationFeed>(reader); } public static TSyndicationFeed Load<TSyndicationFeed>(XmlReader reader) where TSyndicationFeed : SyndicationFeed, new() { CancellationToken ct = new CancellationToken(); return LoadAsync<TSyndicationFeed>(reader, ct).GetAwaiter().GetResult(); } public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, CancellationToken ct) { return await LoadAsync<SyndicationFeed>(reader, ct); } public static async Task<TSyndicationFeed> LoadAsync<TSyndicationFeed>(XmlReader reader, CancellationToken ct) where TSyndicationFeed : SyndicationFeed, new() { Atom10FeedFormatter<TSyndicationFeed> atomSerializer = new Atom10FeedFormatter<TSyndicationFeed>(); if (atomSerializer.CanRead(reader)) { await atomSerializer.ReadFromAsync(reader, ct); return atomSerializer.Feed as TSyndicationFeed; } Rss20FeedFormatter<TSyndicationFeed> rssSerializer = new Rss20FeedFormatter<TSyndicationFeed>(); if (rssSerializer.CanRead(reader)) { await rssSerializer.ReadFromAsync(reader, ct); return rssSerializer.Feed as TSyndicationFeed; } throw new XmlException(SR.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI)); } public virtual SyndicationFeed Clone(bool cloneItems) { return new SyndicationFeed(this, cloneItems); } public Atom10FeedFormatter GetAtom10Formatter() { return new Atom10FeedFormatter(this); } public Rss20FeedFormatter GetRss20Formatter() { return GetRss20Formatter(true); } public Rss20FeedFormatter GetRss20Formatter(bool serializeExtensionsAsAtom) { return new Rss20FeedFormatter(this, serializeExtensionsAsAtom); } public void SaveAsAtom10(XmlWriter writer) { SaveAsAtom10Async(writer, CancellationToken.None).GetAwaiter().GetResult(); } public void SaveAsRss20(XmlWriter writer) { SaveAsRss20Async(writer, CancellationToken.None).GetAwaiter().GetResult(); } public Task SaveAsAtom10Async(XmlWriter writer, CancellationToken ct) { return GetAtom10Formatter().WriteToAsync(writer, ct); } public Task SaveAsRss20Async(XmlWriter writer, CancellationToken ct) { return GetRss20Formatter().WriteToAsync(writer, ct); } protected internal virtual SyndicationCategory CreateCategory() { return new SyndicationCategory(); } protected internal virtual SyndicationItem CreateItem() { return new SyndicationItem(); } protected internal virtual SyndicationLink CreateLink() { return new SyndicationLink(); } protected internal virtual SyndicationPerson CreatePerson() { return new SyndicationPerson(); } protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version) { return false; } protected internal virtual bool TryParseElement(XmlReader reader, string version) { return false; } protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version) { return _extensions.WriteAttributeExtensionsAsync(writer); } protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version) { return _extensions.WriteElementExtensionsAsync(writer); } protected internal virtual void WriteAttributeExtensions(XmlWriter writer, string version) { _extensions.WriteAttributeExtensions(writer); } protected internal virtual void WriteElementExtensions(XmlWriter writer, string version) { _extensions.WriteElementExtensions(writer); } internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize) { _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize); } internal void LoadElementExtensions(XmlBuffer buffer) { _extensions.LoadElementExtensions(buffer); } } }
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> /// Sundry Debtor Fees Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SDFCDataSet : EduHubDataSet<SDFC> { /// <inheritdoc /> public override string Name { get { return "SDFC"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SDFCDataSet(EduHubContext Context) : base(Context) { Index_GLCODE = new Lazy<NullDictionary<string, IReadOnlyList<SDFC>>>(() => this.ToGroupedNullDictionary(i => i.GLCODE)); Index_GST_TYPE = new Lazy<NullDictionary<string, IReadOnlyList<SDFC>>>(() => this.ToGroupedNullDictionary(i => i.GST_TYPE)); Index_INITIATIVE = new Lazy<NullDictionary<string, IReadOnlyList<SDFC>>>(() => this.ToGroupedNullDictionary(i => i.INITIATIVE)); Index_SDFCKEY = new Lazy<Dictionary<string, SDFC>>(() => this.ToDictionary(i => i.SDFCKEY)); Index_SUBPROGRAM = new Lazy<NullDictionary<string, IReadOnlyList<SDFC>>>(() => this.ToGroupedNullDictionary(i => i.SUBPROGRAM)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SDFC" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SDFC" /> fields for each CSV column header</returns> internal override Action<SDFC, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SDFC, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "SDFCKEY": mapper[i] = (e, v) => e.SDFCKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "SDGROUP": mapper[i] = (e, v) => e.SDGROUP = v; break; case "STATEMENT": mapper[i] = (e, v) => e.STATEMENT = v; break; case "METHOD": mapper[i] = (e, v) => e.METHOD = v; break; case "AMOUNT": mapper[i] = (e, v) => e.AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "GROSS_AMOUNT": mapper[i] = (e, v) => e.GROSS_AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "GLCODE": mapper[i] = (e, v) => e.GLCODE = v; break; case "GST_TYPE": mapper[i] = (e, v) => e.GST_TYPE = v; break; case "SUBPROGRAM": mapper[i] = (e, v) => e.SUBPROGRAM = v; break; case "GLPROGRAM": mapper[i] = (e, v) => e.GLPROGRAM = v; break; case "INITIATIVE": mapper[i] = (e, v) => e.INITIATIVE = v; 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="SDFC" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SDFC" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SDFC" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SDFC}"/> of entities</returns> internal override IEnumerable<SDFC> ApplyDeltaEntities(IEnumerable<SDFC> Entities, List<SDFC> DeltaEntities) { HashSet<string> Index_SDFCKEY = new HashSet<string>(DeltaEntities.Select(i => i.SDFCKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.SDFCKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_SDFCKEY.Remove(entity.SDFCKEY); if (entity.SDFCKEY.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<NullDictionary<string, IReadOnlyList<SDFC>>> Index_GLCODE; private Lazy<NullDictionary<string, IReadOnlyList<SDFC>>> Index_GST_TYPE; private Lazy<NullDictionary<string, IReadOnlyList<SDFC>>> Index_INITIATIVE; private Lazy<Dictionary<string, SDFC>> Index_SDFCKEY; private Lazy<NullDictionary<string, IReadOnlyList<SDFC>>> Index_SUBPROGRAM; #endregion #region Index Methods /// <summary> /// Find SDFC by GLCODE field /// </summary> /// <param name="GLCODE">GLCODE value used to find SDFC</param> /// <returns>List of related SDFC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> FindByGLCODE(string GLCODE) { return Index_GLCODE.Value[GLCODE]; } /// <summary> /// Attempt to find SDFC by GLCODE field /// </summary> /// <param name="GLCODE">GLCODE value used to find SDFC</param> /// <param name="Value">List of related SDFC entities</param> /// <returns>True if the list of related SDFC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGLCODE(string GLCODE, out IReadOnlyList<SDFC> Value) { return Index_GLCODE.Value.TryGetValue(GLCODE, out Value); } /// <summary> /// Attempt to find SDFC by GLCODE field /// </summary> /// <param name="GLCODE">GLCODE value used to find SDFC</param> /// <returns>List of related SDFC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> TryFindByGLCODE(string GLCODE) { IReadOnlyList<SDFC> value; if (Index_GLCODE.Value.TryGetValue(GLCODE, out value)) { return value; } else { return null; } } /// <summary> /// Find SDFC by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find SDFC</param> /// <returns>List of related SDFC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> FindByGST_TYPE(string GST_TYPE) { return Index_GST_TYPE.Value[GST_TYPE]; } /// <summary> /// Attempt to find SDFC by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find SDFC</param> /// <param name="Value">List of related SDFC entities</param> /// <returns>True if the list of related SDFC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGST_TYPE(string GST_TYPE, out IReadOnlyList<SDFC> Value) { return Index_GST_TYPE.Value.TryGetValue(GST_TYPE, out Value); } /// <summary> /// Attempt to find SDFC by GST_TYPE field /// </summary> /// <param name="GST_TYPE">GST_TYPE value used to find SDFC</param> /// <returns>List of related SDFC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> TryFindByGST_TYPE(string GST_TYPE) { IReadOnlyList<SDFC> value; if (Index_GST_TYPE.Value.TryGetValue(GST_TYPE, out value)) { return value; } else { return null; } } /// <summary> /// Find SDFC by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find SDFC</param> /// <returns>List of related SDFC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> FindByINITIATIVE(string INITIATIVE) { return Index_INITIATIVE.Value[INITIATIVE]; } /// <summary> /// Attempt to find SDFC by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find SDFC</param> /// <param name="Value">List of related SDFC entities</param> /// <returns>True if the list of related SDFC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByINITIATIVE(string INITIATIVE, out IReadOnlyList<SDFC> Value) { return Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out Value); } /// <summary> /// Attempt to find SDFC by INITIATIVE field /// </summary> /// <param name="INITIATIVE">INITIATIVE value used to find SDFC</param> /// <returns>List of related SDFC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> TryFindByINITIATIVE(string INITIATIVE) { IReadOnlyList<SDFC> value; if (Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out value)) { return value; } else { return null; } } /// <summary> /// Find SDFC by SDFCKEY field /// </summary> /// <param name="SDFCKEY">SDFCKEY value used to find SDFC</param> /// <returns>Related SDFC entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SDFC FindBySDFCKEY(string SDFCKEY) { return Index_SDFCKEY.Value[SDFCKEY]; } /// <summary> /// Attempt to find SDFC by SDFCKEY field /// </summary> /// <param name="SDFCKEY">SDFCKEY value used to find SDFC</param> /// <param name="Value">Related SDFC entity</param> /// <returns>True if the related SDFC entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySDFCKEY(string SDFCKEY, out SDFC Value) { return Index_SDFCKEY.Value.TryGetValue(SDFCKEY, out Value); } /// <summary> /// Attempt to find SDFC by SDFCKEY field /// </summary> /// <param name="SDFCKEY">SDFCKEY value used to find SDFC</param> /// <returns>Related SDFC entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SDFC TryFindBySDFCKEY(string SDFCKEY) { SDFC value; if (Index_SDFCKEY.Value.TryGetValue(SDFCKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find SDFC by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find SDFC</param> /// <returns>List of related SDFC entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> FindBySUBPROGRAM(string SUBPROGRAM) { return Index_SUBPROGRAM.Value[SUBPROGRAM]; } /// <summary> /// Attempt to find SDFC by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find SDFC</param> /// <param name="Value">List of related SDFC entities</param> /// <returns>True if the list of related SDFC entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySUBPROGRAM(string SUBPROGRAM, out IReadOnlyList<SDFC> Value) { return Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out Value); } /// <summary> /// Attempt to find SDFC by SUBPROGRAM field /// </summary> /// <param name="SUBPROGRAM">SUBPROGRAM value used to find SDFC</param> /// <returns>List of related SDFC entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SDFC> TryFindBySUBPROGRAM(string SUBPROGRAM) { IReadOnlyList<SDFC> value; if (Index_SUBPROGRAM.Value.TryGetValue(SUBPROGRAM, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SDFC 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].[SDFC]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SDFC]( [SDFCKEY] varchar(10) NOT NULL, [DESCRIPTION] varchar(30) NULL, [SDGROUP] varchar(10) NULL, [STATEMENT] varchar(1) NULL, [METHOD] varchar(1) NULL, [AMOUNT] money NULL, [GROSS_AMOUNT] money NULL, [GLCODE] varchar(10) NULL, [GST_TYPE] varchar(4) NULL, [SUBPROGRAM] varchar(4) NULL, [GLPROGRAM] varchar(3) NULL, [INITIATIVE] varchar(3) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SDFC_Index_SDFCKEY] PRIMARY KEY CLUSTERED ( [SDFCKEY] ASC ) ); CREATE NONCLUSTERED INDEX [SDFC_Index_GLCODE] ON [dbo].[SDFC] ( [GLCODE] ASC ); CREATE NONCLUSTERED INDEX [SDFC_Index_GST_TYPE] ON [dbo].[SDFC] ( [GST_TYPE] ASC ); CREATE NONCLUSTERED INDEX [SDFC_Index_INITIATIVE] ON [dbo].[SDFC] ( [INITIATIVE] ASC ); CREATE NONCLUSTERED INDEX [SDFC_Index_SUBPROGRAM] ON [dbo].[SDFC] ( [SUBPROGRAM] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_GLCODE') ALTER INDEX [SDFC_Index_GLCODE] ON [dbo].[SDFC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_GST_TYPE') ALTER INDEX [SDFC_Index_GST_TYPE] ON [dbo].[SDFC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_INITIATIVE') ALTER INDEX [SDFC_Index_INITIATIVE] ON [dbo].[SDFC] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_SUBPROGRAM') ALTER INDEX [SDFC_Index_SUBPROGRAM] ON [dbo].[SDFC] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_GLCODE') ALTER INDEX [SDFC_Index_GLCODE] ON [dbo].[SDFC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_GST_TYPE') ALTER INDEX [SDFC_Index_GST_TYPE] ON [dbo].[SDFC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_INITIATIVE') ALTER INDEX [SDFC_Index_INITIATIVE] ON [dbo].[SDFC] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SDFC]') AND name = N'SDFC_Index_SUBPROGRAM') ALTER INDEX [SDFC_Index_SUBPROGRAM] ON [dbo].[SDFC] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SDFC"/> 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="SDFC"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SDFC> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_SDFCKEY = new List<string>(); foreach (var entity in Entities) { Index_SDFCKEY.Add(entity.SDFCKEY); } builder.AppendLine("DELETE [dbo].[SDFC] WHERE"); // Index_SDFCKEY builder.Append("[SDFCKEY] IN ("); for (int index = 0; index < Index_SDFCKEY.Count; index++) { if (index != 0) builder.Append(", "); // SDFCKEY var parameterSDFCKEY = $"@p{parameterIndex++}"; builder.Append(parameterSDFCKEY); command.Parameters.Add(parameterSDFCKEY, SqlDbType.VarChar, 10).Value = Index_SDFCKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SDFC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SDFC data set</returns> public override EduHubDataSetDataReader<SDFC> GetDataSetDataReader() { return new SDFCDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SDFC data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SDFC data set</returns> public override EduHubDataSetDataReader<SDFC> GetDataSetDataReader(List<SDFC> Entities) { return new SDFCDataReader(new EduHubDataSetLoadedReader<SDFC>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SDFCDataReader : EduHubDataSetDataReader<SDFC> { public SDFCDataReader(IEduHubDataSetReader<SDFC> Reader) : base (Reader) { } public override int FieldCount { get { return 15; } } public override object GetValue(int i) { switch (i) { case 0: // SDFCKEY return Current.SDFCKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // SDGROUP return Current.SDGROUP; case 3: // STATEMENT return Current.STATEMENT; case 4: // METHOD return Current.METHOD; case 5: // AMOUNT return Current.AMOUNT; case 6: // GROSS_AMOUNT return Current.GROSS_AMOUNT; case 7: // GLCODE return Current.GLCODE; case 8: // GST_TYPE return Current.GST_TYPE; case 9: // SUBPROGRAM return Current.SUBPROGRAM; case 10: // GLPROGRAM return Current.GLPROGRAM; case 11: // INITIATIVE return Current.INITIATIVE; case 12: // LW_DATE return Current.LW_DATE; case 13: // LW_TIME return Current.LW_TIME; case 14: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // SDGROUP return Current.SDGROUP == null; case 3: // STATEMENT return Current.STATEMENT == null; case 4: // METHOD return Current.METHOD == null; case 5: // AMOUNT return Current.AMOUNT == null; case 6: // GROSS_AMOUNT return Current.GROSS_AMOUNT == null; case 7: // GLCODE return Current.GLCODE == null; case 8: // GST_TYPE return Current.GST_TYPE == null; case 9: // SUBPROGRAM return Current.SUBPROGRAM == null; case 10: // GLPROGRAM return Current.GLPROGRAM == null; case 11: // INITIATIVE return Current.INITIATIVE == null; case 12: // LW_DATE return Current.LW_DATE == null; case 13: // LW_TIME return Current.LW_TIME == null; case 14: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // SDFCKEY return "SDFCKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // SDGROUP return "SDGROUP"; case 3: // STATEMENT return "STATEMENT"; case 4: // METHOD return "METHOD"; case 5: // AMOUNT return "AMOUNT"; case 6: // GROSS_AMOUNT return "GROSS_AMOUNT"; case 7: // GLCODE return "GLCODE"; case 8: // GST_TYPE return "GST_TYPE"; case 9: // SUBPROGRAM return "SUBPROGRAM"; case 10: // GLPROGRAM return "GLPROGRAM"; case 11: // INITIATIVE return "INITIATIVE"; case 12: // LW_DATE return "LW_DATE"; case 13: // LW_TIME return "LW_TIME"; case 14: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "SDFCKEY": return 0; case "DESCRIPTION": return 1; case "SDGROUP": return 2; case "STATEMENT": return 3; case "METHOD": return 4; case "AMOUNT": return 5; case "GROSS_AMOUNT": return 6; case "GLCODE": return 7; case "GST_TYPE": return 8; case "SUBPROGRAM": return 9; case "GLPROGRAM": return 10; case "INITIATIVE": return 11; case "LW_DATE": return 12; case "LW_TIME": return 13; case "LW_USER": return 14; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using java.io; using java.lang; using java.net; using java.nio; using java.text; using java.util; using RSUtilities.Compression; namespace OpenRSS.Cache { /// <summary> /// A <seealso cref="Container" /> holds an optionally compressed file. This class can be /// used to decompress and compress containers. A container can also have a two /// byte trailer which specifies the version of the file within it. /// @author Graham /// @author `Discardedx2 /// </summary> public sealed class Container { /// <summary> /// This type indicates that no compression is used. /// </summary> public const int COMPRESSION_NONE = 0; /// <summary> /// This type indicates that BZIP2 compression is used. /// </summary> public const int COMPRESSION_BZIP2 = 1; /// <summary> /// This type indicates that GZIP compression is used. /// </summary> public const int COMPRESSION_GZIP = 2; /// <summary> /// The decompressed data. /// </summary> private ByteBuffer data; /// <summary> /// The type of compression this container uses. /// </summary> private int type; /// <summary> /// The version of the file within this container. /// </summary> private int version; /// <summary> /// Creates a new unversioned container. /// </summary> /// <param name="type"> The type of compression. </param> /// <param name="data"> The decompressed data. </param> public Container(int type, ByteBuffer data) : this(type, data, -1) { } /// <summary> /// Creates a new versioned container. /// </summary> /// <param name="type"> The type of compression. </param> /// <param name="data"> The decompressed data. </param> /// <param name="version"> The version of the file within this container. </param> public Container(int type, ByteBuffer data, int version) { this.type = type; this.data = data; this.version = version; } /// <summary> /// Decodes and decompresses the container. /// </summary> /// <param name="buffer"> The buffer. </param> /// <returns> The decompressed container. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public static Container Decode(ByteBuffer buffer) { /* decode the type and length */ var type = buffer.get() & 0xFF; var length = buffer.getInt(); /* check if we should decompress the data or not */ if (type == COMPRESSION_NONE) { /* simply grab the data and wrap it in a buffer */ var temp = new byte[length]; buffer.get(temp); var data = ByteBuffer.wrap(temp); /* decode the version if present */ var version = -1; if (buffer.remaining() >= 2) { version = buffer.getShort(); } /* and return the decoded container */ return new Container(type, data, version); } else { /* grab the length of the uncompressed data */ var uncompressedLength = buffer.getInt(); /* grab the data */ var compressed = new byte[length]; buffer.get(compressed); /* uncompress it */ byte[] uncompressed; if (type == COMPRESSION_BZIP2) { uncompressed = CompressionUtils.Bunzip2(compressed); } else if (type == COMPRESSION_GZIP) { uncompressed = CompressionUtils.Gunzip(compressed); } else { throw new IOException("Invalid compression type"); } /* check if the lengths are equal */ if (uncompressed.Length != uncompressedLength) { throw new IOException("Length mismatch"); } /* decode the version if present */ var version = -1; if (buffer.remaining() >= 2) { version = buffer.getShort(); } /* and return the decoded container */ return new Container(type, ByteBuffer.wrap(uncompressed), version); } } /// <summary> /// Checks if this container is versioned. /// </summary> /// <returns> {@code true} if so, {@code false} if not. </returns> public bool IsVersioned() { return version != -1; } /// <summary> /// Gets the version of the file in this container. /// </summary> /// <returns> The version of the file. </returns> /// <exception cref="IllegalArgumentException"> if this container is not versioned. </exception> public int GetVersion() { if (!IsVersioned()) { throw new IllegalStateException(); } return version; } /// <summary> /// Sets the version of this container. /// </summary> /// <param name="version"> The version. </param> public void SetVersion(int version) { this.version = version; } /// <summary> /// Removes the version on this container so it becomes unversioned. /// </summary> public void RemoveVersion() { version = -1; } /// <summary> /// Sets the type of this container. /// </summary> /// <param name="type"> The compression type. </param> public void SetType(int type) { this.type = type; } /// <summary> /// Gets the type of this container. /// </summary> /// <returns> The compression type. </returns> public int GetType() { return type; } /// <summary> /// Gets the decompressed data. /// </summary> /// <returns> The decompressed data. </returns> public ByteBuffer GetData() { return data.asReadOnlyBuffer(); } /// <summary> /// Encodes and compresses this container. /// </summary> /// <returns> The buffer. </returns> /// <exception cref="IOException"> if an I/O error occurs. </exception> public ByteBuffer Encode() { var data = GetData(); // so we have a read only view, making this method thread safe /* grab the data as a byte array for compression */ var bytes = new byte[data.limit()]; data.mark(); data.get(bytes); data.reset(); /* compress the data */ byte[] compressed; if (type == COMPRESSION_NONE) { compressed = bytes; } else if (type == COMPRESSION_GZIP) { compressed = CompressionUtils.Gzip(bytes); } else if (type == COMPRESSION_BZIP2) { compressed = CompressionUtils.Bzip2(bytes); } else { throw new IOException("Invalid compression type"); } /* calculate the size of the header and trailer and allocate a buffer */ var header = 5 + (type == COMPRESSION_NONE ? 0 : 4) + (IsVersioned() ? 2 : 0); var buf = ByteBuffer.allocate(header + compressed.Length); /* write the header, with the optional uncompressed length */ buf.put((byte) type); buf.putInt(compressed.Length); if (type != COMPRESSION_NONE) { buf.putInt(data.limit()); } /* write the compressed length */ buf.put(compressed); /* write the trailer with the optional version */ if (IsVersioned()) { buf.putShort((short) version); } /* flip the buffer and return it */ return (ByteBuffer) buf.flip(); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using System.Collections.ObjectModel; using Xunit; namespace System.Threading.Tasks.Dataflow.Tests { public partial class DataflowBlockTests : DataflowBlockTestBase { [Fact] public void RunTransformManyBlockTests() { Assert.True(IDataflowBlockTestHelper.TestToString(nameFormat => nameFormat != null ? new TransformManyBlock<int, int>(x => new int[] { x }, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) : new TransformManyBlock<int, int>(x => new int[] { x }))); Assert.True(ISourceBlockTestHelper.TestLinkTo<int>(ConstructTransformManyWithNMessages(2), 1)); Assert.True(ISourceBlockTestHelper.TestReserveMessageAndReleaseReservation<int>(ConstructTransformManyWithNMessages(1))); Assert.True(ISourceBlockTestHelper.TestConsumeMessage<int>(ConstructTransformManyWithNMessages(1))); Assert.True(ISourceBlockTestHelper.TestTryReceiveWithFilter<int>(ConstructTransformManyWithNMessages(1), 1)); Assert.True(ISourceBlockTestHelper.TestTryReceiveAll<int>(ConstructTransformManyWithNMessages(1), 1)); Assert.True(ITargetBlockTestHelper.TestOfferMessage<int>(new TransformManyBlock<int, int>(i => new int[] { i }))); Assert.True(ITargetBlockTestHelper.TestPost<int>(new TransformManyBlock<int, int>(i => new int[] { i }))); Assert.True(ITargetBlockTestHelper.TestComplete<int>(new TransformManyBlock<int, int>(i => new int[] { i }))); Assert.True(ITargetBlockTestHelper.TestCompletionTask<int>(new TransformManyBlock<int, int>(i => new int[] { i }))); Assert.True(ITargetBlockTestHelper.TestNonGreedyPost(new TransformManyBlock<int, int>(x => { Task.Delay(500).Wait(); return new int[] { x }; }, new ExecutionDataflowBlockOptions { BoundedCapacity = 1 }))); } private static TransformManyBlock<int, int> ConstructTransformManyWithNMessages(int messagesCount) { var block = new TransformManyBlock<int, int>(i => new int[] { i }); for (int i = 0; i < messagesCount; i++) { block.Post(i); } // Spin until the messages have been properly buffered up. // Otherwise TryReceive fails. SpinWait.SpinUntil(() => block.OutputCount == messagesCount); return block; } [Fact] public void TestTransformManyBlockConstructor() { // IEnumerable without option var block = new TransformManyBlock<int, string>(i => new string[10]); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); // Task without option block = new TransformManyBlock<int, string>(i => Task.Factory.StartNew(() => (IEnumerable<string>)new string[10])); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); // IEnumerable with not cancelled token and default scheduler block = new TransformManyBlock<int, string>(i => new string[10], new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); // Task with not cancelled token and default scheduler block = new TransformManyBlock<int, string>(i => Task.Factory.StartNew(() => (IEnumerable<string>)new string[10]), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); // IEnumerable with a cancelled token and default scheduler var token = new CancellationToken(true); block = new TransformManyBlock<int, string>(i => new string[10], new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token }); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); // Task with a cancelled token and default scheduler token = new CancellationToken(true); block = new TransformManyBlock<int, string>(i => Task.Factory.StartNew(() => (IEnumerable<string>)new string[10]), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1, CancellationToken = token }); Assert.False(block.InputCount != 0, "Constructor failed! InputCount returned a non zero value for a brand new TransformManyBlock."); } [Fact] public void TestTransformManyBlockInvalidArgumentValidation() { bool passed = true; Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, string>((Func<int, IEnumerable<string>>)null)); Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, string>((Func<int, Task<IEnumerable<string>>>)null)); Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, string>(i => new[] { i.ToString() }, null)); Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, string>(i => Task.Factory.StartNew(() => (IEnumerable<string>)new[] { i.ToString() }), null)); passed &= ITargetBlockTestHelper.TestArgumentsExceptions<int>(new TransformManyBlock<int, int>(i => new int[] { i })); passed &= ISourceBlockTestHelper.TestArgumentsExceptions<int>(new TransformManyBlock<int, int>(i => new int[] { i })); Assert.True(passed, "Test failed."); } //[Fact(Skip = "Outerloop")] public void RunTransformManyBlockConformanceTests() { bool passed = true; #region Sync { // Do everything twice - once through OfferMessage and Once through Post for (FeedMethod feedMethod = FeedMethod._First; passed & feedMethod < FeedMethod._Count; feedMethod++) { Func<DataflowBlockOptions, TargetProperties<int>> transformManyBlockFactory = options => { TransformManyBlock<int, int> transformManyBlock = new TransformManyBlock<int, int>(i => new[] { i }, (ExecutionDataflowBlockOptions)options); ActionBlock<int> actionBlock = new ActionBlock<int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options); transformManyBlock.LinkTo(actionBlock); return new TargetProperties<int> { Target = transformManyBlock, Capturer = actionBlock, ErrorVerifyable = false }; }; CancellationTokenSource cancellationSource = new CancellationTokenSource(); var defaultOptions = new ExecutionDataflowBlockOptions(); var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10 }; var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token }; passed &= FeedTarget(transformManyBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true); } // Test chained Post/Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => new[] { i * 2 })); for (int i = 0; i < ITERS; i++) { network.Post(i); localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i * 16); } Console.WriteLine("{0}: Chained Post/Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained SendAsync/Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => new[] { i * 2 })); for (int i = 0; i < ITERS; i++) { network.SendAsync(i); localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i * 16); } Console.WriteLine("{0}: Chained SendAsync/Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained Post all then Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => new[] { i * 2 })); for (int i = 0; i < ITERS; i++) localPassed &= network.Post(i) == true; for (int i = 0; i < ITERS; i++) localPassed &= ((IReceivableSourceBlock<int>)network).Receive() == i * 16; Console.WriteLine("{0}: Chained Post all then Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained SendAsync all then Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => new[] { i * 2 })); var tasks = new Task[ITERS]; for (int i = 1; i <= ITERS; i++) tasks[i - 1] = network.SendAsync(i); Task.WaitAll(tasks); int total = 0; for (int i = 1; i <= ITERS; i++) total += ((IReceivableSourceBlock<int>)network).Receive(); localPassed &= (total == ((ITERS * (ITERS + 1)) / 2 * 16)); Console.WriteLine("{0}: Chained SendAsync all then Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test multiple yielded results { bool localPassed = true; var t = new TransformManyBlock<int, int>(i => { return Enumerable.Range(0, 10); }); t.Post(42); t.Complete(); for (int i = 0; i < 10; i++) { localPassed &= t.Receive() == i; } t.Completion.Wait(); Console.WriteLine("{0}: Test multiple yielded results", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test that OperationCanceledExceptions are ignored { bool localPassed = true; var t = new TransformManyBlock<int, int>(i => { if ((i % 2) == 0) throw new OperationCanceledException(); return new[] { i }; }); for (int i = 0; i < 10; i++) t.Post(i); t.Complete(); for (int i = 0; i < 10; i++) { if ((i % 2) != 0) localPassed &= t.Receive() == i; } t.Completion.Wait(); Console.WriteLine("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test using a precanceled token { bool localPassed = true; try { var cts = new CancellationTokenSource(); cts.Cancel(); var dbo = new ExecutionDataflowBlockOptions { CancellationToken = cts.Token }; var t = new TransformManyBlock<int, int>(i => new[] { i }, dbo); int ignoredValue; IList<int> ignoredValues; localPassed &= t.LinkTo(new ActionBlock<int>(delegate { })) != null; localPassed &= t.SendAsync(42).Result == false; localPassed &= t.TryReceiveAll(out ignoredValues) == false; localPassed &= t.Post(42) == false; localPassed &= t.OutputCount == 0; localPassed &= t.TryReceive(out ignoredValue) == false; localPassed &= t.Completion != null; t.Complete(); } catch (Exception) { localPassed = false; } Console.WriteLine(" > {0}: Precanceled tokens work correctly", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test faulting { bool localPassed = true; var t = new TransformManyBlock<int, int>(new Func<int, IEnumerable<int>>(i => { throw new InvalidOperationException(); })); t.Post(42); t.Post(1); t.Post(2); t.Post(3); try { t.Completion.Wait(); } catch { } localPassed &= t.Completion.IsFaulted; localPassed &= SpinWait.SpinUntil(() => t.InputCount == 0, 500); localPassed &= SpinWait.SpinUntil(() => t.OutputCount == 0, 500); localPassed &= t.Post(4) == false; Console.WriteLine(" > {0}: Faulted handled correctly", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test reuse of a list and array { bool localPassed = true; foreach (bool bounded in new[] { false, true }) { for (int dop = 1; dop < Environment.ProcessorCount; dop++) { var dbo = bounded ? new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = 2 } : new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }; foreach (IList<int> list in new IList<int>[] { new int[1], new List<int>() { 0 }, new Collection<int>() { 0 } }) { int nextExpectedValue = 1; TransformManyBlock<int, int> tmb1 = null; tmb1 = new TransformManyBlock<int, int>(i => { if (i == 1000) { tmb1.Complete(); return (IEnumerable<int>)null; } else if (dop == 1) { list[0] = i + 1; return (IEnumerable<int>)list; } else if (list is int[]) { return new int[1] { i + 1 }; } else if (list is List<int>) { return new List<int>() { i + 1 }; } else return new Collection<int>() { i + 1 }; }, dbo); TransformBlock<int, int> tmb2 = new TransformBlock<int, int>(i => { if (i != nextExpectedValue) { localPassed = false; tmb1.Complete(); } nextExpectedValue++; return i; }); tmb1.LinkTo(tmb2); tmb2.LinkTo(tmb1); tmb1.SendAsync(0).Wait(); tmb1.Completion.Wait(); } } } Console.WriteLine(" > {0}: Reuse of a list and array", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test throwing an OCE { bool localPassed = true; foreach (bool bounded in new[] { true, false }) { for (int dop = 1; dop < Environment.ProcessorCount; dop++) { var dbo = bounded ? new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = 2 } : new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }; foreach (int mode in new[] { 0, 1, 2 }) { const int ITERS = 50; var mres = new ManualResetEventSlim(); var tmb = new TransformManyBlock<int, int>(i => { if (i < ITERS - 1) throw new OperationCanceledException(); if (mode == 0) return new int[] { i }; else if (mode == 1) return new List<int>() { i }; else return Enumerable.Repeat(i, 1); }, dbo); var ab = new ActionBlock<int>(i => { if (i != ITERS - 1) localPassed = false; mres.Set(); }); tmb.LinkTo(ab); for (int i = 0; i < ITERS; i++) tmb.SendAsync(i).Wait(); mres.Wait(); } } } Console.WriteLine("{0}: Canceled invocation", localPassed ? "Success" : "Failure"); passed &= localPassed; } } #endregion #region Async { // Do everything twice - once through OfferMessage and Once through Post for (FeedMethod feedMethod = FeedMethod._First; passed & feedMethod < FeedMethod._Count; feedMethod++) { Func<DataflowBlockOptions, TargetProperties<int>> transformManyBlockFactory = options => { TransformManyBlock<int, int> transformManyBlock = new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i }), (ExecutionDataflowBlockOptions)options); ActionBlock<int> actionBlock = new ActionBlock<int>(i => TrackCaptures(i), (ExecutionDataflowBlockOptions)options); transformManyBlock.LinkTo(actionBlock); return new TargetProperties<int> { Target = transformManyBlock, Capturer = actionBlock, ErrorVerifyable = false }; }; CancellationTokenSource cancellationSource = new CancellationTokenSource(); var defaultOptions = new ExecutionDataflowBlockOptions(); var dopOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; var mptOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 10 }; var cancellationOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, MaxMessagesPerTask = 100, CancellationToken = cancellationSource.Token }; passed &= FeedTarget(transformManyBlockFactory, defaultOptions, 1, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, defaultOptions, 10, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, dopOptions, 1000, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, mptOptions, 10000, Intervention.None, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, mptOptions, 10000, Intervention.Complete, null, feedMethod, true); passed &= FeedTarget(transformManyBlockFactory, cancellationOptions, 10000, Intervention.Cancel, cancellationSource, feedMethod, true); } // Test chained Post/Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i * 2 }))); for (int i = 0; i < ITERS; i++) { network.Post(i); localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i * 16); } Console.WriteLine("{0}: Chained Post/Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained SendAsync/Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i * 2 }))); for (int i = 0; i < ITERS; i++) { network.SendAsync(i); localPassed &= (((IReceivableSourceBlock<int>)network).Receive() == i * 16); } Console.WriteLine("{0}: Chained SendAsync/Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained Post all then Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i * 2 }))); for (int i = 0; i < ITERS; i++) localPassed &= network.Post(i) == true; for (int i = 0; i < ITERS; i++) localPassed &= ((IReceivableSourceBlock<int>)network).Receive() == i * 16; Console.WriteLine("{0}: Chained Post all then Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test chained SendAsync all then Receive { bool localPassed = true; const int ITERS = 2; var network = Chain<TransformManyBlock<int, int>, int>(4, () => new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i * 2 }))); var tasks = new Task[ITERS]; for (int i = 1; i <= ITERS; i++) tasks[i - 1] = network.SendAsync(i); Task.WaitAll(tasks); int total = 0; for (int i = 1; i <= ITERS; i++) total += ((IReceivableSourceBlock<int>)network).Receive(); localPassed &= (total == ((ITERS * (ITERS + 1)) / 2 * 16)); Console.WriteLine("{0}: Chained SendAsync all then Receive", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test multiple yielded results { bool localPassed = true; var t = new TransformManyBlock<int, int>(i => Task.Factory.StartNew(() => (IEnumerable<int>)Enumerable.Range(0, 10).ToArray())); t.Post(42); t.Complete(); for (int i = 0; i < 10; i++) { localPassed &= t.Receive() == i; } t.Completion.Wait(); Console.WriteLine("{0}: Test multiple yielded results", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test that OperationCanceledExceptions are ignored { bool localPassed = true; var t = new TransformManyBlock<int, int>(i => { if ((i % 2) == 0) throw new OperationCanceledException(); return new[] { i }; }); for (int i = 0; i < 10; i++) t.Post(i); t.Complete(); for (int i = 0; i < 10; i++) { if ((i % 2) != 0) localPassed &= t.Receive() == i; } t.Completion.Wait(); Console.WriteLine("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test that null tasks are ignored { bool localPassed = true; var t = new TransformManyBlock<int, int>(i => { if ((i % 2) == 0) return null; return Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i }); }); for (int i = 0; i < 10; i++) t.Post(i); t.Complete(); for (int i = 0; i < 10; i++) { if ((i % 2) != 0) localPassed &= t.Receive() == i; } t.Completion.Wait(); Console.WriteLine("{0}: OperationCanceledExceptions are ignored", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test that null tasks are ignored when a reordering buffer is in place { bool localPassed = true; var t = new TransformManyBlock<int, int>(new Func<int, Task<IEnumerable<int>>>(i => { if (i == 0) { Task.Delay(1000).Wait(); return null; } return Task.Factory.StartNew(() => (IEnumerable<int>)new[] { i }); }), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 }); t.Post(0); t.Post(1); try { localPassed &= t.Receive(TimeSpan.FromSeconds(4)) == 1; } catch { localPassed = false; } Console.WriteLine("{0}: null tasks are ignored with reordering buffer", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test faulting from the delegate { bool localPassed = true; var t = new TransformManyBlock<int, int>(new Func<int, Task<IEnumerable<int>>>(i => { throw new InvalidOperationException(); })); t.Post(42); t.Post(1); t.Post(2); t.Post(3); try { t.Completion.Wait(); } catch { } localPassed &= t.Completion.IsFaulted; localPassed &= SpinWait.SpinUntil(() => t.InputCount == 0, 500); localPassed &= SpinWait.SpinUntil(() => t.OutputCount == 0, 500); localPassed &= t.Post(4) == false; Console.WriteLine(" > {0}: Faulted from delegate handled correctly", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test faulting from the task { bool localPassed = true; var t = new TransformManyBlock<int, int>(new Func<int, Task<IEnumerable<int>>>(i => Task<IEnumerable<int>>.Factory.StartNew(() => { throw new InvalidOperationException(); }))); t.Post(42); t.Post(1); t.Post(2); t.Post(3); try { t.Completion.Wait(); } catch { } localPassed &= t.Completion.IsFaulted; localPassed &= SpinWait.SpinUntil(() => t.InputCount == 0, 500); localPassed &= SpinWait.SpinUntil(() => t.OutputCount == 0, 500); localPassed &= t.Post(4) == false; Console.WriteLine(" > {0}: Faulted from task handled correctly", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test reuse of a list and array { bool localPassed = true; foreach (bool bounded in new[] { false, true }) { for (int dop = 1; dop < Environment.ProcessorCount; dop++) { var dbo = bounded ? new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = 2 } : new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }; foreach (IList<int> list in new IList<int>[] { new int[1], new List<int>() { 0 }, new Collection<int>() { 0 } }) { int nextExpectedValue = 1; TransformManyBlock<int, int> tmb1 = null; tmb1 = new TransformManyBlock<int, int>(i => { return Task.Factory.StartNew(() => { if (i == 1000) { tmb1.Complete(); return (IEnumerable<int>)null; } else if (dop == 1) { list[0] = i + 1; return (IEnumerable<int>)list; } else if (list is int[]) { return new int[1] { i + 1 }; } else if (list is List<int>) { return new List<int>() { i + 1 }; } else return new Collection<int>() { i + 1 }; }); }, dbo); TransformBlock<int, int> tmb2 = new TransformBlock<int, int>(i => { if (i != nextExpectedValue) { localPassed = false; tmb1.Complete(); } nextExpectedValue++; return i; }); tmb1.LinkTo(tmb2); tmb2.LinkTo(tmb1); tmb1.SendAsync(0).Wait(); tmb1.Completion.Wait(); } } } Console.WriteLine(" > {0}: Reuse of a list and array", localPassed ? "Success" : "Failure"); passed &= localPassed; } // Test throwing an OCE { bool localPassed = true; foreach (bool bounded in new[] { true, false }) { for (int dop = 1; dop < Environment.ProcessorCount; dop++) { var dbo = bounded ? new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = 2 } : new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop }; foreach (int mode in new[] { 0, 1, 2 }) { const int ITERS = 50; var mres = new ManualResetEventSlim(); var tmb = new TransformManyBlock<int, int>(i => { var cts = new CancellationTokenSource(); return Task.Factory.StartNew(() => { if (i < ITERS - 1) { cts.Cancel(); cts.Token.ThrowIfCancellationRequested(); } if (mode == 0) return new int[] { i }; else if (mode == 1) return new List<int>() { i }; else return Enumerable.Repeat(i, 1); }, cts.Token); }, dbo); var ab = new ActionBlock<int>(i => { if (i != ITERS - 1) localPassed = false; mres.Set(); }); tmb.LinkTo(ab); for (int i = 0; i < ITERS; i++) tmb.SendAsync(i).Wait(); mres.Wait(); } } } Console.WriteLine(" > {0}: Canceled invocation", localPassed ? "Success" : "Failure"); passed &= localPassed; } } #endregion Assert.True(passed, "Test failed."); } } }
using NUnit.Framework; using Transition.Compiler; using Transition.Compiler.AstNodes; using Transition.Actions; namespace Tests.Compiler { [TestFixture] public class MachineGeneratorTests { private MachineAstNode _machineNode; private MachineGenerator<TestMachineContext> _generator; [SetUp] public void SetUp() { _machineNode = new MachineAstNode(); _machineNode.Name = "mach"; _machineNode.Action = new ActionAstNode() { Name = ParserConstants.TransitionAction }; _generator = new MachineGenerator<TestMachineContext>(); _generator.LoadActions(typeof(TestAction)); } [TestCase] public void Generate_MachineWithId_IdIsSet() { _machineNode.Name = "mach2"; var result = _generator.Generate(_machineNode); Assert.AreEqual("mach2", result.Name); } [TestCase] public void Generate_MachineWithAction_ActionIsTransition() { _machineNode.Action = new ActionAstNode() { Name = ParserConstants.TransitionAction }; var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TransitionAction<TestMachineContext>>(result.EnterAction); } [TestCase] public void Generate_StateExists_MachineHasState() { var state = new StateAstNode { Name = "state1" }; _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.AreEqual("state1", result.States[0].Name); } [TestCase] public void Generate_StateWithRunAction_ActionIsGenerated() { var state = new StateAstNode { Name = "state1" }; state.Run = new SectionAstNode(); state.Run.Actions.Add(new ActionAstNode { Name = "testaction", }); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TestAction>(result.States[0].RunActions[0]); } [TestCase] public void Generate_StateWithTwoRunActions_ActionsAreGenerated() { var state = new StateAstNode { Name = "state1" }; state.Run = new SectionAstNode(); state.Run.Actions.Add(new ActionAstNode { Name = ParserConstants.TransitionAction, }); state.Run.Actions.Add(new ActionAstNode { Name = "testaction", }); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TestAction>(result.States[0].RunActions[1]); } [TestCase] public void Generate_StateWithEnterAction_ActionIsGenerated() { var state = new StateAstNode { Name = "state1" }; state.Enter = new SectionAstNode(); state.Enter.Actions.Add(new ActionAstNode { Name = "testaction", }); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TestAction>(result.States[0].EnterActions[0]); } [TestCase] public void Generate_StateWithExitAction_ActionIsGenerated() { var state = new StateAstNode { Name = "state1" }; state.Exit = new SectionAstNode(); state.Exit.Actions.Add(new ActionAstNode { Name = "testaction", }); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TestAction>(result.States[0].ExitActions[0]); } [TestCase] public void Generate_StateWithOnAction_ActionIsGenerated() { var state = new StateAstNode { Name = "state1" }; state.On = new SectionAstNode(); state.On.Actions.Add(new ActionAstNode { Message = "blah", Name = "testaction" }); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); Assert.IsInstanceOf<TestAction>(result.States[0].OnActions["blah"]); } [TestCase] public void Generate_ActionWithIntParameter_ParameterIsAssigned() { var state = new StateAstNode { Name = "state1" }; state.On = new SectionAstNode(); var action = new ActionAstNode { Message = "blah", Name = "testaction" }; action.Params.Add(new ParamAstNode { Name = "TestProperty1", Op = ParamOperation.Assign, Val = "1234" }); state.On.Actions.Add(action); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); var resultAction = (TestAction)result.States[0].OnActions["blah"]; Assert.AreEqual(1234, resultAction.TestProperty1); } [TestCase] public void Generate_ActionWithTransitionParameter_ParameterIsTransitionDestination() { var state = new StateAstNode { Name = "state1" }; state.On = new SectionAstNode(); var action = new ActionAstNode { Message = "blah", Name = "testaction" }; action.Params.Add(new ParamAstNode { Name = "DestinationProp", Op = ParamOperation.Transition, Val = "state2", StateIdVal = 1 }); state.On.Actions.Add(action); _machineNode.States.Add(state); // add another state to transition to _machineNode.States.Add(new StateAstNode { Name = "state2" }); var result = _generator.Generate(_machineNode); var resultAction = (TestAction)result.States[0].OnActions["blah"]; Assert.IsNotNull(resultAction.DestinationProp); Assert.AreEqual(1, resultAction.DestinationProp.StateId); } [TestCase] public void Generate_ActionWithTwoParameters_ParametersAreAssigned() { var state = new StateAstNode { Name = "state1" }; state.On = new SectionAstNode(); var action = new ActionAstNode { Message = "blah", Name = "testaction" }; action.Params.Add(new ParamAstNode { Name = "TestProperty1", Op = ParamOperation.Assign, Val = "1234" }); action.Params.Add(new ParamAstNode { Name = "TestProperty2", Op = ParamOperation.Assign, Val = "hello" }); state.On.Actions.Add(action); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); var resultAction = (TestAction)result.States[0].OnActions["blah"]; Assert.AreEqual(1234, resultAction.TestProperty1); Assert.AreEqual("hello", resultAction.TestProperty2); } [TestCase] public void Generate_ActionWithDefaultParameter_ParameterIsAssigned() { var state = new StateAstNode { Name = "state1" }; state.On = new SectionAstNode(); var action = new ActionAstNode { Message = "blah", Name = "TestAction" }; action.Params.Add(new ParamAstNode { Name = ParserConstants.DefaultParameterName, Op = ParamOperation.Assign, Val = "1234" }); state.On.Actions.Add(action); _machineNode.States.Add(state); var result = _generator.Generate(_machineNode); var resultAction = (TestAction)result.States[0].OnActions["blah"]; Assert.AreEqual(1234, resultAction.TestProperty1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using System.Threading; namespace System.Reflection { // Helper class to handle the IL EMIT for the generation of proxies. // Much of this code was taken directly from the Silverlight proxy generation. // Differences between this and the Silverlight version are: // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel. // There are several notable differences between them. // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types: // the interface type to implement, and a base type. But they behave slightly differently: // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's // interfaces plus all the interface type's interfaces. // - DispatchProxy generates a proxy type that *derives* from the base type and implements all // the interface type's interfaces. This is true for both the CLR version in NET Native and this // version for CoreCLR. // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies: // - RealProxy type hierarchy is: // proxyType : proxyBaseType : object // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces // explicitly, preventing collision for same name methods on the base and interface types. // - DispatchProxy hierarchy is: // proxyType : baseType (where baseType : DispatchProxy) // The generated DispatchProxy proxy type does not need to generate implementation methods // for the base type's interfaces, because the base type already must have implemented them. // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror // the .Net Remoting design that required the proxy and RealProxy to be separate instances. // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore, // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were // able to remove an extraneous field and ctor arg from the DispatchProxy proxies. // internal static class DispatchProxyGenerator { // Generated proxies have a private Action field that all generated methods // invoke. It is the first field in the class and the first ctor parameter. private const int InvokeActionFieldAndCtorParameterIndex = 0; // Proxies are requested for a pair of types: base type and interface type. // The generated proxy will subclass the given base type and implement the interface type. // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type, // containing the generated proxy type for that pair. There are likely to be few (maybe only 1) // base type in use for many interface types. // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the // interface type. But this does not allow the same interface type to be used with more than a // single base type. The implementation here permits multiple interface types to be used with // multiple base types, and the generated proxy types will be unique. // This cache of generated types grows unbounded, one element per unique T/ProxyT pair. // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs, // which would ultimately be a more expensive leak. // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create. private static readonly Dictionary<Type, Dictionary<Type, Type>> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary<Type, Dictionary<Type, Type>>(); private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly(); private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke"); // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' internal static object CreateProxyInstance(Type baseType, Type interfaceType) { Debug.Assert(baseType != null); Debug.Assert(interfaceType != null); Type proxiedType = GetProxyType(baseType, interfaceType); return Activator.CreateInstance(proxiedType, (Action<object[]>)DispatchProxyGenerator.Invoke); } private static Type GetProxyType(Type baseType, Type interfaceType) { lock (s_baseTypeAndInterfaceToGeneratedProxyType) { Dictionary<Type, Type> interfaceToProxy = null; if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out interfaceToProxy)) { interfaceToProxy = new Dictionary<Type, Type>(); s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; } Type generatedProxy = null; if (!interfaceToProxy.TryGetValue(interfaceType, out generatedProxy)) { generatedProxy = GenerateProxyType(baseType, interfaceType); interfaceToProxy[interfaceType] = generatedProxy; } return generatedProxy; } } // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' private static Type GenerateProxyType(Type baseType, Type interfaceType) { // Parameter validation is deferred until the point we need to create the proxy. // This prevents unnecessary overhead revalidating cached proxy types. TypeInfo baseTypeInfo = baseType.GetTypeInfo(); // The interface type must be an interface, not a class if (!interfaceType.GetTypeInfo().IsInterface) { // "T" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.InterfaceType_Must_Be_Interface, interfaceType.FullName), "T"); } // The base type cannot be sealed because the proxy needs to subclass it. if (baseTypeInfo.IsSealed) { // "TProxy" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Sealed, baseTypeInfo.FullName), "TProxy"); } // The base type cannot be abstract if (baseTypeInfo.IsAbstract) { throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Abstract, baseType.FullName), "TProxy"); } // The base type must have a public default ctor if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0)) { throw new ArgumentException(SR.Format(SR.BaseType_Must_Have_Default_Ctor, baseType.FullName), "TProxy"); } // Create a type that derives from 'baseType' provided by caller ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); foreach (Type t in interfaceType.GetTypeInfo().ImplementedInterfaces) pb.AddInterfaceImpl(t); pb.AddInterfaceImpl(interfaceType); Type generatedProxyType = pb.CreateType(); return generatedProxyType; } // All generated proxy methods call this static helper method to dispatch. // Its job is to unpack the arguments and the 'this' instance and to dispatch directly // to the (abstract) DispatchProxy.Invoke() method. private static void Invoke(object[] args) { PackedArgs packed = new PackedArgs(args); MethodBase method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken); if (method.IsGenericMethodDefinition) method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes); // Call (protected method) DispatchProxy.Invoke() try { Debug.Assert(s_dispatchProxyInvokeMethod != null); object returnValue = s_dispatchProxyInvokeMethod.Invoke(packed.DispatchProxy, new object[] { method, packed.Args }); packed.ReturnValue = returnValue; } catch (TargetInvocationException tie) { ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); } } private class PackedArgs { internal const int DispatchProxyPosition = 0; internal const int DeclaringTypePosition = 1; internal const int MethodTokenPosition = 2; internal const int ArgsPosition = 3; internal const int GenericTypesPosition = 4; internal const int ReturnValuePosition = 5; internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) }; private object[] _args; internal PackedArgs() : this(new object[PackedTypes.Length]) { } internal PackedArgs(object[] args) { _args = args; } internal DispatchProxy DispatchProxy { get { return (DispatchProxy)_args[DispatchProxyPosition]; } } internal Type DeclaringType { get { return (Type)_args[DeclaringTypePosition]; } } internal int MethodToken { get { return (int)_args[MethodTokenPosition]; } } internal object[] Args { get { return (object[])_args[ArgsPosition]; } } internal Type[] GenericTypes { get { return (Type[])_args[GenericTypesPosition]; } } internal object ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } } } private class ProxyAssembly { private AssemblyBuilder _ab; private ModuleBuilder _mb; private int _typeId = 0; // Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code // to pass methods by token private Dictionary<MethodBase, int> _methodToToken = new Dictionary<MethodBase, int>(); private List<MethodBase> _methodsByToken = new List<MethodBase>(); private HashSet<string> _ignoresAccessAssemblyNames = new HashSet<string>(); private ConstructorInfo _ignoresAccessChecksToAttributeConstructor; public ProxyAssembly() { _ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run); _mb = _ab.DefineDynamicModule("testmod"); } // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. internal ConstructorInfo IgnoresAccessChecksAttributeConstructor { get { if (_ignoresAccessChecksToAttributeConstructor == null) { TypeInfo attributeTypeInfo = GenerateTypeInfoOfIgnoresAccessChecksToAttribute(); _ignoresAccessChecksToAttributeConstructor = attributeTypeInfo.DeclaredConstructors.Single(); } return _ignoresAccessChecksToAttributeConstructor; } } public ProxyBuilder CreateProxy(string name, Type proxyBaseType) { int nextId = Interlocked.Increment(ref _typeId); TypeBuilder tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType); return new ProxyBuilder(this, tb, proxyBaseType); } // Generate the declaration for the IgnoresAccessChecksToAttribute type. // This attribute will be both defined and used in the dynamic assembly. // Each usage identifies the name of the assembly containing non-public // types the dynamic assembly needs to access. Normally those types // would be inaccessible, but this attribute allows them to be visible. // It works like a reverse InternalsVisibleToAttribute. // This method returns the TypeInfo of the generated attribute. private TypeInfo GenerateTypeInfoOfIgnoresAccessChecksToAttribute() { TypeBuilder attributeTypeBuilder = _mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", TypeAttributes.Public | TypeAttributes.Class, typeof(Attribute)); // Create backing field as: // private string assemblyName; FieldBuilder assemblyNameField = attributeTypeBuilder.DefineField("assemblyName", typeof(String), FieldAttributes.Private); // Create ctor as: // public IgnoresAccessChecksToAttribute(string) ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { assemblyNameField.FieldType }); ILGenerator il = constructorBuilder.GetILGenerator(); // Create ctor body as: // this.assemblyName = {ctor parameter 0} il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Stfld, assemblyNameField); // return il.Emit(OpCodes.Ret); // Define property as: // public string AssemblyName {get { return this.assemblyName; } } PropertyBuilder getterPropertyBuilder = attributeTypeBuilder.DefineProperty( "AssemblyName", PropertyAttributes.None, CallingConventions.HasThis, returnType: typeof(String), parameterTypes: null); MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod( "get_AssemblyName", MethodAttributes.Public, CallingConventions.HasThis, returnType: typeof(String), parameterTypes: null); // Generate body: // return this.assemblyName; il = getterMethodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, assemblyNameField); il.Emit(OpCodes.Ret); // Generate the AttributeUsage attribute for this attribute type: // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); // Find the ctor that takes only AttributeTargets ConstructorInfo attributeUsageConstructorInfo = attributeUsageTypeInfo.DeclaredConstructors .Single(c => c.GetParameters().Count() == 1 && c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); // Find the property to set AllowMultiple PropertyInfo allowMultipleProperty = attributeUsageTypeInfo.DeclaredProperties .Single(f => String.Equals(f.Name, "AllowMultiple")); // Create a builder to construct the instance via the ctor and property CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeUsageConstructorInfo, new object[] { AttributeTargets.Assembly }, new PropertyInfo[] { allowMultipleProperty }, new object[] { true }); // Attach this attribute instance to the newly defined attribute type attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); // Make the TypeInfo real so the constructor can be used. return attributeTypeBuilder.CreateTypeInfo(); } // Generates an instance of the IgnoresAccessChecksToAttribute to // identify the given assembly as one which contains internal types // the dynamic assembly will need to reference. internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) { // Add this assembly level attribute: // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor; CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { assemblyName }); _ab.SetCustomAttribute(customAttributeBuilder); } // Ensures the type we will reference from the dynamic assembly // is visible. Non-public types need to emit an attribute that // allows access from the dynamic assembly. internal void EnsureTypeIsVisible(Type type) { TypeInfo typeInfo = type.GetTypeInfo(); if (!typeInfo.IsVisible) { string assemblyName = typeInfo.Assembly.GetName().Name; if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) { GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); _ignoresAccessAssemblyNames.Add(assemblyName); } } } internal void GetTokenForMethod(MethodBase method, out Type type, out int token) { type = method.DeclaringType; token = 0; if (!_methodToToken.TryGetValue(method, out token)) { _methodsByToken.Add(method); token = _methodsByToken.Count - 1; _methodToToken[method] = token; } } internal MethodBase ResolveMethodToken(Type type, int token) { Debug.Assert(token >= 0 && token < _methodsByToken.Count); return _methodsByToken[token]; } } private class ProxyBuilder { private static readonly MethodInfo s_delegateInvoke = typeof(Action<object[]>).GetTypeInfo().GetDeclaredMethod("Invoke"); private ProxyAssembly _assembly; private TypeBuilder _tb; private Type _proxyBaseType; private List<FieldBuilder> _fields; internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType) { _assembly = assembly; _tb = tb; _proxyBaseType = proxyBaseType; _fields = new List<FieldBuilder>(); _fields.Add(tb.DefineField("invoke", typeof(Action<object[]>), FieldAttributes.Private)); } private void Complete() { Type[] args = new Type[_fields.Count]; for (int i = 0; i < args.Length; i++) { args[i] = _fields[i].FieldType; } ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args); ILGenerator il = cb.GetILGenerator(); // chained ctor call ConstructorInfo baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0); Debug.Assert(baseCtor != null); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseCtor); // store all the fields for (int i = 0; i < args.Length; i++) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i + 1); il.Emit(OpCodes.Stfld, _fields[i]); } il.Emit(OpCodes.Ret); } internal Type CreateType() { this.Complete(); return _tb.CreateTypeInfo().AsType(); } internal void AddInterfaceImpl(Type iface) { // If necessary, generate an attribute to permit visibility // to internal types. _assembly.EnsureTypeIsVisible(iface); _tb.AddInterfaceImplementation(iface); // AccessorMethods -> Metadata mappings. var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod); if (pi.GetMethod != null) propertyMap[pi.GetMethod] = ai; if (pi.SetMethod != null) propertyMap[pi.SetMethod] = ai; } var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (EventInfo ei in iface.GetRuntimeEvents()) { var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod); if (ei.AddMethod != null) eventMap[ei.AddMethod] = ai; if (ei.RemoveMethod != null) eventMap[ei.RemoveMethod] = ai; if (ei.RaiseMethod != null) eventMap[ei.RaiseMethod] = ai; } foreach (MethodInfo mi in iface.GetRuntimeMethods()) { MethodBuilder mdb = AddMethodImpl(mi); PropertyAccessorInfo associatedProperty; if (propertyMap.TryGetValue(mi, out associatedProperty)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedProperty.InterfaceGetMethod, mi)) associatedProperty.GetMethodBuilder = mdb; else associatedProperty.SetMethodBuilder = mdb; } EventAccessorInfo associatedEvent; if (eventMap.TryGetValue(mi, out associatedEvent)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceAddMethod, mi)) associatedEvent.AddMethodBuilder = mdb; else if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceRemoveMethod, mi)) associatedEvent.RemoveMethodBuilder = mdb; else associatedEvent.RaiseMethodBuilder = mdb; } } foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { PropertyAccessorInfo ai = propertyMap[pi.GetMethod ?? pi.SetMethod]; PropertyBuilder pb = _tb.DefineProperty(pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray()); if (ai.GetMethodBuilder != null) pb.SetGetMethod(ai.GetMethodBuilder); if (ai.SetMethodBuilder != null) pb.SetSetMethod(ai.SetMethodBuilder); } foreach (EventInfo ei in iface.GetRuntimeEvents()) { EventAccessorInfo ai = eventMap[ei.AddMethod ?? ei.RemoveMethod]; EventBuilder eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType); if (ai.AddMethodBuilder != null) eb.SetAddOnMethod(ai.AddMethodBuilder); if (ai.RemoveMethodBuilder != null) eb.SetRemoveOnMethod(ai.RemoveMethodBuilder); if (ai.RaiseMethodBuilder != null) eb.SetRaiseMethod(ai.RaiseMethodBuilder); } } private MethodBuilder AddMethodImpl(MethodInfo mi) { ParameterInfo[] parameters = mi.GetParameters(); Type[] paramTypes = ParamTypes(parameters, false); MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { Type[] ts = mi.GetGenericArguments(); string[] ss = new string[ts.Length]; for (int i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss); for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } ILGenerator il = mdb.GetILGenerator(); ParametersArray args = new ParametersArray(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); GenericArray<object> argsArr = new GenericArray<object>(il, ParamTypes(parameters, true).Length); for (int i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray<object> packedArr = new GenericArray<object>(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(DispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); int methodToken; Type declaringType; _assembly.GetTokenForMethod(mi, out declaringType, out methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(Int32)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); Type[] genericTypes = mi.GetGenericArguments(); GenericArray<Type> typeArr = new GenericArray<Type>(il, genericTypes.Length); for (int i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } // Call static DispatchProxyHelper.Invoke(object[]) il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate packedArr.Load(); il.Emit(OpCodes.Call, s_delegateInvoke); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } if (mi.ReturnType != typeof(void)) { packedArr.Get(PackedArgs.ReturnValuePosition); Convert(il, typeof(object), mi.ReturnType, false); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return mdb; } private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef) { Type[] types = new Type[parms.Length]; for (int i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; if (noByRef && types[i].IsByRef) types[i] = types[i].GetElementType(); } return types; } // TypeCode does not exist in ProjectK or ProjectN. // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs // but returns the integer value equivalent to its TypeCode enum. private static int GetTypeCode(Type type) { if (type == null) return 0; // TypeCode.Empty; if (type == typeof(Boolean)) return 3; // TypeCode.Boolean; if (type == typeof(Char)) return 4; // TypeCode.Char; if (type == typeof(SByte)) return 5; // TypeCode.SByte; if (type == typeof(Byte)) return 6; // TypeCode.Byte; if (type == typeof(Int16)) return 7; // TypeCode.Int16; if (type == typeof(UInt16)) return 8; // TypeCode.UInt16; if (type == typeof(Int32)) return 9; // TypeCode.Int32; if (type == typeof(UInt32)) return 10; // TypeCode.UInt32; if (type == typeof(Int64)) return 11; // TypeCode.Int64; if (type == typeof(UInt64)) return 12; // TypeCode.UInt64; if (type == typeof(Single)) return 13; // TypeCode.Single; if (type == typeof(Double)) return 14; // TypeCode.Double; if (type == typeof(Decimal)) return 15; // TypeCode.Decimal; if (type == typeof(DateTime)) return 16; // TypeCode.DateTime; if (type == typeof(String)) return 18; // TypeCode.String; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return 1; // TypeCode.Object; } private static OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Conv_I1,//Boolean = 3, OpCodes.Conv_I2,//Char = 4, OpCodes.Conv_I1,//SByte = 5, OpCodes.Conv_U1,//Byte = 6, OpCodes.Conv_I2,//Int16 = 7, OpCodes.Conv_U2,//UInt16 = 8, OpCodes.Conv_I4,//Int32 = 9, OpCodes.Conv_U4,//UInt32 = 10, OpCodes.Conv_I8,//Int64 = 11, OpCodes.Conv_U8,//UInt64 = 12, OpCodes.Conv_R4,//Single = 13, OpCodes.Conv_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Nop,//String = 18, }; private static OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Ldind_I1,//Boolean = 3, OpCodes.Ldind_I2,//Char = 4, OpCodes.Ldind_I1,//SByte = 5, OpCodes.Ldind_U1,//Byte = 6, OpCodes.Ldind_I2,//Int16 = 7, OpCodes.Ldind_U2,//UInt16 = 8, OpCodes.Ldind_I4,//Int32 = 9, OpCodes.Ldind_U4,//UInt32 = 10, OpCodes.Ldind_I8,//Int64 = 11, OpCodes.Ldind_I8,//UInt64 = 12, OpCodes.Ldind_R4,//Single = 13, OpCodes.Ldind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldind_Ref,//String = 18, }; private static OpCode[] s_stindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Stind_I1,//Boolean = 3, OpCodes.Stind_I2,//Char = 4, OpCodes.Stind_I1,//SByte = 5, OpCodes.Stind_I1,//Byte = 6, OpCodes.Stind_I2,//Int16 = 7, OpCodes.Stind_I2,//UInt16 = 8, OpCodes.Stind_I4,//Int32 = 9, OpCodes.Stind_I4,//UInt32 = 10, OpCodes.Stind_I8,//Int64 = 11, OpCodes.Stind_I8,//UInt64 = 12, OpCodes.Stind_R4,//Single = 13, OpCodes.Stind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Stind_Ref,//String = 18, }; private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) { Debug.Assert(!target.IsByRef); if (target == source) return; TypeInfo sourceTypeInfo = source.GetTypeInfo(); TypeInfo targetTypeInfo = target.GetTypeInfo(); if (source.IsByRef) { Debug.Assert(!isAddress); Type argType = source.GetElementType(); Ldind(il, argType); Convert(il, argType, target, isAddress); return; } if (targetTypeInfo.IsValueType) { if (sourceTypeInfo.IsValueType) { OpCode opCode = s_convOpCodes[GetTypeCode(target)]; Debug.Assert(!opCode.Equals(OpCodes.Nop)); il.Emit(opCode); } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo)); il.Emit(OpCodes.Unbox, target); if (!isAddress) Ldind(il, target); } } else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo)) { if (sourceTypeInfo.IsValueType || source.IsGenericParameter) { if (isAddress) Ldind(il, source); il.Emit(OpCodes.Box, source); } } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface); if (target.IsGenericParameter) { il.Emit(OpCodes.Unbox_Any, target); } else { il.Emit(OpCodes.Castclass, target); } } } private static void Ldind(ILGenerator il, Type type) { OpCode opCode = s_ldindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Ldobj, type); } } private static void Stind(ILGenerator il, Type type) { OpCode opCode = s_stindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Stobj, type); } } private class ParametersArray { private ILGenerator _il; private Type[] _paramTypes; internal ParametersArray(ILGenerator il, Type[] paramTypes) { _il = il; _paramTypes = paramTypes; } internal void Get(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void EndSet(int i, Type stackType) { Debug.Assert(_paramTypes[i].IsByRef); Type argType = _paramTypes[i].GetElementType(); Convert(_il, stackType, argType, false); Stind(_il, argType); } } private class GenericArray<T> { private ILGenerator _il; private LocalBuilder _lb; internal GenericArray(ILGenerator il, int len) { _il = il; _lb = il.DeclareLocal(typeof(T[])); il.Emit(OpCodes.Ldc_I4, len); il.Emit(OpCodes.Newarr, typeof(T)); il.Emit(OpCodes.Stloc, _lb); } internal void Load() { _il.Emit(OpCodes.Ldloc, _lb); } internal void Get(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); _il.Emit(OpCodes.Ldelem_Ref); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); } internal void EndSet(Type stackType) { Convert(_il, stackType, typeof(T), false); _il.Emit(OpCodes.Stelem_Ref); } } private sealed class PropertyAccessorInfo { public MethodInfo InterfaceGetMethod { get; } public MethodInfo InterfaceSetMethod { get; } public MethodBuilder GetMethodBuilder { get; set; } public MethodBuilder SetMethodBuilder { get; set; } public PropertyAccessorInfo(MethodInfo interfaceGetMethod, MethodInfo interfaceSetMethod) { InterfaceGetMethod = interfaceGetMethod; InterfaceSetMethod = interfaceSetMethod; } } private sealed class EventAccessorInfo { public MethodInfo InterfaceAddMethod { get; } public MethodInfo InterfaceRemoveMethod { get; } public MethodInfo InterfaceRaiseMethod { get; } public MethodBuilder AddMethodBuilder { get; set; } public MethodBuilder RemoveMethodBuilder { get; set; } public MethodBuilder RaiseMethodBuilder { get; set; } public EventAccessorInfo(MethodInfo interfaceAddMethod, MethodInfo interfaceRemoveMethod, MethodInfo interfaceRaiseMethod) { InterfaceAddMethod = interfaceAddMethod; InterfaceRemoveMethod = interfaceRemoveMethod; InterfaceRaiseMethod = interfaceRaiseMethod; } } private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo> { public static readonly MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer(); private MethodInfoEqualityComparer() { } public sealed override bool Equals(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if (left == null) return right == null; else if (right == null) return false; // This assembly should work in netstandard1.3, // so we cannot use MemberInfo.MetadataToken here. // Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching. if (!Equals(left.DeclaringType, right.DeclaringType)) return false; if (!Equals(left.ReturnType, right.ReturnType)) return false; if (left.CallingConvention != right.CallingConvention) return false; if (left.IsStatic != right.IsStatic) return false; if ( left.Name != right.Name) return false; Type[] leftGenericParameters = left.GetGenericArguments(); Type[] rightGenericParameters = right.GetGenericArguments(); if (leftGenericParameters.Length != rightGenericParameters.Length) return false; for (int i = 0; i < leftGenericParameters.Length; i++) { if (!Equals(leftGenericParameters[i], rightGenericParameters[i])) return false; } ParameterInfo[] leftParameters = left.GetParameters(); ParameterInfo[] rightParameters = right.GetParameters(); if (leftParameters.Length != rightParameters.Length) return false; for (int i = 0; i < leftParameters.Length; i++) { if (!Equals(leftParameters[i].ParameterType, rightParameters[i].ParameterType)) return false; } return true; } public sealed override int GetHashCode(MethodInfo obj) { if (obj == null) return 0; int hashCode = obj.DeclaringType.GetHashCode(); hashCode ^= obj.Name.GetHashCode(); foreach (ParameterInfo parameter in obj.GetParameters()) { hashCode ^= parameter.ParameterType.GetHashCode(); } return hashCode; } } } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Xml; namespace Orleans.Runtime.Configuration { /// <summary> /// Orleans application configuration parameters. /// </summary> [Serializable] public class ApplicationConfiguration { private readonly Dictionary<string, GrainTypeConfiguration> classSpecific; private GrainTypeConfiguration defaults; /// <summary> /// The default time period used to collect in-active activations. /// Applies to all grain types. /// </summary> public TimeSpan DefaultCollectionAgeLimit { get { return defaults.CollectionAgeLimit.HasValue ? defaults.CollectionAgeLimit.Value : GlobalConfiguration.DEFAULT_COLLECTION_AGE_LIMIT; } } internal TimeSpan ShortestCollectionAgeLimit { get { TimeSpan shortest = DefaultCollectionAgeLimit; foreach (var typeConfig in ClassSpecific) { TimeSpan curr = typeConfig.CollectionAgeLimit.Value; if (curr < shortest) { shortest = curr; } } return shortest; } } /// <summary> /// Constructor. /// </summary> /// <param name="defaultCollectionAgeLimit">The default time period used to collect in-active activations.</param> public ApplicationConfiguration(TimeSpan? defaultCollectionAgeLimit = null) { classSpecific = new Dictionary<string, GrainTypeConfiguration>(); defaults = new GrainTypeConfiguration(null, defaultCollectionAgeLimit); } /// <summary> /// IEnumerable of all configurations for different grain types. /// </summary> public IEnumerable<GrainTypeConfiguration> ClassSpecific { get { return classSpecific.Values; } } /// <summary> /// Load this configuratin from xml element. /// </summary> /// <param name="xmlElement"></param> /// <param name="logger"></param> public void Load(XmlElement xmlElement, Logger logger) { bool found = false; foreach (XmlNode node in xmlElement.ChildNodes) { found = true; var config = GrainTypeConfiguration.Load((XmlElement)node, logger); if (null == config) continue; if (config.AreDefaults) { defaults = config; } else { if (classSpecific.ContainsKey(config.FullTypeName)) { throw new InvalidOperationException(string.Format("duplicate type {0} in configuration", config.FullTypeName)); } classSpecific.Add(config.FullTypeName, config); } } if (!found) { throw new InvalidOperationException("empty GrainTypeConfiguration element"); } } /// <summary> /// Returns the time period used to collect in-active activations of a given type. /// </summary> /// <param name="type">Grain type.</param> /// <returns></returns> public TimeSpan GetCollectionAgeLimit(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return GetCollectionAgeLimit(type.FullName); } /// <summary> /// Returns the time period used to collect in-active activations of a given type. /// </summary> /// <param name="grainTypeFullName">Grain type full name.</param> /// <returns></returns> public TimeSpan GetCollectionAgeLimit(string grainTypeFullName) { if (String.IsNullOrEmpty(grainTypeFullName)) { throw new ArgumentNullException("grainTypeFullName"); } GrainTypeConfiguration config; return classSpecific.TryGetValue(grainTypeFullName, out config) && config.CollectionAgeLimit.HasValue ? config.CollectionAgeLimit.Value : DefaultCollectionAgeLimit; } /// <summary> /// Sets the time period to collect in-active activations for a given type. /// </summary> /// <param name="type">Grain type full name.</param> /// <param name="ageLimit">The age limit to use.</param> public void SetCollectionAgeLimit(Type type, TimeSpan ageLimit) { if (type == null) { throw new ArgumentNullException("type"); } SetCollectionAgeLimit(type.FullName, ageLimit); } /// <summary> /// Sets the time period to collect in-active activations for a given type. /// </summary> /// <param name="grainTypeFullName">Grain type full name string.</param> /// <param name="ageLimit">The age limit to use.</param> public void SetCollectionAgeLimit(string grainTypeFullName, TimeSpan ageLimit) { if (String.IsNullOrEmpty(grainTypeFullName)) { throw new ArgumentNullException("grainTypeFullName"); } ThrowIfLessThanZero(ageLimit, "ageLimit"); GrainTypeConfiguration config; if (!classSpecific.TryGetValue(grainTypeFullName, out config)) { config = new GrainTypeConfiguration(grainTypeFullName); classSpecific[grainTypeFullName] = config; } config.SetCollectionAgeLimit(ageLimit); } /// <summary> /// Resets the time period to collect in-active activations for a given type to a default value. /// </summary> /// <param name="type">Grain type full name.</param> public void ResetCollectionAgeLimitToDefault(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } ResetCollectionAgeLimitToDefault(type.FullName); } /// <summary> /// Resets the time period to collect in-active activations for a given type to a default value. /// </summary> /// <param name="grainTypeFullName">Grain type full name.</param> public void ResetCollectionAgeLimitToDefault(string grainTypeFullName) { if (String.IsNullOrEmpty(grainTypeFullName)) { throw new ArgumentNullException(nameof(grainTypeFullName)); } GrainTypeConfiguration config; if (!classSpecific.TryGetValue(grainTypeFullName, out config)) return; config.SetCollectionAgeLimit(null); } /// <summary> /// Sets the default time period to collect in-active activations for all grain type. /// </summary> /// <param name="ageLimit">The age limit to use.</param> public void SetDefaultCollectionAgeLimit(TimeSpan ageLimit) { ThrowIfLessThanZero(ageLimit, "ageLimit"); defaults.SetCollectionAgeLimit(ageLimit); } private static void ThrowIfLessThanZero(TimeSpan timeSpan, string paramName) { if (timeSpan < TimeSpan.Zero) throw new ArgumentOutOfRangeException(paramName); } internal void ValidateConfiguration(Logger logger) { foreach (GrainTypeConfiguration config in classSpecific.Values) { config.ValidateConfiguration(logger); } } /// <summary> /// Prints the current application configuration. /// </summary> /// <returns></returns> public override string ToString() { var result = new StringBuilder(); result.AppendFormat(" Application:").AppendLine(); result.AppendFormat(" Defaults:").AppendLine(); result.AppendFormat(" Deactivate if idle for: {0}", DefaultCollectionAgeLimit) .AppendLine(); foreach (GrainTypeConfiguration config in classSpecific.Values) { if (!config.CollectionAgeLimit.HasValue) continue; result.AppendFormat(" GrainType Type=\"{0}\":", config.FullTypeName) .AppendLine(); result.AppendFormat(" Deactivate if idle for: {0} seconds", (long)config.CollectionAgeLimit.Value.TotalSeconds) .AppendLine(); } return result.ToString(); } } /// <summary> /// Grain type specific application configuration. /// </summary> [Serializable] public class GrainTypeConfiguration { /// <summary> /// The type of the grain of this configuration. /// </summary> public string FullTypeName { get; private set; } /// <summary> /// Whether this is a defualt configuration that applies to all grain types. /// </summary> public bool AreDefaults { get { return FullTypeName == null; } } /// <summary> /// The time period used to collect in-active activations of this type. /// </summary> public TimeSpan? CollectionAgeLimit { get { return collectionAgeLimit; } } private TimeSpan? collectionAgeLimit; /// <summary> /// Constructor. /// </summary> /// <param name="type">Grain type of this configuration.</param> public GrainTypeConfiguration(string type) { FullTypeName = type; } /// <summary> /// Constructor. /// </summary> /// <param name="type">Grain type of this configuration.</param> /// <param name="ageLimit">Age limit for this type.</param> public GrainTypeConfiguration(string type, TimeSpan? ageLimit) { FullTypeName = type; SetCollectionAgeLimit(ageLimit); } /// <summary>Sets a custom collection age limit for a grain type.</summary> /// <param name="ageLimit">Age limit for this type.</param> public void SetCollectionAgeLimit(TimeSpan? ageLimit) { if (ageLimit == null) { collectionAgeLimit = null; } TimeSpan minAgeLimit = GlobalConfiguration.DEFAULT_COLLECTION_QUANTUM; if (ageLimit < minAgeLimit) { if (GlobalConfiguration.ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT) { throw new ArgumentOutOfRangeException($"The AgeLimit attribute is required to be at least {minAgeLimit}."); } } collectionAgeLimit = ageLimit; } /// <summary> /// Load this configuration from xml element. /// </summary> /// <param name="xmlElement"></param> /// <param name="logger"></param> public static GrainTypeConfiguration Load(XmlElement xmlElement, Logger logger) { string fullTypeName = null; bool areDefaults = xmlElement.LocalName == "Defaults"; foreach (XmlAttribute attribute in xmlElement.Attributes) { if (!areDefaults && attribute.LocalName == "Type") { fullTypeName = attribute.Value.Trim(); } else { throw new InvalidOperationException(string.Format("unrecognized attribute {0}", attribute.LocalName)); } } if (!areDefaults) { if (fullTypeName == null) throw new InvalidOperationException("Type attribute not specified"); } bool found = false; TimeSpan? collectionAgeLimit = null; foreach (XmlNode node in xmlElement.ChildNodes) { var child = (XmlElement)node; switch (child.LocalName) { default: throw new InvalidOperationException(string.Format("unrecognized XML element {0}", child.LocalName)); case "Deactivation": found = true; collectionAgeLimit = ConfigUtilities.ParseCollectionAgeLimit(child); break; } } if (found) return new GrainTypeConfiguration(fullTypeName, collectionAgeLimit); throw new InvalidOperationException(string.Format("empty GrainTypeConfiguration for {0}", fullTypeName == null ? "defaults" : fullTypeName)); } internal void ValidateConfiguration(Logger logger) { if (AreDefaults) return; Type type = null; try { type = TypeUtils.ResolveType(FullTypeName); } catch (Exception exception) { string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName); logger.Error(ErrorCode.Loader_TypeLoadError, errStr, exception); throw new OrleansException(errStr, exception); } if (type == null) { string errStr = String.Format("Unable to find grain class type {0} specified in configuration; Failing silo startup.", FullTypeName); logger.Error(ErrorCode.Loader_TypeLoadError_2, errStr); throw new OrleansException(errStr); } var typeInfo = type.GetTypeInfo(); // postcondition: returned type must implement IGrain. if (!typeof(IGrain).IsAssignableFrom(type)) { string errStr = String.Format("Type {0} must implement IGrain to be used Application configuration context.",type.FullName); logger.Error(ErrorCode.Loader_TypeLoadError_3, errStr); throw new OrleansException(errStr); } // postcondition: returned type must either be an interface or a class. if (!typeInfo.IsInterface && !typeInfo.IsClass) { string errStr = String.Format("Type {0} must either be an interface or class used Application configuration context.",type.FullName); logger.Error(ErrorCode.Loader_TypeLoadError_4, errStr); throw new OrleansException(errStr); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="BillingSetupServiceClient"/> instances.</summary> public sealed partial class BillingSetupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="BillingSetupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="BillingSetupServiceSettings"/>.</returns> public static BillingSetupServiceSettings GetDefault() => new BillingSetupServiceSettings(); /// <summary>Constructs a new <see cref="BillingSetupServiceSettings"/> object with default settings.</summary> public BillingSetupServiceSettings() { } private BillingSetupServiceSettings(BillingSetupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetBillingSetupSettings = existing.GetBillingSetupSettings; MutateBillingSetupSettings = existing.MutateBillingSetupSettings; OnCopy(existing); } partial void OnCopy(BillingSetupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BillingSetupServiceClient.GetBillingSetup</c> and <c>BillingSetupServiceClient.GetBillingSetupAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetBillingSetupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BillingSetupServiceClient.MutateBillingSetup</c> and <c>BillingSetupServiceClient.MutateBillingSetupAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateBillingSetupSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="BillingSetupServiceSettings"/> object.</returns> public BillingSetupServiceSettings Clone() => new BillingSetupServiceSettings(this); } /// <summary> /// Builder class for <see cref="BillingSetupServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class BillingSetupServiceClientBuilder : gaxgrpc::ClientBuilderBase<BillingSetupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BillingSetupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BillingSetupServiceClientBuilder() { UseJwtAccessWithScopes = BillingSetupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BillingSetupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BillingSetupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override BillingSetupServiceClient Build() { BillingSetupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BillingSetupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BillingSetupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BillingSetupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BillingSetupServiceClient.Create(callInvoker, Settings); } private async stt::Task<BillingSetupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BillingSetupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BillingSetupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BillingSetupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BillingSetupServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>BillingSetupService client wrapper, for convenient use.</summary> /// <remarks> /// A service for designating the business entity responsible for accrued costs. /// /// A billing setup is associated with a payments account. Billing-related /// activity for all billing setups associated with a particular payments account /// will appear on a single invoice generated monthly. /// /// Mutates: /// The REMOVE operation cancels a pending billing setup. /// The CREATE operation creates a new billing setup. /// </remarks> public abstract partial class BillingSetupServiceClient { /// <summary> /// The default endpoint for the BillingSetupService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default BillingSetupService scopes.</summary> /// <remarks> /// The default BillingSetupService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="BillingSetupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="BillingSetupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="BillingSetupServiceClient"/>.</returns> public static stt::Task<BillingSetupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BillingSetupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BillingSetupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="BillingSetupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns> public static BillingSetupServiceClient Create() => new BillingSetupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="BillingSetupServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="BillingSetupServiceSettings"/>.</param> /// <returns>The created <see cref="BillingSetupServiceClient"/>.</returns> internal static BillingSetupServiceClient Create(grpccore::CallInvoker callInvoker, BillingSetupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BillingSetupService.BillingSetupServiceClient grpcClient = new BillingSetupService.BillingSetupServiceClient(callInvoker); return new BillingSetupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC BillingSetupService client</summary> public virtual BillingSetupService.BillingSetupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BillingSetup GetBillingSetup(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, st::CancellationToken cancellationToken) => GetBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BillingSetup GetBillingSetup(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetBillingSetup(new GetBillingSetupRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetBillingSetupAsync(new GetBillingSetupRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(string resourceName, st::CancellationToken cancellationToken) => GetBillingSetupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::BillingSetup GetBillingSetup(gagvr::BillingSetupName resourceName, gaxgrpc::CallSettings callSettings = null) => GetBillingSetup(new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(gagvr::BillingSetupName resourceName, gaxgrpc::CallSettings callSettings = null) => GetBillingSetupAsync(new GetBillingSetupRequest { ResourceNameAsBillingSetupName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the billing setup to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(gagvr::BillingSetupName resourceName, st::CancellationToken cancellationToken) => GetBillingSetupAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, st::CancellationToken cancellationToken) => MutateBillingSetupAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateBillingSetupResponse MutateBillingSetup(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateBillingSetup(new MutateBillingSetupRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateBillingSetupAsync(new MutateBillingSetupRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. Id of the customer to apply the billing setup mutate operation to. /// </param> /// <param name="operation"> /// Required. The operation to perform. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(string customerId, BillingSetupOperation operation, st::CancellationToken cancellationToken) => MutateBillingSetupAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BillingSetupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service for designating the business entity responsible for accrued costs. /// /// A billing setup is associated with a payments account. Billing-related /// activity for all billing setups associated with a particular payments account /// will appear on a single invoice generated monthly. /// /// Mutates: /// The REMOVE operation cancels a pending billing setup. /// The CREATE operation creates a new billing setup. /// </remarks> public sealed partial class BillingSetupServiceClientImpl : BillingSetupServiceClient { private readonly gaxgrpc::ApiCall<GetBillingSetupRequest, gagvr::BillingSetup> _callGetBillingSetup; private readonly gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> _callMutateBillingSetup; /// <summary> /// Constructs a client wrapper for the BillingSetupService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="BillingSetupServiceSettings"/> used within this client.</param> public BillingSetupServiceClientImpl(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings settings) { GrpcClient = grpcClient; BillingSetupServiceSettings effectiveSettings = settings ?? BillingSetupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetBillingSetup = clientHelper.BuildApiCall<GetBillingSetupRequest, gagvr::BillingSetup>(grpcClient.GetBillingSetupAsync, grpcClient.GetBillingSetup, effectiveSettings.GetBillingSetupSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetBillingSetup); Modify_GetBillingSetupApiCall(ref _callGetBillingSetup); _callMutateBillingSetup = clientHelper.BuildApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse>(grpcClient.MutateBillingSetupAsync, grpcClient.MutateBillingSetup, effectiveSettings.MutateBillingSetupSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateBillingSetup); Modify_MutateBillingSetupApiCall(ref _callMutateBillingSetup); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetBillingSetupApiCall(ref gaxgrpc::ApiCall<GetBillingSetupRequest, gagvr::BillingSetup> call); partial void Modify_MutateBillingSetupApiCall(ref gaxgrpc::ApiCall<MutateBillingSetupRequest, MutateBillingSetupResponse> call); partial void OnConstruction(BillingSetupService.BillingSetupServiceClient grpcClient, BillingSetupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BillingSetupService client</summary> public override BillingSetupService.BillingSetupServiceClient GrpcClient { get; } partial void Modify_GetBillingSetupRequest(ref GetBillingSetupRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateBillingSetupRequest(ref MutateBillingSetupRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::BillingSetup GetBillingSetup(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBillingSetupRequest(ref request, ref callSettings); return _callGetBillingSetup.Sync(request, callSettings); } /// <summary> /// Returns a billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::BillingSetup> GetBillingSetupAsync(GetBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBillingSetupRequest(ref request, ref callSettings); return _callGetBillingSetup.Async(request, callSettings); } /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateBillingSetupResponse MutateBillingSetup(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBillingSetupRequest(ref request, ref callSettings); return _callMutateBillingSetup.Sync(request, callSettings); } /// <summary> /// Creates a billing setup, or cancels an existing billing setup. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [BillingSetupError]() /// [DateError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateBillingSetupResponse> MutateBillingSetupAsync(MutateBillingSetupRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateBillingSetupRequest(ref request, ref callSettings); return _callMutateBillingSetup.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.Common; using System.Dynamic; using System.Linq; using System.Text; namespace Massive { public static class ObjectExtensions { /// <summary> /// Extension method for adding in a bunch of parameters /// </summary> public static void AddParams(this DbCommand cmd, params object[] args) { foreach (var item in args) { AddParam(cmd, item); } } /// <summary> /// Extension for adding single parameter /// </summary> public static void AddParam(this DbCommand cmd, object item) { var p = cmd.CreateParameter(); p.ParameterName = string.Format("@{0}", cmd.Parameters.Count); if (item == null) { p.Value = DBNull.Value; } else { if (item.GetType() == typeof (Guid)) { p.Value = item.ToString(); p.DbType = DbType.String; p.Size = 4000; } else if (item.GetType() == typeof (ExpandoObject)) { var d = (IDictionary<string, object>) item; p.Value = d.Values.FirstOrDefault(); } else { p.Value = item; } if (item.GetType() == typeof (string)) p.Size = ((string) item).Length > 4000 ? -1 : 4000; } cmd.Parameters.Add(p); } /// <summary> /// Turns an IDataReader to a Dynamic list of things /// </summary> public static List<dynamic> ToExpandoList(this IDataReader rdr) { var result = new List<dynamic>(); while (rdr.Read()) { result.Add(rdr.RecordToExpando()); } return result; } public static dynamic RecordToExpando(this IDataReader rdr) { dynamic e = new ExpandoObject(); var d = e as IDictionary<string, object>; for (var i = 0; i < rdr.FieldCount; i++) { d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]); } return e; } /// <summary> /// Turns the object into an ExpandoObject /// </summary> public static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary if (o.GetType() == typeof (ExpandoObject)) return o; //shouldn't have to... but just in case if (o.GetType() == typeof (NameValueCollection) || o.GetType().IsSubclassOf(typeof (NameValueCollection))) { var nv = (NameValueCollection) o; nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i)); } else { var props = o.GetType().GetProperties(); foreach (var item in props) { d.Add(item.Name, item.GetValue(o, null)); } } return result; } /// <summary> /// Turns the object into a Dictionary /// </summary> public static IDictionary<string, object> ToDictionary(this object thingy) { return (IDictionary<string, object>) thingy.ToExpando(); } } /// <summary> /// Convenience class for opening/executing data /// </summary> public static class DB { public static DynamicModel Current { get { if (ConfigurationManager.ConnectionStrings.Count > 1) { return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name); } throw new InvalidOperationException("Need a connection string name - can't determine what it is"); } } } /// <summary> /// A class that wraps your database table in Dynamic Funtime /// </summary> public class DynamicModel : DynamicObject { private readonly DbProviderFactory _factory; private string ConnectionString; public IList<string> Errors = new List<string>(); /// <summary> /// List out all the schema bits for use with ... whatever /// </summary> private IEnumerable<dynamic> _schema; public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "") { TableName = tableName == "" ? GetType().Name : tableName; PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField; DescriptorField = descriptorField; var _providerName = "System.Data.SqlClient"; if (ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName != null) _providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName; _factory = DbProviderFactories.GetFactory(_providerName); ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } /// <summary> /// Creates an empty Expando set with defaults from the DB /// </summary> public dynamic Prototype { get { dynamic result = new ExpandoObject(); var schema = Schema; foreach (var column in schema) { var dc = (IDictionary<string, object>) result; dc.Add(column.COLUMN_NAME, DefaultValue(column)); } result._Table = this; return result; } } public string DescriptorField { get; protected set; } public IEnumerable<dynamic> Schema { get { if (_schema == null) _schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName); return _schema; } } public virtual string PrimaryKeyField { get; set; } public virtual string TableName { get; set; } public DynamicModel SetConnectionString(string connectionString) { ConnectionString = connectionString; return this; } public static DynamicModel Open(string connectionStringName) { dynamic dm = new DynamicModel(connectionStringName); return dm; } /// <summary> /// Creates a new Expando from a Form POST - white listed against the columns in the DB /// </summary> public dynamic CreateFrom(NameValueCollection coll) { dynamic result = new ExpandoObject(); var dc = (IDictionary<string, object>) result; var schema = Schema; //loop the collection, setting only what's in the Schema foreach (var item in coll.Keys) { var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower()); if (exists) { var key = item.ToString(); var val = coll[key]; dc.Add(key, val); } } return result; } /// <summary> /// Gets a default value for the column /// </summary> public dynamic DefaultValue(dynamic column) { dynamic result = null; string def = column.COLUMN_DEFAULT; if (String.IsNullOrEmpty(def)) { result = null; } else if (def == "getdate()" || def == "(getdate())") { result = DateTime.Now.ToShortDateString(); } else if (def == "newid()") { result = Guid.NewGuid().ToString(); } else { result = def.Replace("(", "").Replace(")", ""); } return result; } /// <summary> /// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert /// </summary> public virtual IEnumerable<dynamic> Query(string sql, params object[] args) { using (var conn = OpenConnection()) { var rdr = CreateCommand(sql, conn, args).ExecuteReader(); while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) { using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) { while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } /// <summary> /// Returns a single result /// </summary> public virtual object Scalar(string sql, params object[] args) { object result = null; using (var conn = OpenConnection()) { result = CreateCommand(sql, conn, args).ExecuteScalar(); } return result; } /// <summary> /// Creates a DBCommand that you can use for loving your database. /// </summary> private DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) { var result = _factory.CreateCommand(); result.Connection = conn; result.CommandText = sql; if (args.Length > 0) result.AddParams(args); return result; } /// <summary> /// Returns and OpenConnection /// </summary> public virtual DbConnection OpenConnection() { var result = _factory.CreateConnection(); result.ConnectionString = ConnectionString; result.Open(); return result; } /// <summary> /// Builds a set of Insert and Update commands based on the passed-on objects. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual List<DbCommand> BuildCommands(params object[] things) { var commands = new List<DbCommand>(); foreach (var item in things) { if (HasPrimaryKey(item)) { commands.Add(CreateUpdateCommand(item.ToExpando(), GetPrimaryKey(item))); } else { commands.Add(CreateInsertCommand(item.ToExpando())); } } return commands; } public virtual int Execute(DbCommand command) { return Execute(new[] { command }); } public virtual int Execute(string sql, params object[] args) { return Execute(CreateCommand(sql, null, args)); } /// <summary> /// Executes a series of DBCommands in a transaction /// </summary> public virtual int Execute(IEnumerable<DbCommand> commands) { var result = 0; using (var conn = OpenConnection()) { using (var tx = conn.BeginTransaction()) { foreach (var cmd in commands) { cmd.Connection = conn; cmd.Transaction = tx; result += cmd.ExecuteNonQuery(); } tx.Commit(); } } return result; } /// <summary> /// Conventionally introspects the object passed in for a field that /// looks like a PK. If you've named your PrimaryKeyField, this becomes easy /// </summary> public virtual bool HasPrimaryKey(object o) { return o.ToDictionary().ContainsKey(PrimaryKeyField); } /// <summary> /// If the object passed in has a property with the same name as your PrimaryKeyField /// it is returned here. /// </summary> public virtual object GetPrimaryKey(object o) { object result = null; o.ToDictionary().TryGetValue(PrimaryKeyField, out result); return result; } /// <summary> /// Returns all records complying with the passed-in WHERE clause and arguments, /// ordered as specified, limited (TOP) by limit. /// </summary> public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) { var sql = BuildSelect(where, orderBy, limit); return Query(string.Format(sql, columns, TableName), args); } private static string BuildSelect(string where, string orderBy, int limit) { var sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} "; if (!string.IsNullOrEmpty(where)) sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : " WHERE " + where; if (!String.IsNullOrEmpty(orderBy)) sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy; return sql; } /// <summary> /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords. /// </summary> public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(where: where, orderBy: orderBy, columns: columns, pageSize: pageSize, currentPage: currentPage, args: args); } public virtual dynamic Paged(string sql, string primaryKey, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(sql, primaryKey, where, orderBy, columns, pageSize, currentPage, args); } private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { dynamic result = new ExpandoObject(); var countSQL = ""; if (!string.IsNullOrEmpty(sql)) countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql); else countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName); if (String.IsNullOrEmpty(orderBy)) { orderBy = string.IsNullOrEmpty(primaryKeyField) ? PrimaryKeyField : primaryKeyField; } if (!string.IsNullOrEmpty(where)) { if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) { where = " WHERE " + where; } } var query = ""; if (!string.IsNullOrEmpty(sql)) query = string.Format( "SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM ({3}) AS PagedTable {4}) AS Paged ", columns, pageSize, orderBy, sql, where); else query = string.Format( "SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where); var pageStart = (currentPage - 1)*pageSize; query += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize)); countSQL += where; result.TotalRecords = Scalar(countSQL, args); result.TotalPages = result.TotalRecords/pageSize; if (result.TotalRecords%pageSize > 0) result.TotalPages += 1; result.Items = Query(string.Format(query, columns, TableName), args); return result; } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(string where, params object[] args) { var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where); return Query(sql, args).FirstOrDefault(); } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(object key, string columns = "*") { var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField); return Query(sql, key).FirstOrDefault(); } /// <summary> /// This will return a string/object dictionary for dropdowns etc /// </summary> public virtual IDictionary<string, object> KeyValues(string orderBy = "") { if (String.IsNullOrEmpty(DescriptorField)) throw new InvalidOperationException( "There's no DescriptorField set - do this in your constructor to describe the text value you want to see"); var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName); if (!String.IsNullOrEmpty(orderBy)) sql += "ORDER BY " + orderBy; var results = Query(sql).ToList().Cast<IDictionary<string, object>>(); return results.ToDictionary(key => key[PrimaryKeyField].ToString(), value => value[DescriptorField]); } /// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) { return item; } //Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return dc.ContainsKey(key); } /// <summary> /// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual int Save(params object[] things) { foreach (var item in things) { if (!IsValid(item)) { throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray())); } } var commands = BuildCommands(things); return Execute(commands); } public virtual DbCommand CreateInsertCommand(dynamic expando) { DbCommand result = null; var settings = (IDictionary<string, object>) expando; var sbKeys = new StringBuilder(); var sbVals = new StringBuilder(); var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})"; result = CreateCommand(stub, null); var counter = 0; foreach (var item in settings) { sbKeys.AppendFormat("{0},", item.Key); sbVals.AppendFormat("@{0},", counter); result.AddParam(item.Value); counter++; } if (counter > 0) { var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1); var vals = sbVals.ToString().Substring(0, sbVals.Length - 1); var sql = string.Format(stub, TableName, keys, vals); result.CommandText = sql; } else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set"); return result; } /// <summary> /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with /// </summary> public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) { var settings = (IDictionary<string, object>) expando; var sbKeys = new StringBuilder(); var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}"; var args = new List<object>(); var result = CreateCommand(stub, null); var counter = 0; foreach (var item in settings) { var val = item.Value; if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) { result.AddParam(val); sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter); counter++; } } if (counter > 0) { //add the key result.AddParam(key); //strip the last commas var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4); result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter); } else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs"); return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) { var sql = string.Format("DELETE FROM {0} ", TableName); if (key != null) { sql += string.Format("WHERE {0}=@0", PrimaryKeyField); args = new[] { key }; } else if (!string.IsNullOrEmpty(where)) { sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where; } return CreateCommand(sql, null, args); } public bool IsValid(dynamic item) { Errors.Clear(); Validate(item); return Errors.Count == 0; } //Temporary holder for error messages /// <summary> /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString /// </summary> public virtual dynamic Insert(object o) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray())); } if (BeforeSave(ex)) { using (dynamic conn = OpenConnection()) { var cmd = CreateInsertCommand(ex); cmd.Connection = conn; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @@IDENTITY as newID"; ex.ID = cmd.ExecuteScalar(); Inserted(ex); } return ex; } else { return null; } } /// <summary> /// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString /// </summary> public virtual int Update(object o, object key) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray())); } var result = 0; if (BeforeSave(ex)) { result = Execute(CreateUpdateCommand(ex, key)); Updated(ex); } return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public int Delete(object key = null, string where = "", params object[] args) { var deleted = Single(key); var result = 0; if (BeforeDelete(deleted)) { result = Execute(CreateDeleteCommand(where: where, key: key, args: args)); Deleted(deleted); } return result; } public void DefaultTo(string key, object value, dynamic item) { if (!ItemContainsKey(key, item)) { var dc = (IDictionary<string, object>) item; dc[key] = value; } } //Hooks public virtual void Validate(dynamic item) { } public virtual void Inserted(dynamic item) { } public virtual void Updated(dynamic item) { } public virtual void Deleted(dynamic item) { } public virtual bool BeforeDelete(dynamic item) { return true; } public virtual bool BeforeSave(dynamic item) { return true; } //validation methods public virtual void ValidatesPresenceOf(object value, string message = "Required") { if (value == null) Errors.Add(message); if (String.IsNullOrEmpty(value.ToString())) Errors.Add(message); } //fun methods public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") { var type = value.GetType().Name; var numerics = new[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" }; if (!numerics.Contains(type)) { Errors.Add(message); } } public virtual void ValidateIsCurrency(object value, string message = "Should be money") { if (value == null) Errors.Add(message); var val = decimal.MinValue; decimal.TryParse(value.ToString(), out val); if (val == decimal.MinValue) Errors.Add(message); } public int Count() { return Count(TableName); } public int Count(string tableName, string where = "", params object[] args) { return (int) Scalar("SELECT COUNT(*) FROM " + tableName + " " + where, args); } /// <summary> /// A helpful query tool /// </summary> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //parse the method var constraints = new List<string>(); var counter = 0; var info = binder.CallInfo; // accepting named args only... SKEET! if (info.ArgumentNames.Count != args.Length) { throw new InvalidOperationException( "Please use named arguments for this type of query - the column name, orderby, columns, etc"); } //first should be "FindBy, Last, Single, First" var op = binder.Name; var columns = " * "; var orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField); var sql = ""; var where = ""; var whereArgs = new List<object>(); //loop the named args - see if we have order, columns and constraints if (info.ArgumentNames.Count > 0) { for (var i = 0; i < args.Length; i++) { var name = info.ArgumentNames[i].ToLower(); switch (name) { case "orderby": orderBy = " ORDER BY " + args[i]; break; case "columns": columns = args[i].ToString(); break; default: constraints.Add(string.Format(" {0} = @{1}", name, counter)); whereArgs.Add(args[i]); counter++; break; } } } //Build the WHERE bits if (constraints.Count > 0) { where = " WHERE " + string.Join(" AND ", constraints.ToArray()); } //probably a bit much here but... yeah this whole thing needs to be refactored... if (op.ToLower() == "count") { result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "sum") { result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "max") { result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "min") { result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "avg") { result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else { //build the SQL sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where; var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single"); //Be sure to sort by DESC on the PK (PK Sort is the default) if (op.StartsWith("Last")) { orderBy = orderBy + " DESC "; } else { //default to multiple sql = "SELECT " + columns + " FROM " + TableName + where; } if (justOne) { //return a single record result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault(); } else { //return lots result = Query(sql + orderBy, whereArgs.ToArray()); } } return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using OLEDB.Test.ModuleCore; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // TestCase TCXML Normalization // //////////////////////////////////////////////////////////////// [TestCase(Name = "FactoryReader Normalization", Desc = "FactoryReader")] public partial class TCNormalization : TCXMLReaderBaseGeneral { protected const String ST_ATTR_TEST_NAME = "ATTRIBUTE5"; protected const String ST_ATTR_EXP_STRING = "x x"; protected const String ST_ATTR_EXP_STRING_MS = "x x"; protected const String ST_ELEM_EXP_STRING = "x\nx"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.LBNORMALIZATION); return ret; } public override int Terminate(object objParam) { // just in case it failed without closing DataReader.Close(); return base.Terminate(objParam); } //////////////////////////////////////////////////////////////// // Variations //////////////////////////////////////////////////////////////// [Variation("XmlTextReader Normalization - CRLF in Attribute value", Pri = 0)] public int TestNormalization1() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement(ST_ATTR_TEST_NAME); bPassed = CError.Equals(DataReader.GetAttribute("CRLF"), ST_ATTR_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - CR in Attribute value")] public int TestNormalization2() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement(ST_ATTR_TEST_NAME); bPassed = CError.Equals(DataReader.GetAttribute("CR"), ST_ATTR_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - LF in Attribute value")] public int TestNormalization3() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement(ST_ATTR_TEST_NAME); bPassed = CError.Equals(DataReader.GetAttribute("LF"), ST_ATTR_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - multiple spaces in Attribute value", Pri = 0)] public int TestNormalization4() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement(ST_ATTR_TEST_NAME); // as far as the MS attribute is CDATA internal spaces are not compacted bPassed = CError.Equals(DataReader.GetAttribute("MS"), ST_ATTR_EXP_STRING_MS, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - tab in Attribute value", Pri = 0)] public int TestNormalization5() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement(ST_ATTR_TEST_NAME); bPassed = CError.Equals(DataReader.GetAttribute("TAB"), ST_ATTR_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - CRLF in text node", Pri = 0)] public int TestNormalization6() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement("ENDOFLINE1"); DataReader.Read(); bPassed = CError.Equals(DataReader.Value, ST_ELEM_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - CR in text node")] public int TestNormalization7() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement("ENDOFLINE2"); DataReader.Read(); bPassed = CError.Equals(DataReader.Value, ST_ELEM_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization - LF in text node")] public int TestNormalization8() { bool bPassed = false; ReloadSource(); DataReader.PositionOnElement("ENDOFLINE3"); DataReader.Read(); bPassed = CError.Equals(DataReader.Value, ST_ELEM_EXP_STRING, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("XmlTextReader Normalization = true with invalid chars", Pri = 0)] public int TestNormalization9() { ReloadSourceStr("<root>&#0;&#1;&#2;&#3;&#4;&#5;&#6;&#7;&#8;&#9;</root>"); try { while (DataReader.Read()) ; } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } // XML 1.0 SE [Variation("Line breaks normalization in document entity")] public int TestNormalization11() { ReloadSource(); // #xD should be replaced by #xA while (DataReader.Read()) { if (DataReader.HasValue) { if (DataReader.Value.IndexOf('\r') != -1) { CError.WriteLine("#xD found in node {0}, line {1} col {2}", DataReader.NodeType, DataReader.LineNumber, DataReader.LinePosition); return TEST_FAIL; } } } return TEST_PASS; } [Variation("XmlTextReader Normalization = true with invalid chars")] public int TestNormalization14() { string[] invalidXML = { "0", "8", "B", "C", "E", "1F", "FFFE", "FFFF" }; for (int i = 0; i < invalidXML.Length; i++) { string strxml = String.Format("<ROOT>&#x{0};</ROOT>", invalidXML[i]); ReloadSourceStr(strxml); try { while (DataReader.Read()) ; CError.WriteLine("Accepted invalid character XML"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_InvalidCharacter", e, 1, 10); } } return TEST_PASS; } [Variation("Character entities with Normalization=true")] public int TestNormalization16() { string strxml = "<e a='a&#xD;\r\n \r&#xA;b&#xD;&#x20;&#x9;&#x41;'/>"; string expNormalizedValue = "a\r \nb\r \tA"; ReloadSourceStr(strxml); DataReader.Read(); // use different ways of getting the value string valueGet = DataReader.GetAttribute("a"); DataReader.MoveToAttribute("a"); string valueMove = DataReader.Value; DataReader.ReadAttributeValue(); string valueRead = DataReader.Value; CError.Compare(valueGet, expNormalizedValue, "Wrong normalization (GetAttributeValue)"); CError.Compare(valueMove, expNormalizedValue, "Wrong normalization (MoveToAttribute)"); CError.Compare(valueRead, expNormalizedValue, "Wrong normalization (ReadAttributeValue)"); return TEST_PASS; } [Variation("Character entities with in text nodes")] public int TestNormalization17() { string strxml = "<root>a&#xD;&#xA;&#xD;b</root>"; ReloadSourceStr(strxml); DataReader.PositionOnNodeType(XmlNodeType.Text); CError.Compare(DataReader.Value, "a\r\n\rb", "Wrong end-of-line handling"); return TEST_PASS; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Globalization; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA2208: Instantiate argument exceptions correctly /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class InstantiateArgumentExceptionsCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA2208"; internal const string MessagePosition = nameof(MessagePosition); private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageNoArguments = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageNoArguments), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageIncorrectMessage = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageIncorrectMessage), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageIncorrectParameterName = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyMessageIncorrectParameterName), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor RuleNoArguments = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageNoArguments, DiagnosticCategory.Usage, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor RuleIncorrectMessage = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageIncorrectMessage, DiagnosticCategory.Usage, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor RuleIncorrectParameterName = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageIncorrectParameterName, DiagnosticCategory.Usage, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleNoArguments, RuleIncorrectMessage, RuleIncorrectParameterName); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction( compilationContext => { Compilation compilation = compilationContext.Compilation; ITypeSymbol? argumentExceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException); if (argumentExceptionType == null) { return; } compilationContext.RegisterOperationAction( operationContext => AnalyzeObjectCreation( operationContext, operationContext.ContainingSymbol, argumentExceptionType), OperationKind.ObjectCreation); }); } private static void AnalyzeObjectCreation( OperationAnalysisContext context, ISymbol owningSymbol, ITypeSymbol argumentExceptionType) { var creation = (IObjectCreationOperation)context.Operation; if (!creation.Type.Inherits(argumentExceptionType) || !MatchesConfiguredVisibility(owningSymbol, context) || !HasParameterNameConstructor(creation.Type)) { return; } if (creation.Arguments.IsEmpty) { if (HasParameters(owningSymbol)) { // Call the {0} constructor that contains a message and/ or paramName parameter context.ReportDiagnostic(context.Operation.Syntax.CreateDiagnostic(RuleNoArguments, creation.Type.Name)); } } else { Diagnostic? diagnostic = null; foreach (IArgumentOperation argument in creation.Arguments) { if (argument.Parameter.Type.SpecialType != SpecialType.System_String) { continue; } string? value = argument.Value.ConstantValue.HasValue ? argument.Value.ConstantValue.Value as string : null; if (value == null) { continue; } diagnostic = CheckArgument(owningSymbol, creation, argument.Parameter, value, context); // RuleIncorrectMessage is the highest priority rule, no need to check other rules if (diagnostic != null && diagnostic.Descriptor.Equals(RuleIncorrectMessage)) { break; } } if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } } private static bool MatchesConfiguredVisibility(ISymbol owningSymbol, OperationAnalysisContext context) => context.Options.MatchesConfiguredVisibility(RuleIncorrectParameterName, owningSymbol, context.Compilation, context.CancellationToken, defaultRequiredVisibility: SymbolVisibilityGroup.All); private static bool HasParameters(ISymbol owningSymbol) => !owningSymbol.GetParameters().IsEmpty; private static Diagnostic? CheckArgument( ISymbol targetSymbol, IObjectCreationOperation creation, IParameterSymbol parameter, string stringArgument, OperationAnalysisContext context) { bool matchesParameter = MatchesParameter(targetSymbol, creation, stringArgument); if (IsMessage(parameter) && matchesParameter) { var dictBuilder = ImmutableDictionary.CreateBuilder<string, string?>(); dictBuilder.Add(MessagePosition, parameter.Ordinal.ToString(CultureInfo.InvariantCulture)); return context.Operation.CreateDiagnostic(RuleIncorrectMessage, dictBuilder.ToImmutable(), targetSymbol.Name, stringArgument, parameter.Name, creation.Type.Name); } else if (HasParameters(targetSymbol) && IsParameterName(parameter) && !matchesParameter) { // Allow argument exceptions in accessors to use the associated property symbol name. if (!MatchesAssociatedSymbol(targetSymbol, stringArgument)) { return context.Operation.CreateDiagnostic(RuleIncorrectParameterName, targetSymbol.Name, stringArgument, parameter.Name, creation.Type.Name); } } return null; } private static bool IsMessage(IParameterSymbol parameter) { return parameter.Name == "message"; } private static bool IsParameterName(IParameterSymbol parameter) { return parameter.Name is "paramName" or "parameterName"; } private static bool HasParameterNameConstructor(ITypeSymbol type) { foreach (ISymbol member in type.GetMembers()) { if (!member.IsConstructor()) { continue; } foreach (IParameterSymbol parameter in member.GetParameters()) { if (parameter.Type.SpecialType == SpecialType.System_String && IsParameterName(parameter)) { return true; } } } return false; } private static bool MatchesParameter(ISymbol? symbol, IObjectCreationOperation creation, string stringArgumentValue) { if (MatchesParameterCore(symbol, stringArgumentValue)) { return true; } var operation = creation.Parent; while (operation != null) { symbol = null; switch (operation.Kind) { case OperationKind.LocalFunction: symbol = ((ILocalFunctionOperation)operation).Symbol; break; case OperationKind.AnonymousFunction: symbol = ((IAnonymousFunctionOperation)operation).Symbol; break; } if (symbol != null && MatchesParameterCore(symbol, stringArgumentValue)) { return true; } operation = operation.Parent; } return false; } private static bool MatchesParameterCore(ISymbol? symbol, string stringArgumentValue) { foreach (IParameterSymbol parameter in symbol.GetParameters()) { if (parameter.Name == stringArgumentValue) { return true; } } if (symbol is IMethodSymbol method) { if (method.IsGenericMethod) { foreach (ITypeParameterSymbol parameter in method.TypeParameters) { if (parameter.Name == stringArgumentValue) { return true; } } } } return false; } private static bool MatchesAssociatedSymbol(ISymbol targetSymbol, string stringArgument) => targetSymbol.IsAccessorMethod() && ((IMethodSymbol)targetSymbol).AssociatedSymbol?.Name == stringArgument; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty; public readonly PropertyAccessor<JobConstraints> ConstraintsProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty; public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty; public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<JobNetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty; public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty; public readonly PropertyAccessor<PoolInformation> PoolInformationProperty; public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<int?> PriorityProperty; public readonly PropertyAccessor<Common.JobState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<JobStatistics> StatisticsProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(CommonEnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>(nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None); this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>(nameof(ExecutionInformation), BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>(nameof(JobManagerTask), BindingAccess.Read | BindingAccess.Write); this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>(nameof(JobPreparationTask), BindingAccess.Read | BindingAccess.Write); this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>(nameof(JobReleaseTask), BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<JobNetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>(nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>(nameof(OnTaskFailure), BindingAccess.Read | BindingAccess.Write); this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>(nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(PreviousState), BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(PreviousStateTransitionTime), BindingAccess.None); this.PriorityProperty = this.CreatePropertyAccessor<int?>(nameof(Priority), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>(nameof(Statistics), BindingAccess.None); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>(nameof(UsesTaskDependencies), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings), nameof(CommonEnvironmentSettings), BindingAccess.Read); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)), nameof(Constraints), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, nameof(CreationTime), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, nameof(ETag), BindingAccess.Read); this.ExecutionInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()), nameof(ExecutionInformation), BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read); this.JobManagerTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()), nameof(JobManagerTask), BindingAccess.Read); this.JobPreparationTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()), nameof(JobPreparationTask), BindingAccess.Read); this.JobReleaseTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()), nameof(JobReleaseTask), BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, nameof(LastModified), BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new JobNetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete), nameof(OnAllTasksComplete), BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure), nameof(OnTaskFailure), BindingAccess.Read); this.PoolInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)), nameof(PoolInformation), BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState), nameof(PreviousState), BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, nameof(PreviousStateTransitionTime), BindingAccess.Read); this.PriorityProperty = this.CreatePropertyAccessor( protocolObject.Priority, nameof(Priority), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()), nameof(Statistics), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor( protocolObject.UsesTaskDependencies, nameof(UsesTaskDependencies), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudJob"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudJob( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudJob( BatchClient parentBatchClient, Models.CloudJob protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudJob"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudJob /// <summary> /// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks /// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> public IList<EnvironmentSetting> CommonEnvironmentSettings { get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; } set { this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> public JobConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets the creation time of the job. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets or sets the display name of the job. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the job. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets the execution information for the job. /// </summary> public JobExecutionInformation ExecutionInformation { get { return this.propertyContainer.ExecutionInformationProperty.Value; } } /// <summary> /// Gets or sets the id of the job. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started. /// </summary> public JobManagerTask JobManagerTask { get { return this.propertyContainer.JobManagerTaskProperty.Value; } set { this.propertyContainer.JobManagerTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node /// before starting any tasks of that job on that compute node. /// </summary> public JobPreparationTask JobPreparationTask { get { return this.propertyContainer.JobPreparationTaskProperty.Value; } set { this.propertyContainer.JobPreparationTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Release task. The Batch service runs the Job Release task when the job ends, on each compute /// node where any task of the job has run. /// </summary> public JobReleaseTask JobReleaseTask { get { return this.propertyContainer.JobReleaseTaskProperty.Value; } set { this.propertyContainer.JobReleaseTaskProperty.Value = value; } } /// <summary> /// Gets the last modified time of the job. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration for the job. /// </summary> public JobNetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/> /// state. /// </summary> public Common.OnAllTasksComplete? OnAllTasksComplete { get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; } set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when any task in the job fails. /// </summary> /// <remarks> /// A task is considered to have failed if it completes with a non-zero exit code and has exhausted its retry count, /// or if it had a scheduling error. /// </remarks> public Common.OnTaskFailure? OnTaskFailure { get { return this.propertyContainer.OnTaskFailureProperty.Value; } set { this.propertyContainer.OnTaskFailureProperty.Value = value; } } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's tasks. /// </summary> public PoolInformation PoolInformation { get { return this.propertyContainer.PoolInformationProperty.Value; } set { this.propertyContainer.PoolInformationProperty.Value = value; } } /// <summary> /// Gets the previous state of the job. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined. /// </remarks> public Common.JobState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its previous state. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property /// is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest /// priority and 1000 being the highest priority. /// </summary> /// <remarks> /// The default value is 0. /// </remarks> public int? Priority { get { return this.propertyContainer.PriorityProperty.Value; } set { this.propertyContainer.PriorityProperty.Value = value; } } /// <summary> /// Gets the current state of the job. /// </summary> public Common.JobState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets resource usage statistics for the entire lifetime of the job. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch /// service performs periodic roll-up of statistics. The typical delay is about 30 minutes. /// </remarks> public JobStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on each other. /// </summary> /// <remarks> /// The default value is false. /// </remarks> public bool? UsesTaskDependencies { get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; } set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; } } #endregion // CloudJob #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject() { Models.JobAddParameter result = new Models.JobAddParameter() { CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings), Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()), JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()), JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()), Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete), OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure), PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()), Priority = this.Priority, UsesTaskDependencies = this.UsesTaskDependencies, }; return result; } #endregion // Internal/private methods } }
using UnityEngine; using System.Collections; [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")] public class Bloom : PostEffectsBase { public enum LensFlareStyle { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } public enum BloomQuality { Cheap = 0, High = 1, } public TweakMode tweakMode = 0; public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; public float sepBlurSpread = 2.5f; public BloomQuality quality = BloomQuality.High; public float bloomIntensity = 0.5f; public float bloomThreshhold = 0.5f; public Color bloomThreshholdColor = Color.white; public int bloomBlurIterations = 2; public int hollywoodFlareBlurIterations = 2; public float flareRotation = 0.0f; public LensFlareStyle lensflareMode = (LensFlareStyle) 1; public float hollyStretchWidth = 2.5f; public float lensflareIntensity = 0.0f; public float lensflareThreshhold = 0.3f; public float lensFlareSaturation = 0.75f; public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f); public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f); public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f); public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f); public float blurWidth = 1.0f; public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader blurAndFlaresShader; private Material blurAndFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; public override bool CheckResources (){ CheckSupport (false); screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial); blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if(!isSupported) ReportAutoDisable (); return isSupported; } void OnRenderImage ( RenderTexture source , RenderTexture destination ){ if(CheckResources()==false) { Graphics.Blit (source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if(hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if(doHdr) realBlendMode = BloomScreenBlendMode.Add; var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; var rtW2= source.width/2; var rtH2= source.height/2; var rtW4= source.width/4; var rtH4= source.height/4; float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); if(quality > BloomQuality.Cheap) { Graphics.Blit (source, halfRezColorDown, screenBlend, 2); RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2); Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6); RenderTexture.ReleaseTemporary(rtDown4); } else { Graphics.Blit (source, halfRezColorDown); Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6); } RenderTexture.ReleaseTemporary (halfRezColorDown); // cut colors (threshholding) RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); BrightFilter (bloomThreshhold * bloomThreshholdColor, quarterRezColor, secondQuarterRezColor); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; else if (bloomBlurIterations > 10) bloomBlurIterations = 10; for (int iter = 0; iter < bloomBlurIterations; iter++ ) { float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread; // vertical blur RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary(secondQuarterRezColor); secondQuarterRezColor = blur4; // horizontal blur blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary (secondQuarterRezColor); secondQuarterRezColor = blur4; if (quality > BloomQuality.Cheap) { if (iter == 0) { Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (secondQuarterRezColor, quarterRezColor); } else { quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10); } } } if(quality > BloomQuality.Cheap) { Graphics.SetRenderTarget(secondQuarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6); } // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) if (lensflareIntensity > Mathf.Epsilon) { RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); if (lensflareMode == 0) { // ghosting only BrightFilter (lensflareThreshhold, secondQuarterRezColor, rtFlares4); if(quality > BloomQuality.Cheap) { // smooth a little blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f)); Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f)); Graphics.SetRenderTarget(rtFlares4); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); } // no ugly edges! Vignette (0.975f, rtFlares4, rtFlares4); BlendFlares (rtFlares4, secondQuarterRezColor); } else { //Vignette (0.975ff, rtFlares4, rtFlares4); //DrawBorder(rtFlares4, screenBlend, 8); float flareXRot = 1.0f * Mathf.Cos(flareRotation); float flareyRot = 1.0f * Mathf.Sin(flareRotation); float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshhold, 1.0f, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation); // "pre and cut" quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); // "post" rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f)); // stretch 1st blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // stretch 2nd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); // stretch 3rd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // additional blur passes for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++ ) { stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); } if (lensflareMode == (LensFlareStyle) 1) // anamorphic lens flares AddTo (1.0f, quarterRezColor, secondQuarterRezColor); else { // "combined" lens flares Vignette (1.0f, quarterRezColor, rtFlares4); BlendFlares (rtFlares4, quarterRezColor); AddTo (1.0f, quarterRezColor, secondQuarterRezColor); } } RenderTexture.ReleaseTemporary (rtFlares4); } int blendPass = (int) realBlendMode; //if(Mathf.Abs(chromaticBloom) < Mathf.Epsilon) // blendPass += 4; screenBlend.SetFloat ("_Intensity", bloomIntensity); screenBlend.SetTexture ("_ColorBuffer", source); if(quality > BloomQuality.Cheap) { RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); Graphics.Blit (secondQuarterRezColor, halfRezColorUp); Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (halfRezColorUp); } else Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (quarterRezColor); RenderTexture.ReleaseTemporary (secondQuarterRezColor); } private void AddTo ( float intensity_ , RenderTexture from , RenderTexture to ){ screenBlend.SetFloat ("_Intensity", intensity_); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, screenBlend, 9); } private void BlendFlares ( RenderTexture from , RenderTexture to ){ lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, lensFlareMaterial); } private void BrightFilter ( float thresh , RenderTexture from , RenderTexture to ){ brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh)); Graphics.Blit (from, to, brightPassFilterMaterial, 0); } private void BrightFilter ( Color threshColor , RenderTexture from , RenderTexture to ){ brightPassFilterMaterial.SetVector ("_Threshhold", threshColor); Graphics.Blit (from, to, brightPassFilterMaterial, 1); } private void Vignette ( float amount , RenderTexture from , RenderTexture to ){ if(lensFlareVignetteMask) { screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask); to.MarkRestoreExpected(); // using blending, RT restore expected Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3); } else if (from != to) { Graphics.SetRenderTarget (to); GL.Clear(false, true, Color.black); // clear destination to avoid RT restore Graphics.Blit (from, to); } } }
using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.IO; namespace Org.BouncyCastle.Bcpg { /** * Basic output stream. */ public class ArmoredOutputStream : BaseOutputStream { private static readonly byte[] encodingTable = { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** * encode the input data producing a base 64 encoded byte array. */ private static void Encode( Stream outStream, int[] data, int len) { Debug.Assert(len > 0); Debug.Assert(len < 4); byte[] bs = new byte[4]; int d1 = data[0]; bs[0] = encodingTable[(d1 >> 2) & 0x3f]; switch (len) { case 1: { bs[1] = encodingTable[(d1 << 4) & 0x3f]; bs[2] = (byte)'='; bs[3] = (byte)'='; break; } case 2: { int d2 = data[1]; bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f]; bs[2] = encodingTable[(d2 << 2) & 0x3f]; bs[3] = (byte)'='; break; } case 3: { int d2 = data[1]; int d3 = data[2]; bs[1] = encodingTable[((d1 << 4) | (d2 >> 4)) & 0x3f]; bs[2] = encodingTable[((d2 << 2) | (d3 >> 6)) & 0x3f]; bs[3] = encodingTable[d3 & 0x3f]; break; } } outStream.Write(bs, 0, bs.Length); } private readonly Stream outStream; private int[] buf = new int[3]; private int bufPtr = 0; private Crc24 crc = new Crc24(); private int chunkCount = 0; private int lastb; private bool start = true; private bool clearText = false; private bool newLine = false; private string type; private static readonly string nl = Platform.NewLine; private static readonly string headerStart = "-----BEGIN PGP "; private static readonly string headerTail = "-----"; private static readonly string footerStart = "-----END PGP "; private static readonly string footerTail = "-----"; private static readonly string version = "BCPG C# v" + Assembly.GetExecutingAssembly().GetName().Version; private readonly IDictionary headers; public ArmoredOutputStream(Stream outStream) { this.outStream = outStream; this.headers = new Hashtable(); this.headers["Version"] = version; } public ArmoredOutputStream(Stream outStream, IDictionary headers) { this.outStream = outStream; this.headers = new Hashtable(headers); this.headers["Version"] = version; } /** * Set an additional header entry. * * @param name the name of the header entry. * @param v the value of the header entry. */ public void SetHeader( string name, string v) { headers[name] = v; } /** * Reset the headers to only contain a Version string. */ public void ResetHeaders() { headers.Clear(); headers["Version"] = version; } /** * Start a clear text signed message. * @param hashAlgorithm */ public void BeginClearText( HashAlgorithmTag hashAlgorithm) { string hash; switch (hashAlgorithm) { case HashAlgorithmTag.Sha1: hash = "SHA1"; break; case HashAlgorithmTag.Sha256: hash = "SHA256"; break; case HashAlgorithmTag.Sha384: hash = "SHA384"; break; case HashAlgorithmTag.Sha512: hash = "SHA512"; break; case HashAlgorithmTag.MD2: hash = "MD2"; break; case HashAlgorithmTag.MD5: hash = "MD5"; break; case HashAlgorithmTag.RipeMD160: hash = "RIPEMD160"; break; default: throw new IOException("unknown hash algorithm tag in beginClearText: " + hashAlgorithm); } DoWrite("-----BEGIN PGP SIGNED MESSAGE-----" + nl); DoWrite("Hash: " + hash + nl + nl); clearText = true; newLine = true; lastb = 0; } public void EndClearText() { clearText = false; } public override void WriteByte( byte b) { if (clearText) { outStream.WriteByte(b); if (newLine) { if (!(b == '\n' && lastb == '\r')) { newLine = false; } if (b == '-') { outStream.WriteByte((byte)' '); outStream.WriteByte((byte)'-'); // dash escape } } if (b == '\r' || (b == '\n' && lastb != '\r')) { newLine = true; } lastb = b; return; } if (start) { bool newPacket = (b & 0x40) != 0; int tag; if (newPacket) { tag = b & 0x3f; } else { tag = (b & 0x3f) >> 2; } switch ((PacketTag)tag) { case PacketTag.PublicKey: type = "PUBLIC KEY BLOCK"; break; case PacketTag.SecretKey: type = "PRIVATE KEY BLOCK"; break; case PacketTag.Signature: type = "SIGNATURE"; break; default: type = "MESSAGE"; break; } DoWrite(headerStart + type + headerTail + nl); WriteHeaderEntry("Version", (string) headers["Version"]); foreach (DictionaryEntry de in headers) { string k = (string) de.Key; if (k != "Version") { string v = (string) de.Value; WriteHeaderEntry(k, v); } } DoWrite(nl); start = false; } if (bufPtr == 3) { Encode(outStream, buf, bufPtr); bufPtr = 0; if ((++chunkCount & 0xf) == 0) { DoWrite(nl); } } crc.Update(b); buf[bufPtr++] = b & 0xff; } /** * <b>Note</b>: close does nor close the underlying stream. So it is possible to write * multiple objects using armoring to a single stream. */ public override void Close() { if (type != null) { if (bufPtr > 0) { Encode(outStream, buf, bufPtr); } DoWrite(nl + '='); int crcV = crc.Value; buf[0] = ((crcV >> 16) & 0xff); buf[1] = ((crcV >> 8) & 0xff); buf[2] = (crcV & 0xff); Encode(outStream, buf, 3); DoWrite(nl); DoWrite(footerStart); DoWrite(type); DoWrite(footerTail); DoWrite(nl); outStream.Flush(); type = null; start = true; base.Close(); } } private void WriteHeaderEntry( string name, string v) { DoWrite(name + ": " + v + nl); } private void DoWrite( string s) { byte[] bs = Encoding.ASCII.GetBytes(s); outStream.Write(bs, 0, bs.Length); } } }
// $Id: mxObjectCodec.cs,v 1.3 2013/08/18 20:19:11 gaudenz Exp $ // Copyright (c) 2007-2008, Gaudenz Alder using System; using System.ComponentModel; using System.Diagnostics; using System.Xml; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Text; namespace com.mxgraph { /// <summary> /// Generic codec for C# objects. See below for a detailed description of /// the encoding/decoding scheme. /// Note: Since booleans are numbers in JavaScript, all boolean values are /// encoded into 1 for true and 0 for false. /// </summary> public class mxObjectCodec { /// <summary> /// Immutable empty set. /// </summary> private static List<string> EMPTY_SET = new List<string>(); /// <summary> /// Holds the template object associated with this codec. /// </summary> protected Object template; /// <summary> /// Array containing the variable names that should be /// ignored by the codec. /// </summary> protected List<string> exclude; /// <summary> /// Array containing the variable names that should be /// turned into or converted from references. See /// mxCodec.getId and mxCodec.getObject. /// </summary> protected List<string> idrefs; /// <summary> /// Maps from from fieldnames to XML attribute names. /// </summary> protected Dictionary<string, string> mapping; /// <summary> /// Maps from from XML attribute names to fieldnames. /// </summary> protected Dictionary<string, string> reverse; /// <summary> /// Constructs a new codec for the specified template object. /// </summary> /// <param name="template">Prototypical instance of the object to be encoded/decoded.</param> public mxObjectCodec(Object template) : this(template, null, null, null) { } /// <summary> /// Constructs a new codec for the specified template object. /// The variables in the optional exclude array are ignored by /// the codec. Variables in the optional idrefs array are /// turned into references in the XML. The optional mapping /// may be used to map from variable names to XML attributes. /// </summary> /// <param name="template">Prototypical instance of the object to be encoded/decoded.</param> /// <param name="exclude">Optional array of fieldnames to be ignored.</param> /// <param name="idrefs">Optional array of fieldnames to be converted to/from references.</param> /// <param name="mapping">Optional mapping from field- to attributenames.</param> public mxObjectCodec(Object template, string[] exclude, string[] idrefs, Dictionary<string, string> mapping) { this.template = template; if (exclude != null) { this.exclude = new List<string>(); foreach (string s in exclude) { this.exclude.Add(s); } } else { this.exclude = EMPTY_SET; } if (idrefs != null) { this.idrefs = new List<String>(); foreach (string s in idrefs) { this.idrefs.Add(s); } } else { this.idrefs = EMPTY_SET; } if (mapping == null) { mapping = new Dictionary<string, string>(); } this.mapping = mapping; reverse = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> entry in mapping) { reverse[entry.Value] = entry.Key; } } /// <summary> /// Returns the name used for the nodenames and lookup of the codec when /// classes are encoded and nodes are decoded. For classes to work with /// this the codec registry automatically adds an alias for the classname /// if that is different than what this returns. The default implementation /// returns the classname of the template class. /// </summary> public string GetName() { return mxCodecRegistry.GetName(Template); } /// <summary> /// Returns the template object associated with this codec. /// </summary> /// <returns>Returns the template object.</returns> public Object Template { get { return template; } } /// <summary> /// Returns a new instance of the template object for representing the given /// node. /// </summary> /// <param name="node">XML node that the object is going to represent.</param> /// <returns>Returns a new template instance.</returns> protected virtual Object CloneTemplate(XmlNode node) { Object obj = null; try { obj = Activator.CreateInstance(template.GetType()); // Special case: Check if the collection // should be a map. This is if the first // child has an "as"-attribute. This // assumes that all childs will have // as attributes in this case. This is // required because in JavaScript, the // map and array object are the same. if (obj is ICollection) { node = node.FirstChild; if (node.Attributes["as"] != null) { obj = new Hashtable(); } } } catch (Exception e) { Trace.WriteLine(this + ".CloneTemplate(" + node + "): " + e.Message + " for " + template); } return obj; } /// <summary> /// Returns true if the given attribute is to be ignored /// by the codec. This implementation returns true if the /// given fieldname is in exclude. /// </summary> /// <param name="obj">Object instance that contains the field.</param> /// <param name="attr">Fieldname of the field.</param> /// <param name="value">Value of the field.</param> /// <param name="write">Boolean indicating if the field is being encoded or /// decoded. write is true if the field is being encoded, else it is /// being decoded.</param> /// <returns>Returns true if the given attribute should be ignored.</returns> public virtual bool IsExcluded(Object obj, string attr, Object value, bool write) { return exclude.Contains(attr); } /// <summary> /// Returns true if the given fieldname is to be treated /// as a textual reference (ID). This implementation returns /// true if the given fieldname is in idrefs. /// </summary> /// <param name="obj">Object instance that contains the field.</param> /// <param name="attr">Fieldname of the field.</param> /// <param name="value">Value of the field.</param> /// <param name="write">Boolean indicating if the field is being encoded or /// decoded. write is true if the field is being encoded, else it is being /// decoded.</param> /// <returns>Returns true if the given attribute should be handled as a /// reference.</returns> public virtual bool IsReference(Object obj, string attr, Object value, bool write) { return idrefs.Contains(attr); } /// <summary> /// Encodes the specified object and returns a node /// representing then given object. Calls beforeEncode /// after creating the node and afterEncode with the /// resulting node after processing. /// Enc is a reference to the calling encoder. It is used /// to encode complex objects and create references. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object to be encoded.</param> /// <returns>Returns the resulting XML node that represents the given object.</returns> public virtual XmlNode Encode(mxCodec enc, Object obj) { XmlNode node = enc.Document.CreateElement(GetName()); obj = BeforeEncode(enc, obj, node); EncodeObject(enc, obj, node); return AfterEncode(enc, obj, node); } /// <summary> /// Encodes the value of each member in then given obj /// into the given node using encodeFields and encodeElements. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object to be encoded.</param> /// <param name="node">XML node that contains the encoded object.</param> protected virtual void EncodeObject(mxCodec enc, Object obj, XmlNode node) { mxCodec.SetAttribute(node, "id", enc.GetId(obj)); EncodeFields(enc, obj, node); EncodeElements(enc, obj, node); } /// <summary> /// Encodes the members of the given object into the given node. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object whose fields should be encoded.</param> /// <param name="node">XML node that contains the encoded object.</param> protected void EncodeFields(mxCodec enc, Object obj, XmlNode node) { Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (property.CanRead && property.CanWrite) { string name = property.Name; Object value = GetFieldValue(obj, name); // Removes Is-Prefix from bool properties if (value is bool && name.StartsWith("Is")) { name = name.Substring(2); } name = name.Substring(0, 1).ToLower() + name.Substring(1); EncodeValue(enc, obj, name, value, node); } } } /// <summary> /// Encodes the child objects of arrays, dictionaries and enumerables. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object whose child objects should be encoded.</param> /// <param name="node">XML node that contains the encoded object.</param> protected void EncodeElements(mxCodec enc, Object obj, XmlNode node) { if (obj.GetType().IsArray) { foreach (Object o in ((Object[])obj)) { EncodeValue(enc, obj, null, o, node); } } else if (obj is IDictionary) { foreach (KeyValuePair<string, string> entry in ((IDictionary)mapping)) { EncodeValue(enc, obj, entry.Key, entry.Value, node); } } else if (obj is IEnumerable) { foreach (Object value in ((IEnumerable)obj)) { EncodeValue(enc, obj, null, value, node); } } } /// <summary> /// Converts the given value according to the mappings and id-refs in /// this codec and uses writeAttribute to write the attribute into the /// given node. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object whose member is going to be encoded.</param> /// <param name="fieldname"></param> /// <param name="value">Value of the property to be encoded.</param> /// <param name="node">XML node that contains the encoded object.</param> protected void EncodeValue(mxCodec enc, Object obj, string fieldname, Object value, XmlNode node) { if (value != null && !IsExcluded(obj, fieldname, value, true)) { if (IsReference(obj, fieldname, value, true)) { Object tmp = enc.GetId(value); if (tmp == null) { Trace.WriteLine("mxObjectCodec.encode: No ID for " + GetName() + "." + fieldname + "=" + value); return; // exit } value = tmp; } Object defaultValue = GetFieldValue(template, fieldname); if (fieldname == null || enc.IsEncodeDefaults || defaultValue == null || !defaultValue.Equals(value)) { WriteAttribute(enc, obj, GetAttributeName(fieldname), value, node); } } } /// <summary> /// Returns true if the given object is a primitive value. /// </summary> /// <param name="value">Object that should be checked.</param> /// <returns>Returns true if the given object is a primitive value.</returns> protected bool IsPrimitiveValue(Object value) { return value is string || value is Boolean || value is Char || value is Byte || value is Int16 || value is Int32 || value is Int64 || value is Single || value is Double || value.GetType().IsPrimitive; } /// <summary> /// Writes the given value into node using writePrimitiveAttribute /// or writeComplexAttribute depending on the type of the value. /// </summary> /// protected void WriteAttribute(mxCodec enc, Object obj, string attr, Object value, XmlNode node) { value = ConvertValueToXml(value); if (IsPrimitiveValue(value)) { WritePrimitiveAttribute(enc, obj, attr, value, node); } else { WriteComplexAttribute(enc, obj, attr, value, node); } } /// <summary> /// Writes the given value as an attribute of the given node. /// </summary> protected void WritePrimitiveAttribute(mxCodec enc, Object obj, string attr, Object value, XmlNode node) { if (attr == null || obj is IDictionary) { XmlNode child = enc.Document.CreateElement("add"); if (attr != null) { mxCodec.SetAttribute(child, "as", attr); } mxCodec.SetAttribute(child, "value", value); node.AppendChild(child); } else { mxCodec.SetAttribute(node, attr, value); } } /// <summary> /// Writes the given value as a child node of the given node. /// </summary> protected void WriteComplexAttribute(mxCodec enc, Object obj, string attr, Object value, XmlNode node) { XmlNode child = enc.Encode(value); if (child != null) { if (attr != null) { mxCodec.SetAttribute(child, "as", attr); } node.AppendChild(child); } else { Trace.WriteLine("mxObjectCodec.encode: No node for " + GetName() + "." + attr + ": " + value); } } /// <summary> /// Converts true to "1" and false to "0". All other values are ignored. /// </summary> protected virtual Object ConvertValueToXml(Object value) { if (value is Boolean) { value = ((bool)value) ? "1" : "0"; } return value; } /// <summary> /// Converts XML attribute values to object of the given type. /// </summary> protected virtual Object ConvertValueFromXml(Type type, Object value) { // Special case: Booleans are stored as numeric values if (type == true.GetType()) // TODO: static type reference { value = value.Equals("1"); } else { TypeConverter tc = TypeDescriptor.GetConverter(type); if (tc.CanConvertFrom(value.GetType())) { value = tc.ConvertFrom(value); } } return value; } /// <summary> /// Returns the XML node attribute name for the given C# field name. /// That is, it returns the mapping of the field name. /// </summary> protected string GetAttributeName(string fieldname) { if (fieldname != null) { string mapped = (mapping.ContainsKey(fieldname)) ? mapping[fieldname] : null; if (mapped != null) { fieldname = mapped; } } return fieldname; } /// <summary> /// Returns the C# field name for the given XML attribute /// name. That is, it returns the reverse mapping of the /// attribute name. /// </summary> /// <param name="attributename">The attribute name to be mapped.</param> /// <returns>String that represents the mapped field name.</returns> protected string GetFieldName(string attributename) { if (attributename != null) { string mapped = (reverse.ContainsKey(attributename)) ? reverse[attributename] : null; if (mapped != null) { attributename = mapped; } } return attributename; } /// <summary> /// Returns the value of the field with the specified name /// in the specified object instance. /// </summary> protected Object GetFieldValue(Object obj, string name) { Object value = null; if (obj != null && name != null && name.Length > 0) { name = name.Substring(0, 1).ToUpper() + name.Substring(1); PropertyInfo property = obj.GetType().GetProperty(name); // Gets a boolean property by adding Is-Prefix if (property == null) { property = obj.GetType().GetProperty("Is"+name); } try { value = property.GetValue(obj, null); } catch (Exception e) { Trace.WriteLine(this + ".GetFieldValue(" + obj + ", " + name + "): " + e.Message); } } return value; } /// <summary> /// Sets the value of the field with the specified name /// in the specified object instance. /// </summary> protected void SetFieldValue(Object obj, string name, Object value) { try { name = name.Substring(0, 1).ToUpper() + name.Substring(1); PropertyInfo property = obj.GetType().GetProperty(name); // Finds a boolean property by adding Is-Prefix if (property == null) { property = obj.GetType().GetProperty("Is"+name); if ((!value.Equals("1") && !value.Equals("0")) || property.PropertyType != true.GetType()) { property = null; } } if (property != null) { value = ConvertValueFromXml(property.PropertyType, value); // Converts collection to a typed array or typed list if (value is ArrayList) { ArrayList list = (ArrayList)value; if (property.PropertyType.IsArray) { value = list.ToArray(property.PropertyType.GetElementType()); } else if (list.Count > 0 && property.PropertyType.IsAssignableFrom(typeof(List<>).MakeGenericType(list[0].GetType()))) { IList newValue = (IList)Activator.CreateInstance(property.PropertyType); Type targetType = property.PropertyType.GetGenericArguments()[0]; foreach (var elt in list) { if (targetType.IsAssignableFrom(elt.GetType())) { newValue.Add(elt); } } value = newValue; } } property.SetValue(obj, value, null); } else { Console.WriteLine("Cannot set field " + name); } } catch (Exception e) { Trace.WriteLine(this + ".SetFieldValue(" + obj + ", " + name + ", " + value + "): " + e.Message); } } /// <summary> /// Hook for subclassers to pre-process the object before /// encoding. This returns the input object. The return /// value of this function is used in encode to perform /// the default encoding into the given node. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object to be encoded.</param> /// <param name="node">XML node to encode the object into.</param> /// <returns>Returns the object to be encoded by the default encoding.</returns> public virtual Object BeforeEncode(mxCodec enc, Object obj, XmlNode node) { return obj; } /// <summary> /// Hook for subclassers to Receive-process the node /// for the given object after encoding and return the /// Receive-processed node. This implementation returns /// the input node. The return value of this method /// is returned to the encoder from encode. /// </summary> /// <param name="enc">Codec that controls the encoding process.</param> /// <param name="obj">Object to be encoded.</param> /// <param name="node">XML node that represents the default encoding.</param> /// <returns>Returns the resulting node of the encoding.</returns> public virtual XmlNode AfterEncode(mxCodec enc, Object obj, XmlNode node) { return node; } /// <summary> /// Parses the given node into the object or returns a new object /// representing the given node. /// </summary> /// <param name="dec">Codec that controls the encoding process.</param> /// <param name="node">XML node to be decoded.</param> /// <returns>Returns the resulting object that represents the given XML node.</returns> public virtual Object Decode(mxCodec dec, XmlNode node) { return Decode(dec, node, null); } /// <summary> /// Parses the given node into the object or returns a new object /// representing the given node. /// Dec is a reference to the calling decoder. It is used to decode /// complex objects and resolve references. /// If a node has an id attribute then the object cache is checked for the /// object. If the object is not yet in the cache then it is constructed /// using the constructor of template and cached in mxCodec.objects. /// This implementation decodes all attributes and childs of a node /// according to the following rules: /// - If the variable name is in exclude or if the attribute name is "id" /// or "as" then it is ignored. /// - If the variable name is in idrefs then mxCodec.getObject is used /// to replace the reference with an object. /// - The variable name is mapped using a reverse mapping. /// - If the value has a child node, then the codec is used to create a /// child object with the variable name taken from the "as" attribute. /// - If the object is an array and the variable name is empty then the /// value or child object is appended to the array. /// - If an add child has no value or the object is not an array then /// the child text content is evaluated using mxUtils.eval. /// If no object exists for an ID in idrefs a warning is issued /// using mxLog.warn. /// Returns the resulting object that represents the given XML /// node or the configured given object. /// </summary> /// <param name="dec">Codec that controls the encoding process.</param> /// <param name="node">XML node to be decoded.</param> /// <param name="into">Optional objec to encode the node into.</param> /// <returns>Returns the resulting object that represents the given XML node /// or the object given to the method as the into parameter.</returns> public virtual Object Decode(mxCodec dec, XmlNode node, Object into) { Object obj = null; if (node is XmlElement) { string id = ((XmlElement)node).GetAttribute("id"); obj = (dec.Objects.ContainsKey(id)) ? dec.Objects[id] : null; if (obj == null) { obj = into; if (obj == null) { obj = CloneTemplate(node); } if (id != null && id.Length > 0) { dec.PutObject(id, obj); } } node = BeforeDecode(dec, node, obj); DecodeNode(dec, node, obj); obj = AfterDecode(dec, node, obj); } return obj; } /// <summary> /// Calls decodeAttributes and decodeChildren for the given node. /// </summary> protected void DecodeNode(mxCodec dec, XmlNode node, Object obj) { if (node != null) { DecodeAttributes(dec, node, obj); DecodeChildren(dec, node, obj); } } /// <summary> /// Decodes all attributes of the given node using decodeAttribute. /// </summary> protected void DecodeAttributes(mxCodec dec, XmlNode node, Object obj) { XmlAttributeCollection attrs = node.Attributes; if (attrs != null) { foreach (XmlAttribute attr in attrs) { DecodeAttribute(dec, attr, obj); } } } /// <summary> /// Reads the given attribute into the specified object. /// </summary> protected void DecodeAttribute(mxCodec dec, XmlNode attr, Object obj) { string name = attr.Name; if (!name.ToLower().Equals("as") && !name.ToLower().Equals("id")) { Object value = attr.Value; string fieldname = GetFieldName(name); if (IsReference(obj, fieldname, value, false)) { Object tmp = dec.GetObject(value.ToString()); if (tmp == null) { Trace.WriteLine("mxObjectCodec.decode: No object for " + GetName() + "." + fieldname + "=" + value); return; // exit } value = tmp; } if (!IsExcluded(obj, fieldname, value, false)) { SetFieldValue(obj, fieldname, value); } } } /// <summary> /// Reads the given attribute into the specified object. /// </summary> protected void DecodeChildren(mxCodec dec, XmlNode node, Object obj) { XmlNode child = node.FirstChild; while (child != null) { if (child.NodeType == XmlNodeType.Element && !ProcessInclude(dec, child, obj)) { DecodeChild(dec, child, obj); } child = child.NextSibling; } } /// <summary> /// Reads the specified child into the given object. /// </summary> protected void DecodeChild(mxCodec dec, XmlNode child, Object obj) { string fieldname = GetFieldName(((XmlElement)child).GetAttribute("as")); if (fieldname == null || !IsExcluded(obj, fieldname, child, false)) { Object template = GetFieldTemplate(obj, fieldname, child); Object value = null; if (child.Name.Equals("add")) { value = ((XmlElement)child).GetAttribute("value"); if (value == null) { value = child.InnerText; } } else { value = dec.Decode(child, template); } AddObjectValue(obj, fieldname, value, template); } } /// <summary> /// Returns the template instance for the given field. This returns the /// value of the field, null if the value is an array or an empty collection /// if the value is a collection. The value is then used to populate the /// field for a new instance. For strongly typed languages it may be /// required to override this to return the correct collection instance /// based on the encoded child. /// </summary> protected Object GetFieldTemplate(Object obj, String fieldname, XmlNode child) { Object template = GetFieldValue(obj, fieldname); // Arrays are replaced completely if (template != null && template.GetType().IsArray) { template = null; } // Collections are cleared else if (template is IList) { ((IList)template).Clear(); } return template; } /// <summary> /// Sets the decoded child node as a value of the given object. If the /// object is a map, then the value is added with the given fieldname as a /// key. If the fieldname is not empty, then setFieldValue is called or /// else, if the object is a collection, the value is added to the /// collection. For strongly typed languages it may be required to /// override this with the correct code to add an entry to an object. /// </summary> protected void AddObjectValue(Object obj, String fieldname, Object value, Object template) { if (value != null && !value.Equals(template)) { if (fieldname != null && obj is IDictionary) { ((IDictionary)obj).Add(fieldname, value); } else if (fieldname != null && fieldname.Length > 0) { SetFieldValue(obj, fieldname, value); } // Arrays are treated as collections and // converted in setFieldValue else if (obj is IList) { ((IList)obj).Add(value); } } } /// <summary> /// /// </summary> /// <param name="dec">Codec that controls the encoding/decoding process.</param> /// <param name="node">XML node to be checked.</param> /// <param name="into">Optional object to pass-thru to the codec.</param> /// <returns>Returns true if the given node was processed as an include.</returns> public bool ProcessInclude(mxCodec dec, XmlNode node, Object into) { if (node.NodeType == XmlNodeType.Element && node.Name.ToLower().Equals("include")) { string name = ((XmlElement)node).GetAttribute("name"); if (name != null) { XmlNode xml = mxUtils.LoadDocument(name).DocumentElement; if (xml != null) { dec.Decode(xml, into); } } return true; } return false; } /// <summary> /// Hook for subclassers to pre-process the node for /// the specified object and return the node to be /// used for further processing by decode. /// The object is created based on the template in the /// calling method and is never null. This implementation /// returns the input node. The return value of this /// function is used in decode to perform /// the default decoding into the given object. /// </summary> /// <param name="dec">Codec that controls the decoding process.</param> /// <param name="node">XML node to be decoded.</param> /// <param name="obj">Object to encode the node into.</param> /// <returns>Returns the node used for the default decoding.</returns> public virtual XmlNode BeforeDecode(mxCodec dec, XmlNode node, Object obj) { return node; } /// <summary> /// Hook for subclassers to Receive-process the object after /// decoding. This implementation returns the given object /// without any changes. The return value of this method /// is returned to the decoder from decode. /// </summary> /// <param name="dec">Codec that controls the decoding process.</param> /// <param name="node">XML node to be decoded.</param> /// <param name="obj">Object that represents the default decoding.</param> /// <returns>Returns the result of the decoding process.</returns> public virtual Object AfterDecode(mxCodec dec, XmlNode node, Object obj) { return obj; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AmbientServicesExtensions.cs" company="Kephas Software SRL"> // Copyright (c) Kephas Software SRL. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> // <summary> // Implements the ambient services extensions class. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas { using System; using Kephas.Application; using Kephas.Composition; using Kephas.Composition.Hosting; using Kephas.Composition.Lite; using Kephas.Composition.Lite.Hosting; using Kephas.Configuration; using Kephas.Cryptography; using Kephas.Diagnostics.Contracts; using Kephas.Licensing; using Kephas.Logging; using Kephas.Reflection; using Kephas.Resources; using Kephas.Services; /// <summary> /// Extension methods for <see cref="IAmbientServices"/>. /// </summary> public static class AmbientServicesExtensions { /// <summary> /// Gets the logger with the provided name. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="loggerName">Name of the logger.</param> /// <returns> /// A logger for the provided name. /// </returns> public static ILogger GetLogger(this IAmbientServices ambientServices, string loggerName) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNullOrEmpty(loggerName, nameof(loggerName)); return ambientServices.LogManager.GetLogger(loggerName); } /// <summary> /// Gets the logger for the provided type. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="type">The type.</param> /// <returns> /// A logger for the provided type. /// </returns> public static ILogger GetLogger(this IAmbientServices ambientServices, Type type) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(type, nameof(type)); return ambientServices.LogManager.GetLogger(type); } /// <summary> /// Gets the logger for the provided type. /// </summary> /// <typeparam name="T">The type for which a logger should be created.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// A logger for the provided type. /// </returns> public static ILogger GetLogger<T>(this IAmbientServices ambientServices) { Requires.NotNull(ambientServices, nameof(ambientServices)); return ambientServices.LogManager.GetLogger(typeof(T)); } /// <summary> /// Configures the settings. /// </summary> /// <typeparam name="TSettings">Type of the settings.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="optionsConfig">The options configuration.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Configure<TSettings>(this IAmbientServices ambientServices, Action<TSettings> optionsConfig) where TSettings : class, new() { Requires.NotNull(ambientServices, nameof(ambientServices)); ambientServices.ConfigurationStore.Configure(optionsConfig); return ambientServices; } /// <summary> /// Registers the provided service. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="builder">The registration builder.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register<TService>(this IAmbientServices ambientServices, Action<IServiceRegistrationBuilder> builder) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(builder, nameof(builder)); return ambientServices.Register(typeof(TService), builder); } /// <summary> /// Registers the provided service, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="builder">The registration builder.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple<TService>(this IAmbientServices ambientServices, Action<IServiceRegistrationBuilder> builder) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(builder, nameof(builder)); return ambientServices.Register( typeof(TService), b => { builder(b); b.AllowMultiple(); }); } /// <summary> /// Registers the provided service instance. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="service">The service.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register<TService>(this IAmbientServices ambientServices, TService service) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(service, nameof(service)); return ambientServices.Register(typeof(TService), b => b.WithInstance(service)); } /// <summary> /// Registers the provided service instance, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="service">The service.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple<TService>(this IAmbientServices ambientServices, TService service) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(service, nameof(service)); return ambientServices.Register(typeof(TService), b => b.WithInstance(service).AllowMultiple()); } /// <summary> /// Registers the provided service with implementation type as singleton. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <typeparam name="TServiceImplementation">Type of the service implementation.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register<TService, TServiceImplementation>(this IAmbientServices ambientServices) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); return ambientServices.Register( typeof(TService), b => b.WithType(typeof(TServiceImplementation)) .AsSingleton()); } /// <summary> /// Registers the provided service with implementation type as singleton, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <typeparam name="TServiceImplementation">Type of the service implementation.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple<TService, TServiceImplementation>(this IAmbientServices ambientServices) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); return ambientServices.Register( typeof(TService), b => b.WithType(typeof(TServiceImplementation)) .AsSingleton() .AllowMultiple()); } /// <summary> /// Registers the provided service with implementation type as transient. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <typeparam name="TServiceImplementation">Type of the service implementation.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransient<TService, TServiceImplementation>(this IAmbientServices ambientServices) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); return ambientServices.Register( typeof(TService), b => b.WithType(typeof(TServiceImplementation)) .AsTransient()); } /// <summary> /// Registers the provided service with implementation type as transient, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <typeparam name="TServiceImplementation">Type of the service implementation.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransientMultiple<TService, TServiceImplementation>(this IAmbientServices ambientServices) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); return ambientServices.Register( typeof(TService), b => b.WithType(typeof(TServiceImplementation)) .AsTransient() .AllowMultiple()); } /// <summary> /// Registers the provided service as singleton factory. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register<TService>( this IAmbientServices ambientServices, Func<TService> serviceFactory) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( typeof(TService), b => b.WithFactory(ctx => serviceFactory()) .AsSingleton()); } /// <summary> /// Registers the provided service as singleton factory, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple<TService>( this IAmbientServices ambientServices, Func<TService> serviceFactory) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( typeof(TService), b => b.WithFactory(ctx => serviceFactory()) .AsSingleton() .AllowMultiple()); } /// <summary> /// Registers the provided service as transient factory. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransient<TService>( this IAmbientServices ambientServices, Func<TService> serviceFactory) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( typeof(TService), b => b.WithFactory(ctx => serviceFactory()) .AsTransient()); } /// <summary> /// Registers the provided service as transient factory, allowing also multiple registrations. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransientMultiple<TService>( this IAmbientServices ambientServices, Func<TService> serviceFactory) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( typeof(TService), b => b.WithFactory(ctx => serviceFactory()) .AsTransient() .AllowMultiple()); } /// <summary> /// Registers the provided service as singleton factory. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register( this IAmbientServices ambientServices, Type serviceType, Func<object> serviceFactory) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( serviceType, b => b.WithFactory(ctx => serviceFactory()) .AsSingleton()); } /// <summary> /// Registers the provided service as singleton factory, allowing also multiple registrations. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple( this IAmbientServices ambientServices, Type serviceType, Func<object> serviceFactory) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( serviceType, b => b.WithFactory(ctx => serviceFactory()) .AsSingleton() .AllowMultiple()); } /// <summary> /// Registers the provided service as transient factory. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransient( this IAmbientServices ambientServices, Type serviceType, Func<object> serviceFactory) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( serviceType, b => b.WithFactory(ctx => serviceFactory()) .AsTransient()); } /// <summary> /// Registers the provided service as transient factory, allowing also multiple registrations. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceFactory">The service factory.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransientMultiple( this IAmbientServices ambientServices, Type serviceType, Func<object> serviceFactory) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceFactory, nameof(serviceFactory)); return ambientServices.Register( serviceType, b => b.WithFactory(ctx => serviceFactory()) .AsTransient() .AllowMultiple()); } /// <summary> /// Registers the provided service. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="service">The service.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register( this IAmbientServices ambientServices, Type serviceType, object service) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(service, nameof(service)); return ambientServices.Register(serviceType, b => b.WithInstance(service)); } /// <summary> /// Registers the provided service, allowing also multiple registrations. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="service">The service.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple( this IAmbientServices ambientServices, Type serviceType, object service) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(service, nameof(service)); return ambientServices.Register(serviceType, b => b.WithInstance(service).AllowMultiple()); } /// <summary> /// Registers the provided service as singleton. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceImplementationType">The service implementation type.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices Register( this IAmbientServices ambientServices, Type serviceType, Type serviceImplementationType) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceImplementationType, nameof(serviceImplementationType)); ambientServices.Register( serviceType, b => b.WithType(serviceImplementationType).AsSingleton()); return ambientServices; } /// <summary> /// Registers the provided service as singleton, allowing also multiple registrations. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceImplementationType">The service implementation type.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterMultiple( this IAmbientServices ambientServices, Type serviceType, Type serviceImplementationType) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceImplementationType, nameof(serviceImplementationType)); ambientServices.Register( serviceType, b => b.WithType(serviceImplementationType).AsSingleton().AllowMultiple()); return ambientServices; } /// <summary> /// Registers the provided service as transient. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceImplementationType">The service implementation type.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransient( this IAmbientServices ambientServices, Type serviceType, Type serviceImplementationType) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceImplementationType, nameof(serviceImplementationType)); ambientServices.Register( serviceType, b => b.WithType(serviceImplementationType).AsTransient()); return ambientServices; } /// <summary> /// Registers the provided service as transient, allowing also multiple registrations. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <param name="serviceImplementationType">The service implementation type.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices RegisterTransientMultiple( this IAmbientServices ambientServices, Type serviceType, Type serviceImplementationType) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); Requires.NotNull(serviceImplementationType, nameof(serviceImplementationType)); ambientServices.Register( serviceType, b => b.WithType(serviceImplementationType).AsTransient().AllowMultiple()); return ambientServices; } /// <summary> /// Gets the service with the provided type. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// A service object of type <typeparamref name="TService"/>.-or- <c>null</c> if there is no /// service object of type <typeparamref name="TService"/>. /// </returns> public static TService GetService<TService>(this IServiceProvider ambientServices) where TService : class { Requires.NotNull(ambientServices, nameof(ambientServices)); return (TService)ambientServices.GetService(typeof(TService)); } /// <summary> /// Gets the service with the provided type. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="serviceType">Type of the service.</param> /// <returns> /// A service object of type <paramref name="serviceType"/>. /// </returns> public static object GetRequiredService(this IServiceProvider ambientServices, Type serviceType) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(serviceType, nameof(serviceType)); var service = ambientServices.GetService(serviceType); if (service == null) { throw new CompositionException( string.Format( Strings.AmbientServices_RequiredServiceNotRegistered_Exception, serviceType)); } return service; } /// <summary> /// Gets the service with the provided type. /// </summary> /// <typeparam name="TService">Type of the service.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <returns> /// A service object of type <typeparamref name="TService"/>.-or- <c>null</c> if there is no /// service object of type <typeparamref name="TService"/>. /// </returns> public static TService GetRequiredService<TService>(this IServiceProvider ambientServices) where TService : class { return (TService)GetRequiredService(ambientServices, typeof(TService)); } /// <summary> /// Sets the configuration store to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="configurationStore">The configuration store.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithConfigurationStore(this IAmbientServices ambientServices, IConfigurationStore configurationStore) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(configurationStore, nameof(configurationStore)); ambientServices.Register(configurationStore); return ambientServices; } /// <summary> /// Sets the licensing manager to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="licensingManager">The licensing manager.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithLicensingManager(this IAmbientServices ambientServices, ILicensingManager licensingManager) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(licensingManager, nameof(licensingManager)); ambientServices.Register(licensingManager); return ambientServices; } /// <summary> /// Sets the default licensing manager to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="encryptionService">The encryption service.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithDefaultLicensingManager(this IAmbientServices ambientServices, IEncryptionService encryptionService) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(encryptionService, nameof(encryptionService)); const string LicenseRepositoryKey = "__LicenseRepository"; ambientServices.Register<ILicensingManager>(new DefaultLicensingManager(appid => ((ambientServices[LicenseRepositoryKey] as ILicenseRepository) ?? (ILicenseRepository)(ambientServices[LicenseRepositoryKey] = new LicenseRepository(ambientServices.AppRuntime, encryptionService))) .GetLicenseData(appid))); return ambientServices; } /// <summary> /// Sets the log manager to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="logManager">The log manager.</param> /// <param name="replaceDefault">Optional. True to replace the <see cref="LoggingHelper.DefaultLogManager"/>.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithLogManager(this IAmbientServices ambientServices, ILogManager logManager, bool replaceDefault = true) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(logManager, nameof(logManager)); if (replaceDefault) { LoggingHelper.DefaultLogManager = logManager; } ambientServices.Register<ILogManager>(b => b.WithInstance(logManager).ExternallyOwned(false)); return ambientServices; } /// <summary> /// Sets the application runtime to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="appRuntime">The application runtime.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithAppRuntime(this IAmbientServices ambientServices, IAppRuntime appRuntime) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(appRuntime, nameof(appRuntime)); var existingAppRuntime = ambientServices.AppRuntime; if (existingAppRuntime != null && existingAppRuntime != appRuntime) { ServiceHelper.Finalize(existingAppRuntime); } if (existingAppRuntime != appRuntime) { ServiceHelper.Initialize(appRuntime); ambientServices.Register(appRuntime); } return ambientServices; } /// <summary> /// Sets the composition container to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="compositionContainer">The composition container.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithCompositionContainer(this IAmbientServices ambientServices, ICompositionContext compositionContainer) { Requires.NotNull(ambientServices, nameof(ambientServices)); Requires.NotNull(compositionContainer, nameof(compositionContainer)); ambientServices.Register(compositionContainer); return ambientServices; } /// <summary> /// Sets the composition container to the ambient services. /// </summary> /// <typeparam name="TContainerBuilder">Type of the composition container builder.</typeparam> /// <param name="ambientServices">The ambient services.</param> /// <param name="containerBuilderConfig">The container builder configuration.</param> /// <remarks>The container builder type must provide a constructor with one parameter of type <see cref="IContext" />.</remarks> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices WithCompositionContainer<TContainerBuilder>(this IAmbientServices ambientServices, Action<TContainerBuilder>? containerBuilderConfig = null) where TContainerBuilder : ICompositionContainerBuilder { Requires.NotNull(ambientServices, nameof(ambientServices)); var builderType = ambientServices.TypeRegistry.GetTypeInfo(typeof(TContainerBuilder)); var context = new CompositionRegistrationContext(ambientServices); var containerBuilder = (TContainerBuilder)builderType.CreateInstance(new[] { context }); containerBuilderConfig?.Invoke(containerBuilder); return ambientServices.WithCompositionContainer(containerBuilder.CreateContainer()); } /// <summary> /// Builds the composition container using Lite and adds it to the ambient services. /// </summary> /// <param name="ambientServices">The ambient services.</param> /// <param name="containerBuilderConfig">Optional. The container builder configuration.</param> /// <returns> /// This <paramref name="ambientServices"/>. /// </returns> public static IAmbientServices BuildWithLite(this IAmbientServices ambientServices, Action<LiteCompositionContainerBuilder>? containerBuilderConfig = null) { Requires.NotNull(ambientServices, nameof(ambientServices)); var containerBuilder = new LiteCompositionContainerBuilder(new CompositionRegistrationContext(ambientServices)); containerBuilderConfig?.Invoke(containerBuilder); var container = containerBuilder.CreateContainer(); return ambientServices.WithCompositionContainer(container); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.Rfc2251.RfcFilter.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Asn1; using LdapException = Novell.Directory.Ldap.LdapException; using LdapLocalException = Novell.Directory.Ldap.LdapLocalException; using LdapSearchRequest = Novell.Directory.Ldap.LdapSearchRequest; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap.Rfc2251 { /// <summary> Represents an Ldap Filter. /// /// This filter object can be created from a String or can be built up /// programatically by adding filter components one at a time. Existing filter /// components can be iterated though. /// /// Each filter component has an integer identifier defined in this class. /// The following are basic filter components: {@link #EQUALITY_MATCH}, /// {@link #GREATER_OR_EQUAL}, {@link #LESS_OR_EQUAL}, {@link #SUBSTRINGS}, /// {@link #PRESENT}, {@link #APPROX_MATCH}, {@link #EXTENSIBLE_MATCH}. /// /// More filters can be nested together into more complex filters with the /// following filter components: {@link #AND}, {@link #OR}, {@link #NOT} /// /// Substrings can have three components: /// <pre> /// Filter ::= CHOICE { /// and [0] SET OF Filter, /// or [1] SET OF Filter, /// not [2] Filter, /// equalityMatch [3] AttributeValueAssertion, /// substrings [4] SubstringFilter, /// greaterOrEqual [5] AttributeValueAssertion, /// lessOrEqual [6] AttributeValueAssertion, /// present [7] AttributeDescription, /// approxMatch [8] AttributeValueAssertion, /// extensibleMatch [9] MatchingRuleAssertion } /// </pre> /// </summary> public class RfcFilter:Asn1Choice { //************************************************************************* // Public variables for Filter //************************************************************************* /// <summary> Identifier for AND component.</summary> public const int AND = LdapSearchRequest.AND; /// <summary> Identifier for OR component.</summary> public const int OR = LdapSearchRequest.OR; /// <summary> Identifier for NOT component.</summary> public const int NOT = LdapSearchRequest.NOT; /// <summary> Identifier for EQUALITY_MATCH component.</summary> public const int EQUALITY_MATCH = LdapSearchRequest.EQUALITY_MATCH; /// <summary> Identifier for SUBSTRINGS component.</summary> public const int SUBSTRINGS = LdapSearchRequest.SUBSTRINGS; /// <summary> Identifier for GREATER_OR_EQUAL component.</summary> public const int GREATER_OR_EQUAL = LdapSearchRequest.GREATER_OR_EQUAL; /// <summary> Identifier for LESS_OR_EQUAL component.</summary> public const int LESS_OR_EQUAL = LdapSearchRequest.LESS_OR_EQUAL; /// <summary> Identifier for PRESENT component.</summary> public const int PRESENT = LdapSearchRequest.PRESENT; /// <summary> Identifier for APPROX_MATCH component.</summary> public const int APPROX_MATCH = LdapSearchRequest.APPROX_MATCH; /// <summary> Identifier for EXTENSIBLE_MATCH component.</summary> public const int EXTENSIBLE_MATCH = LdapSearchRequest.EXTENSIBLE_MATCH; /// <summary> Identifier for INITIAL component.</summary> public const int INITIAL = LdapSearchRequest.INITIAL; /// <summary> Identifier for ANY component.</summary> public const int ANY = LdapSearchRequest.ANY; /// <summary> Identifier for FINAL component.</summary> public const int FINAL = LdapSearchRequest.FINAL; //************************************************************************* // Private variables for Filter //************************************************************************* private FilterTokenizer ft; private System.Collections.Stack filterStack; private bool finalFound; //************************************************************************* // Constructor for Filter //************************************************************************* /// <summary> Constructs a Filter object by parsing an RFC 2254 Search Filter String.</summary> public RfcFilter(System.String filter):base(null) { ChoiceValue = parse(filter); return ; } /// <summary> Constructs a Filter object that will be built up piece by piece. </summary> public RfcFilter():base(null) { filterStack = new System.Collections.Stack(); //The choice value must be set later: setChoiceValue(rootFilterTag) return ; } //************************************************************************* // Helper methods for RFC 2254 Search Filter parsing. //************************************************************************* /// <summary> Parses an RFC 2251 filter string into an ASN.1 Ldap Filter object.</summary> private Asn1Tagged parse(System.String filterExpr) { if ((System.Object) filterExpr == null || filterExpr.Equals("")) { filterExpr = new System.Text.StringBuilder("(objectclass=*)").ToString(); } int idx; if ((idx = filterExpr.IndexOf((System.Char) '\\')) != - 1) { System.Text.StringBuilder sb = new System.Text.StringBuilder(filterExpr); int i = idx; while (i < (sb.Length - 1)) { char c = sb[i++]; if (c == '\\') { // found '\' (backslash) // If V2 escape, turn to a V3 escape c = sb[i]; if (c == '*' || c == '(' || c == ')' || c == '\\') { // Ldap v2 filter, convert them into hex chars sb.Remove(i, i + 1 - i); sb.Insert(i, System.Convert.ToString((int) c, 16)); i += 2; } } } filterExpr = sb.ToString(); } // missing opening and closing parentheses, must be V2, add parentheses if ((filterExpr[0] != '(') && (filterExpr[filterExpr.Length - 1] != ')')) { filterExpr = "(" + filterExpr + ")"; } char ch = filterExpr[0]; int len = filterExpr.Length; // missing opening parenthesis ? if (ch != '(') { throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR); } // missing closing parenthesis ? if (filterExpr[len - 1] != ')') { throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR); } // unmatched parentheses ? int parenCount = 0; for (int i = 0; i < len; i++) { if (filterExpr[i] == '(') { parenCount++; } if (filterExpr[i] == ')') { parenCount--; } } if (parenCount > 0) { throw new LdapLocalException(ExceptionMessages.MISSING_RIGHT_PAREN, LdapException.FILTER_ERROR); } if (parenCount < 0) { throw new LdapLocalException(ExceptionMessages.MISSING_LEFT_PAREN, LdapException.FILTER_ERROR); } ft = new FilterTokenizer(this, filterExpr); return parseFilter(); } /// <summary> Parses an RFC 2254 filter</summary> private Asn1Tagged parseFilter() { ft.getLeftParen(); Asn1Tagged filter = parseFilterComp(); ft.getRightParen(); return filter; } /// <summary> RFC 2254 filter helper method. Will Parse a filter component.</summary> private Asn1Tagged parseFilterComp() { Asn1Tagged tag = null; int filterComp = ft.OpOrAttr; switch (filterComp) { case AND: case OR: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilterList(), false); break; case NOT: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterComp), parseFilter(), true); break; default: int filterType = ft.FilterType; System.String value_Renamed = ft.Value; switch (filterType) { case GREATER_OR_EQUAL: case LESS_OR_EQUAL: case APPROX_MATCH: tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, filterType), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false); break; case EQUALITY_MATCH: if (value_Renamed.Equals("*")) { // present tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(ft.Attr), false); } else if (value_Renamed.IndexOf((System.Char) '*') != - 1) { // substrings parse: // [initial], *any*, [final] into an Asn1SequenceOf SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*", true); // SupportClass.Tokenizer sub = new SupportClass.Tokenizer(value_Renamed, "*");//, true); Asn1SequenceOf seq = new Asn1SequenceOf(5); int tokCnt = sub.Count; int cnt = 0; System.String lastTok = new System.Text.StringBuilder("").ToString(); while (sub.HasMoreTokens()) { System.String subTok = sub.NextToken(); cnt++; if (subTok.Equals("*")) { // if previous token was '*', and since the current // token is a '*', we need to insert 'any' if (lastTok.Equals(subTok)) { // '**' seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString("")), false)); } } else { // value (RfcLdapString) if (cnt == 1) { // initial seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, INITIAL), new RfcLdapString(unescapeString(subTok)), false)); } else if (cnt < tokCnt) { // any seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, ANY), new RfcLdapString(unescapeString(subTok)), false)); } else { // final seq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, FINAL), new RfcLdapString(unescapeString(subTok)), false)); } } lastTok = subTok; } tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(ft.Attr), seq), false); } else { // simple tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EQUALITY_MATCH), new RfcAttributeValueAssertion(new RfcAttributeDescription(ft.Attr), new RfcAssertionValue(unescapeString(value_Renamed))), false); } break; case EXTENSIBLE_MATCH: System.String type = null, matchingRule = null; bool dnAttributes = false; // SupportClass.Tokenizer st = new StringTokenizer(ft.Attr, ":", true); SupportClass.Tokenizer st = new SupportClass.Tokenizer(ft.Attr, ":");//, true); bool first = true; while (st.HasMoreTokens()) { System.String s = st.NextToken().Trim(); if (first && !s.Equals(":")) { type = s; } // dn must be lower case to be considered dn of the Entry. else if (s.Equals("dn")) { dnAttributes = true; } else if (!s.Equals(":")) { matchingRule = s; } first = false; } tag = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((System.Object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((System.Object) type == null)?null:new RfcAttributeDescription(type), new RfcAssertionValue(unescapeString(value_Renamed)), (dnAttributes == false)?null:new Asn1Boolean(true)), false); break; } break; } return tag; } /// <summary> Must have 1 or more Filters</summary> private Asn1SetOf parseFilterList() { Asn1SetOf set_Renamed = new Asn1SetOf(); set_Renamed.add(parseFilter()); // must have at least 1 filter while (ft.peekChar() == '(') { // check for more filters set_Renamed.add(parseFilter()); } return set_Renamed; } /// <summary> Convert hex character to an integer. Return -1 if char is something /// other than a hex char. /// </summary> internal static int hex2int(char c) { return (c >= '0' && c <= '9')?c - '0':(c >= 'A' && c <= 'F')?c - 'A' + 10:(c >= 'a' && c <= 'f')?c - 'a' + 10:- 1; } /// <summary> Replace escaped hex digits with the equivalent binary representation. /// Assume either V2 or V3 escape mechanisms: /// V2: \*, \(, \), \\. /// V3: \2A, \28, \29, \5C, \00. /// /// </summary> /// <param name="string"> A part of the input filter string to be converted. /// /// </param> /// <returns> octet-string encoding of the specified string. /// </returns> private sbyte[] unescapeString(System.String string_Renamed) { // give octets enough space to grow sbyte[] octets = new sbyte[string_Renamed.Length * 3]; // index for string and octets int iString, iOctets; // escape==true means we are in an escape sequence. bool escape = false; // escStart==true means we are reading the first character of an escape. bool escStart = false; int ival, length = string_Renamed.Length; sbyte[] utf8Bytes; char ch; // Character we are adding to the octet string char[] ca = new char[1]; // used while converting multibyte UTF-8 char char temp = (char) (0); // holds the value of the escaped sequence // loop through each character of the string and copy them into octets // converting escaped sequences when needed for (iString = 0, iOctets = 0; iString < length; iString++) { ch = string_Renamed[iString]; if (escape) { if ((ival = hex2int(ch)) < 0) { // Invalid escape value(not a hex character) throw new LdapLocalException(ExceptionMessages.INVALID_ESCAPE, new System.Object[]{ch}, LdapException.FILTER_ERROR); } else { // V3 escaped: \\** if (escStart) { temp = (char) (ival << 4); // high bits of escaped char escStart = false; } else { temp |= (char) (ival); // all bits of escaped char octets[iOctets++] = (sbyte) temp; escStart = escape = false; } } } else if (ch == '\\') { escStart = escape = true; } else { try { // place the character into octets. if ((ch >= 0x01 && ch <= 0x27) || (ch >= 0x2B && ch <= 0x5B) || (ch >= 0x5D)) { // found valid char if (ch <= 0x7f) { // char = %x01-27 / %x2b-5b / %x5d-7f octets[iOctets++] = (sbyte) ch; } else { // char > 0x7f, could be encoded in 2 or 3 bytes ca[0] = ch; System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(new System.String(ca)); utf8Bytes=SupportClass.ToSByteArray(ibytes); // utf8Bytes = new System.String(ca).getBytes("UTF-8"); // copy utf8 encoded character into octets Array.Copy((System.Array) (utf8Bytes), 0, (System.Array) octets, iOctets, utf8Bytes.Length); iOctets = iOctets + utf8Bytes.Length; } escape = false; } else { // found invalid character System.String escString = ""; ca[0] = ch; System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(new System.String(ca)); utf8Bytes=SupportClass.ToSByteArray(ibytes); // utf8Bytes = new System.String(ca).getBytes("UTF-8"); for (int i = 0; i < utf8Bytes.Length; i++) { sbyte u = utf8Bytes[i]; if ((u >= 0) && (u < 0x10)) { escString = escString + "\\0" + System.Convert.ToString(u & 0xff, 16); } else { escString = escString + "\\" + System.Convert.ToString(u & 0xff, 16); } } throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_FILTER, new System.Object[]{ch, escString}, LdapException.FILTER_ERROR); } } catch (System.IO.IOException ue) { throw new System.SystemException("UTF-8 String encoding not supported by JVM"); } } } // Verify that any escape sequence completed if (escStart || escape) { throw new LdapLocalException(ExceptionMessages.SHORT_ESCAPE, LdapException.FILTER_ERROR); } sbyte[] toReturn = new sbyte[iOctets]; // Array.Copy((System.Array)SupportClass.ToByteArray(octets), 0, (System.Array)SupportClass.ToByteArray(toReturn), 0, iOctets); Array.Copy((System.Array)octets, 0, (System.Array)toReturn, 0, iOctets); octets = null; return toReturn; } /* ********************************************************************** * The following methods aid in building filters sequentially, * and is used by DSMLHandler: ***********************************************************************/ /// <summary> Called by sequential filter building methods to add to a filter /// component. /// /// Verifies that the specified Asn1Object can be added, then adds the /// object to the filter. /// </summary> /// <param name="current"> Filter component to be added to the filter /// @throws LdapLocalException Occurs when an invalid component is added, or /// when the component is out of sequence. /// </param> private void addObject(Asn1Object current) { if (filterStack == null) { filterStack = new System.Collections.Stack(); } if (choiceValue() == null) { //ChoiceValue is the root Asn1 node ChoiceValue = current; } else { Asn1Tagged topOfStack = (Asn1Tagged) filterStack.Peek(); Asn1Object value_Renamed = topOfStack.taggedValue(); if (value_Renamed == null) { topOfStack.TaggedValue = current; filterStack.Push(current); // filterStack.Add(current); } else if (value_Renamed is Asn1SetOf) { ((Asn1SetOf) value_Renamed).add(current); //don't add this to the stack: } else if (value_Renamed is Asn1Set) { ((Asn1Set) value_Renamed).add(current); //don't add this to the stack: } else if (value_Renamed.getIdentifier().Tag == LdapSearchRequest.NOT) { throw new LdapLocalException("Attemp to create more than one 'not' sub-filter", LdapException.FILTER_ERROR); } } int type = current.getIdentifier().Tag; if (type == AND || type == OR || type == NOT) { // filterStack.Add(current); filterStack.Push(current); } return ; } /// <summary> Creates and addes a substrings filter component. /// /// startSubstrings must be immediatly followed by at least one /// {@link #addSubstring} method and one {@link #endSubstrings} method /// @throws Novell.Directory.Ldap.LdapLocalException /// Occurs when this component is created out of sequence. /// </summary> public virtual void startSubstrings(System.String attrName) { finalFound = false; Asn1SequenceOf seq = new Asn1SequenceOf(5); Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, SUBSTRINGS), new RfcSubstringFilter(new RfcAttributeDescription(attrName), seq), false); addObject(current); SupportClass.StackPush(filterStack, seq); return ; } /// <summary> Adds a Substring component of initial, any or final substring matching. /// /// This method can be invoked only if startSubString was the last filter- /// building method called. A substring is not required to have an 'INITIAL' /// substring. However, when a filter contains an 'INITIAL' substring only /// one can be added, and it must be the first substring added. Any number of /// 'ANY' substrings can be added. A substring is not required to have a /// 'FINAL' substrings either. However, when a filter does contain a 'FINAL' /// substring only one can be added, and it must be the last substring added. /// /// </summary> /// <param name="type">Substring type: INITIAL | ANY | FINAL] /// </param> /// <param name="value">Value to use for matching /// @throws LdapLocalException Occurs if this method is called out of /// sequence or the type added is out of sequence. /// </param> [CLSCompliantAttribute(false)] public virtual void addSubstring(int type, sbyte[] value_Renamed) { try { Asn1SequenceOf substringSeq = (Asn1SequenceOf) filterStack.Peek(); if (type != INITIAL && type != ANY && type != FINAL) { throw new LdapLocalException("Attempt to add an invalid " + "substring type", LdapException.FILTER_ERROR); } if (type == INITIAL && substringSeq.size() != 0) { throw new LdapLocalException("Attempt to add an initial " + "substring match after the first substring", LdapException.FILTER_ERROR); } if (finalFound) { throw new LdapLocalException("Attempt to add a substring " + "match after a final substring match", LdapException.FILTER_ERROR); } if (type == FINAL) { finalFound = true; } substringSeq.add(new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, type), new RfcLdapString(value_Renamed), false)); } catch (System.InvalidCastException e) { throw new LdapLocalException("A call to addSubstring occured " + "without calling startSubstring", LdapException.FILTER_ERROR); } return ; } /// <summary> Completes a SubString filter component. /// /// @throws LdapLocalException Occurs when this is called out of sequence, /// or the substrings filter is empty. /// </summary> public virtual void endSubstrings() { try { finalFound = false; Asn1SequenceOf substringSeq = (Asn1SequenceOf) filterStack.Peek(); if (substringSeq.size() == 0) { throw new LdapLocalException("Empty substring filter", LdapException.FILTER_ERROR); } } catch (System.InvalidCastException e) { throw new LdapLocalException("Missmatched ending of substrings", LdapException.FILTER_ERROR); } filterStack.Pop(); return ; } /// <summary> Creates and adds an AttributeValueAssertion to the filter. /// /// </summary> /// <param name="rfcType">Filter type: EQUALITY_MATCH | GREATER_OR_EQUAL /// | LESS_OR_EQUAL | APPROX_MATCH ] /// </param> /// <param name="attrName">Name of the attribute to be asserted /// </param> /// <param name="value">Value of the attribute to be asserted /// @throws LdapLocalException /// Occurs when the filter type is not a valid attribute assertion. /// </param> [CLSCompliantAttribute(false)] public virtual void addAttributeValueAssertion(int rfcType, System.String attrName, sbyte[] value_Renamed) { if (filterStack != null && !(filterStack.Count == 0) && filterStack.Peek() is Asn1SequenceOf) { //If a sequenceof is on the stack then substring is left on the stack throw new LdapLocalException("Cannot insert an attribute assertion in a substring", LdapException.FILTER_ERROR); } if ((rfcType != EQUALITY_MATCH) && (rfcType != GREATER_OR_EQUAL) && (rfcType != LESS_OR_EQUAL) && (rfcType != APPROX_MATCH)) { throw new LdapLocalException("Invalid filter type for AttributeValueAssertion", LdapException.FILTER_ERROR); } Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new RfcAttributeValueAssertion(new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed)), false); addObject(current); return ; } /// <summary> Creates and adds a present matching to the filter. /// /// </summary> /// <param name="attrName">Name of the attribute to check for presence. /// @throws LdapLocalException /// Occurs if addPresent is called out of sequence. /// </param> public virtual void addPresent(System.String attrName) { Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, false, PRESENT), new RfcAttributeDescription(attrName), false); addObject(current); return ; } /// <summary> Adds an extensible match to the filter. /// /// </summary> /// <param name="">matchingRule /// OID or name of the matching rule to use for comparison /// </param> /// <param name="attrName"> Name of the attribute to match. /// </param> /// <param name="value"> Value of the attribute to match against. /// </param> /// <param name="useDNMatching">Indicates whether DN matching should be used. /// @throws LdapLocalException /// Occurs when addExtensibleMatch is called out of sequence. /// </param> [CLSCompliantAttribute(false)] public virtual void addExtensibleMatch(System.String matchingRule, System.String attrName, sbyte[] value_Renamed, bool useDNMatching) { Asn1Object current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, EXTENSIBLE_MATCH), new RfcMatchingRuleAssertion(((System.Object) matchingRule == null)?null:new RfcMatchingRuleId(matchingRule), ((System.Object) attrName == null)?null:new RfcAttributeDescription(attrName), new RfcAssertionValue(value_Renamed), (useDNMatching == false)?null:new Asn1Boolean(true)), false); addObject(current); return ; } /// <summary> Creates and adds the Asn1Tagged value for a nestedFilter: AND, OR, or /// NOT. /// /// Note that a Not nested filter can only have one filter, where AND /// and OR do not /// /// </summary> /// <param name="rfcType">Filter type: /// [AND | OR | NOT] /// @throws Novell.Directory.Ldap.LdapLocalException /// </param> public virtual void startNestedFilter(int rfcType) { Asn1Object current; if (rfcType == AND || rfcType == OR) { current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), new Asn1SetOf(), false); } else if (rfcType == NOT) { current = new Asn1Tagged(new Asn1Identifier(Asn1Identifier.CONTEXT, true, rfcType), null, true); } else { throw new LdapLocalException("Attempt to create a nested filter other than AND, OR or NOT", LdapException.FILTER_ERROR); } addObject(current); return ; } /// <summary> Completes a nested filter and checks for the valid filter type.</summary> /// <param name="rfcType"> Type of filter to complete. /// @throws Novell.Directory.Ldap.LdapLocalException Occurs when the specified /// type differs from the current filter component. /// </param> public virtual void endNestedFilter(int rfcType) { if (rfcType == NOT) { //if this is a Not than Not should be the second thing on the stack filterStack.Pop(); } int topOfStackType = ((Asn1Object) filterStack.Peek()).getIdentifier().Tag; if (topOfStackType != rfcType) { throw new LdapLocalException("Missmatched ending of nested filter", LdapException.FILTER_ERROR); } filterStack.Pop(); return ; } /// <summary> Creates an iterator over the preparsed segments of a filter. /// /// The first object returned by an iterator is an integer indicating the /// type of filter components. Subseqence values are returned. If a /// component is of type 'AND' or 'OR' or 'NOT' then the value /// returned is another iterator. This iterator is used by toString. /// /// </summary> /// <returns> Iterator over filter segments /// </returns> public virtual System.Collections.IEnumerator getFilterIterator() { return new FilterIterator(this, (Asn1Tagged) this.choiceValue()); } /// <summary> Creates and returns a String representation of this filter.</summary> public virtual System.String filterToString() { System.Text.StringBuilder filter = new System.Text.StringBuilder(); stringFilter(this.getFilterIterator(), filter); return filter.ToString(); } /// <summary> Uses a filterIterator to create a string representation of a filter. /// /// </summary> /// <param name="itr">Iterator of filter components /// </param> /// <param name="filter">Buffer to place a string representation of the filter /// </param> /// <seealso cref="FilterIterator"> /// </seealso> private static void stringFilter(System.Collections.IEnumerator itr, System.Text.StringBuilder filter) { int op = - 1; filter.Append('('); while (itr.MoveNext()) { System.Object filterpart = itr.Current; if (filterpart is System.Int32) { op = ((System.Int32) filterpart); switch (op) { case AND: filter.Append('&'); break; case OR: filter.Append('|'); break; case NOT: filter.Append('!'); break; case EQUALITY_MATCH: { filter.Append((System.String) itr.Current); filter.Append('='); sbyte[] value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case GREATER_OR_EQUAL: { filter.Append((System.String) itr.Current); filter.Append(">="); sbyte[] value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case LESS_OR_EQUAL: { filter.Append((System.String) itr.Current); filter.Append("<="); sbyte[] value_Renamed = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed)); break; } case PRESENT: filter.Append((System.String) itr.Current); filter.Append("=*"); break; case APPROX_MATCH: filter.Append((System.String) itr.Current); filter.Append("~="); sbyte[] value_Renamed2 = (sbyte[]) itr.Current; filter.Append(byteString(value_Renamed2)); break; case EXTENSIBLE_MATCH: System.String oid = (System.String) itr.Current; filter.Append((System.String) itr.Current); filter.Append(':'); filter.Append(oid); filter.Append(":="); filter.Append((System.String) itr.Current); break; case SUBSTRINGS: { filter.Append((System.String) itr.Current); filter.Append('='); bool noStarLast = false; while (itr.MoveNext()) { op = ((System.Int32) itr.Current); switch (op) { case INITIAL: filter.Append((System.String) itr.Current); filter.Append('*'); noStarLast = false; break; case ANY: if (noStarLast) filter.Append('*'); filter.Append((System.String) itr.Current); filter.Append('*'); noStarLast = false; break; case FINAL: if (noStarLast) filter.Append('*'); filter.Append((System.String) itr.Current); break; } } break; } } } else if (filterpart is System.Collections.IEnumerator) { stringFilter((System.Collections.IEnumerator) filterpart, filter); } } filter.Append(')'); } /// <summary> Convert a UTF8 encoded string, or binary data, into a String encoded for /// a string filter. /// </summary> private static System.String byteString(sbyte[] value_Renamed) { System.String toReturn = null; if (Novell.Directory.Ldap.Utilclass.Base64.isValidUTF8(value_Renamed, true)) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray(value_Renamed)); toReturn = new String(dchar); // toReturn = new String(value_Renamed, "UTF-8"); } catch (System.IO.IOException e) { throw new System.SystemException("Default JVM does not support UTF-8 encoding" + e); } } else { System.Text.StringBuilder binary = new System.Text.StringBuilder(); for (int i = 0; i < value_Renamed.Length; i++) { //TODO repair binary output //Every octet needs to be escaped if (value_Renamed[i] >= 0) { //one character hex string binary.Append("\\0"); binary.Append(System.Convert.ToString(value_Renamed[i], 16)); } else { //negative (eight character) hex string binary.Append("\\" + System.Convert.ToString(value_Renamed[i], 16).Substring(6)); } } toReturn = binary.ToString(); } return toReturn; } /// <summary> This inner class wrappers the Search Filter with an iterator. /// This iterator will give access to all the individual components /// preparsed. The first call to next will return an Integer identifying /// the type of filter component. Then the component values will be returned /// AND, NOT, and OR components values will be returned as Iterators. /// </summary> private class FilterIterator : System.Collections.IEnumerator { public void Reset(){} private void InitBlock(RfcFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private RfcFilter enclosingInstance; /// <summary> Returns filter identifiers and components of a filter. /// /// The first object returned is an Integer identifying /// its type. /// </summary> public virtual System.Object Current { get { System.Object toReturn = null; if (!tagReturned) { tagReturned = true; toReturn = root.getIdentifier().Tag; } else { Asn1Object asn1 = root.taggedValue(); if (asn1 is RfcLdapString) { //one value to iterate hasMore = false; toReturn = ((RfcLdapString) asn1).stringValue(); } else if (asn1 is RfcSubstringFilter) { RfcSubstringFilter sub = (RfcSubstringFilter) asn1; if (index == - 1) { //return attribute name index = 0; RfcAttributeDescription attr = (RfcAttributeDescription) sub.get_Renamed(0); toReturn = attr.stringValue(); } else if (index % 2 == 0) { //return substring identifier Asn1SequenceOf substrs = (Asn1SequenceOf) sub.get_Renamed(1); toReturn = ((Asn1Tagged) substrs.get_Renamed(index / 2)).getIdentifier().Tag; index++; } else { //return substring value Asn1SequenceOf substrs = (Asn1SequenceOf) sub.get_Renamed(1); Asn1Tagged tag = (Asn1Tagged) substrs.get_Renamed(index / 2); RfcLdapString value_Renamed = (RfcLdapString) tag.taggedValue(); toReturn = value_Renamed.stringValue(); index++; } if (index / 2 >= ((Asn1SequenceOf) sub.get_Renamed(1)).size()) { hasMore = false; } } else if (asn1 is RfcAttributeValueAssertion) { // components: =,>=,<=,~= RfcAttributeValueAssertion assertion = (RfcAttributeValueAssertion) asn1; if (index == - 1) { toReturn = assertion.AttributeDescription; index = 1; } else if (index == 1) { toReturn = assertion.AssertionValue; index = 2; hasMore = false; } } else if (asn1 is RfcMatchingRuleAssertion) { //Extensible match RfcMatchingRuleAssertion exMatch = (RfcMatchingRuleAssertion) asn1; if (index == - 1) { index = 0; } toReturn = ((Asn1OctetString) ((Asn1Tagged) exMatch.get_Renamed(index++)).taggedValue()).stringValue(); if (index > 2) { hasMore = false; } } else if (asn1 is Asn1SetOf) { //AND and OR nested components Asn1SetOf set_Renamed = (Asn1SetOf) asn1; if (index == - 1) { index = 0; } toReturn = new FilterIterator(enclosingInstance,(Asn1Tagged) set_Renamed.get_Renamed(index++)); if (index >= set_Renamed.size()) { this.hasMore = false; } } else if (asn1 is Asn1Tagged) { //NOT nested component. toReturn = new FilterIterator(enclosingInstance,(Asn1Tagged) asn1); this.hasMore = false; } } return toReturn; } } public RfcFilter Enclosing_Instance { get { return enclosingInstance; } } internal Asn1Tagged root; /// <summary>indicates if the identifier for a component has been returned yet </summary> internal bool tagReturned = false; /// <summary>indexes the several parts a component may have </summary> internal int index = - 1; private bool hasMore = true; public FilterIterator(RfcFilter enclosingInstance, Asn1Tagged root) { InitBlock(enclosingInstance); this.root = root; } public virtual bool MoveNext() { return hasMore; } public void remove() { throw new System.NotSupportedException("Remove is not supported on a filter iterator"); } } /// <summary> This inner class will tokenize the components of an RFC 2254 search filter.</summary> internal class FilterTokenizer { private void InitBlock(RfcFilter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private RfcFilter enclosingInstance; /// <summary> Reads either an operator, or an attribute, whichever is /// next in the filter string. /// /// /// If the next component is an attribute, it is read and stored in the /// attr field of this class which may be retrieved with getAttr() /// and a -1 is returned. Otherwise, the int value of the operator read is /// returned. /// </summary> virtual public int OpOrAttr { get { int index; if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } int ret; int testChar = filter[offset]; if (testChar == '&') { offset++; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.AND; } else if (testChar == '|') { offset++; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.OR; } else if (testChar == '!') { offset++; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.NOT; } else { if (filter.Substring(offset).StartsWith(":=") == true) { throw new LdapLocalException(ExceptionMessages.NO_MATCHING_RULE, LdapException.FILTER_ERROR); } if (filter.Substring(offset).StartsWith("::=") == true || filter.Substring(offset).StartsWith(":::=") == true) { throw new LdapLocalException(ExceptionMessages.NO_DN_NOR_MATCHING_RULE, LdapException.FILTER_ERROR); } // get first component of 'item' (attr or :dn or :matchingrule) System.String delims = "=~<>()"; System.Text.StringBuilder sb = new System.Text.StringBuilder(); while (delims.IndexOf((System.Char) filter[offset]) == - 1 && filter.Substring(offset).StartsWith(":=") == false) { sb.Append(filter[offset++]); } attr = sb.ToString().Trim(); // is there an attribute name specified in the filter ? if (attr.Length == 0 || attr[0] == ';') { throw new LdapLocalException(ExceptionMessages.NO_ATTRIBUTE_NAME, LdapException.FILTER_ERROR); } for (index = 0; index < attr.Length; index++) { char atIndex = attr[index]; if (!(System.Char.IsLetterOrDigit(atIndex) || atIndex == '-' || atIndex == '.' || atIndex == ';' || atIndex == ':')) { if (atIndex == '\\') { throw new LdapLocalException(ExceptionMessages.INVALID_ESC_IN_DESCR, LdapException.FILTER_ERROR); } else { throw new LdapLocalException(ExceptionMessages.INVALID_CHAR_IN_DESCR, new System.Object[]{atIndex}, LdapException.FILTER_ERROR); } } } // is there an option specified in the filter ? index = attr.IndexOf((System.Char) ';'); if (index != - 1 && index == attr.Length - 1) { throw new LdapLocalException(ExceptionMessages.NO_OPTION, LdapException.FILTER_ERROR); } ret = - 1; } return ret; } } /// <summary> Reads an RFC 2251 filter type from the filter string and returns its /// int value. /// </summary> virtual public int FilterType { get { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } int ret; if (filter.Substring(offset).StartsWith(">=")) { offset += 2; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.GREATER_OR_EQUAL; } else if (filter.Substring(offset).StartsWith("<=")) { offset += 2; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.LESS_OR_EQUAL; } else if (filter.Substring(offset).StartsWith("~=")) { offset += 2; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.APPROX_MATCH; } else if (filter.Substring(offset).StartsWith(":=")) { offset += 2; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.EXTENSIBLE_MATCH; } else if (filter[offset] == '=') { offset++; ret = Novell.Directory.Ldap.Rfc2251.RfcFilter.EQUALITY_MATCH; } else { //"Invalid comparison operator", throw new LdapLocalException(ExceptionMessages.INVALID_FILTER_COMPARISON, LdapException.FILTER_ERROR); } return ret; } } /// <summary> Reads a value from a filter string.</summary> virtual public System.String Value { get { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } int idx = filter.IndexOf((System.Char) ')', offset); if (idx == - 1) { idx = filterLength; } System.String ret = filter.Substring(offset, (idx) - (offset)); offset = idx; return ret; } } /// <summary> Returns the current attribute identifier.</summary> virtual public System.String Attr { get { return attr; } } public RfcFilter Enclosing_Instance { get { return enclosingInstance; } } //************************************************************************* // Private variables //************************************************************************* private System.String filter; // The filter string to parse private System.String attr; // Name of the attribute just parsed private int offset; // Offset pointer into the filter string private int filterLength; // Length of the filter string to parse //************************************************************************* // Constructor //************************************************************************* /// <summary> Constructs a FilterTokenizer for a filter.</summary> public FilterTokenizer(RfcFilter enclosingInstance, System.String filter) { InitBlock(enclosingInstance); this.filter = filter; this.offset = 0; this.filterLength = filter.Length; return ; } //************************************************************************* // Tokenizer methods //************************************************************************* /// <summary> Reads the current char and throws an Exception if it is not a left /// parenthesis. /// </summary> public void getLeftParen() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } if (filter[offset++] != '(') { //"Missing left paren", throw new LdapLocalException(ExceptionMessages.EXPECTING_LEFT_PAREN, new System.Object[]{filter[offset -= 1]}, LdapException.FILTER_ERROR); } return ; } /// <summary> Reads the current char and throws an Exception if it is not a right /// parenthesis. /// </summary> public void getRightParen() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } if (filter[offset++] != ')') { //"Missing right paren", throw new LdapLocalException(ExceptionMessages.EXPECTING_RIGHT_PAREN, new System.Object[]{filter[offset - 1]}, LdapException.FILTER_ERROR); } return ; } /// <summary> Return the current char without advancing the offset pointer. This is /// used by ParseFilterList when determining if there are any more /// Filters in the list. /// </summary> public char peekChar() { if (offset >= filterLength) { //"Unexpected end of filter", throw new LdapLocalException(ExceptionMessages.UNEXPECTED_END, LdapException.FILTER_ERROR); } return filter[offset]; } } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 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; using Astrid.Core; using Astrid.FarseerPhysics.Common; namespace Astrid.FarseerPhysics.Dynamics.Joints { // Linear constraint (point-to-line) // d = pB - pA = xB + rB - xA - rA // C = dot(ay, d) // Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) // = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) // J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] // Spring linear constraint // C = dot(ax, d) // Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) // J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] // Motor rotational constraint // Cdot = wB - wA // J = [0 0 -1 0 0 1] /// <summary> /// A wheel joint. This joint provides two degrees of freedom: translation /// along an axis fixed in bodyA and rotation in the plane. You can use a /// joint limit to restrict the range of motion and a joint motor to drive /// the rotation or to model rotational friction. /// This joint is designed for vehicle suspensions. /// </summary> public class WheelJoint : Joint { // Solver shared private Vector2 _localYAxis; private float _impulse; private float _motorImpulse; private float _springImpulse; private float _maxMotorTorque; private float _motorSpeed; private bool _enableMotor; // Solver temp private int _indexA; private int _indexB; private Vector2 _localCenterA; private Vector2 _localCenterB; private float _invMassA; private float _invMassB; private float _invIA; private float _invIB; private Vector2 _ax, _ay; private float _sAx, _sBx; private float _sAy, _sBy; private float _mass; private float _motorMass; private float _springMass; private float _bias; private float _gamma; private Vector2 _axis; internal WheelJoint() { JointType = JointType.Wheel; } /// <summary> /// Constructor for WheelJoint /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="anchor">The anchor point</param> /// <param name="axis">The axis</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public WheelJoint(Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Wheel; if (useWorldCoordinates) { LocalAnchorA = bodyA.GetLocalPoint(anchor); LocalAnchorB = bodyB.GetLocalPoint(anchor); } else { LocalAnchorA = bodyA.GetLocalPoint(bodyB.GetWorldPoint(anchor)); LocalAnchorB = anchor; } Axis = axis; //FPE only: We maintain the original value as it is supposed to. } /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 LocalAnchorA { get; set; } /// <summary> /// The local anchor point on BodyB /// </summary> public Vector2 LocalAnchorB { get; set; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } set { LocalAnchorA = BodyA.GetLocalPoint(value); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { LocalAnchorB = BodyB.GetLocalPoint(value); } } /// <summary> /// The axis at which the suspension moves. /// </summary> public Vector2 Axis { get { return _axis; } set { _axis = value; LocalXAxis = BodyA.GetLocalVector(_axis); _localYAxis = MathUtils.Cross(1.0f, LocalXAxis); } } /// <summary> /// The axis in local coordinates relative to BodyA /// </summary> public Vector2 LocalXAxis { get; private set; } /// <summary> /// The desired motor speed in radians per second. /// </summary> public float MotorSpeed { get { return _motorSpeed; } set { WakeBodies(); _motorSpeed = value; } } /// <summary> /// The maximum motor torque, usually in N-m. /// </summary> public float MaxMotorTorque { get { return _maxMotorTorque; } set { WakeBodies(); _maxMotorTorque = value; } } /// <summary> /// Suspension frequency, zero indicates no suspension /// </summary> public float Frequency { get; set; } /// <summary> /// Suspension damping ratio, one indicates critical damping /// </summary> public float DampingRatio { get; set; } /// <summary> /// Gets the translation along the axis /// </summary> public float JointTranslation { get { Body bA = BodyA; Body bB = BodyB; Vector2 pA = bA.GetWorldPoint(LocalAnchorA); Vector2 pB = bB.GetWorldPoint(LocalAnchorB); Vector2 d = pB - pA; Vector2 axis = bA.GetWorldVector(LocalXAxis); float translation = Vector2.Dot(d, axis); return translation; } } /// <summary> /// Gets the angular velocity of the joint /// </summary> public float JointSpeed { get { float wA = BodyA.AngularVelocity; float wB = BodyB.AngularVelocity; return wB - wA; } } /// <summary> /// Enable/disable the joint motor. /// </summary> public bool MotorEnabled { get { return _enableMotor; } set { WakeBodies(); _enableMotor = value; } } /// <summary> /// Gets the torque of the motor /// </summary> /// <param name="invDt">inverse delta time</param> public float GetMotorTorque(float invDt) { return invDt * _motorImpulse; } public override Vector2 GetReactionForce(float invDt) { return invDt * (_impulse * _ay + _springImpulse * _ax); } public override float GetReactionTorque(float invDt) { return invDt * _motorImpulse; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; Rot qA = new Rot(aA), qB = new Rot(aB); // Compute the effective masses. Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); Vector2 d1 = cB + rB - cA - rA; // Point to line constraint { _ay = MathUtils.Mul(qA, _localYAxis); _sAy = MathUtils.Cross(d1 + rA, _ay); _sBy = MathUtils.Cross(rB, _ay); _mass = mA + mB + iA * _sAy * _sAy + iB * _sBy * _sBy; if (_mass > 0.0f) { _mass = 1.0f / _mass; } } // Spring constraint _springMass = 0.0f; _bias = 0.0f; _gamma = 0.0f; if (Frequency > 0.0f) { _ax = MathUtils.Mul(qA, LocalXAxis); _sAx = MathUtils.Cross(d1 + rA, _ax); _sBx = MathUtils.Cross(rB, _ax); float invMass = mA + mB + iA * _sAx * _sAx + iB * _sBx * _sBx; if (invMass > 0.0f) { _springMass = 1.0f / invMass; float C = Vector2.Dot(d1, _ax); // Frequency float omega = 2.0f * Settings.Pi * Frequency; // Damping coefficient float d = 2.0f * _springMass * DampingRatio * omega; // Spring stiffness float k = _springMass * omega * omega; // magic formulas float h = data.step.dt; _gamma = h * (d + h * k); if (_gamma > 0.0f) { _gamma = 1.0f / _gamma; } _bias = C * h * k * _gamma; _springMass = invMass + _gamma; if (_springMass > 0.0f) { _springMass = 1.0f / _springMass; } } } else { _springImpulse = 0.0f; } // Rotational motor if (_enableMotor) { _motorMass = iA + iB; if (_motorMass > 0.0f) { _motorMass = 1.0f / _motorMass; } } else { _motorMass = 0.0f; _motorImpulse = 0.0f; } if (Settings.EnableWarmstarting) { // Account for variable time step. _impulse *= data.step.dtRatio; _springImpulse *= data.step.dtRatio; _motorImpulse *= data.step.dtRatio; Vector2 P = _impulse * _ay + _springImpulse * _ax; float LA = _impulse * _sAy + _springImpulse * _sAx + _motorImpulse; float LB = _impulse * _sBy + _springImpulse * _sBx + _motorImpulse; vA -= _invMassA * P; wA -= _invIA * LA; vB += _invMassB * P; wB += _invIB * LB; } else { _impulse = 0.0f; _springImpulse = 0.0f; _motorImpulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; // Solve spring constraint { float Cdot = Vector2.Dot(_ax, vB - vA) + _sBx * wB - _sAx * wA; float impulse = -_springMass * (Cdot + _bias + _gamma * _springImpulse); _springImpulse += impulse; Vector2 P = impulse * _ax; float LA = impulse * _sAx; float LB = impulse * _sBx; vA -= mA * P; wA -= iA * LA; vB += mB * P; wB += iB * LB; } // Solve rotational motor constraint { float Cdot = wB - wA - _motorSpeed; float impulse = -_motorMass * Cdot; float oldImpulse = _motorImpulse; float maxImpulse = data.step.dt * _maxMotorTorque; _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve point to line constraint { float Cdot = Vector2.Dot(_ay, vB - vA) + _sBy * wB - _sAy * wA; float impulse = -_mass * Cdot; _impulse += impulse; Vector2 P = impulse * _ay; float LA = impulse * _sAy; float LB = impulse * _sBy; vA -= mA * P; wA -= iA * LA; vB += mB * P; wB += iB * LB; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Rot qA = new Rot(aA), qB = new Rot(aB); Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); Vector2 d = (cB - cA) + rB - rA; Vector2 ay = MathUtils.Mul(qA, _localYAxis); float sAy = MathUtils.Cross(d + rA, ay); float sBy = MathUtils.Cross(rB, ay); float C = Vector2.Dot(d, ay); float k = _invMassA + _invMassB + _invIA * _sAy * _sAy + _invIB * _sBy * _sBy; float impulse; if (k != 0.0f) { impulse = -C / k; } else { impulse = 0.0f; } Vector2 P = impulse * ay; float LA = impulse * sAy; float LB = impulse * sBy; cA -= _invMassA * P; aA -= _invIA * LA; cB += _invMassB * P; aB += _invIB * LB; data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return Math.Abs(C) <= Settings.LinearSlop; } } }
using System.Linq; using Newtonsoft.Json.Linq; using Skybrud.Essentials.Json.Extensions; using Skybrud.Essentials.Time; using Skybrud.Social.Facebook.Models.Albums; using Skybrud.Social.Facebook.Models.Common; using Skybrud.Social.Facebook.Models.Events; using Skybrud.Social.Facebook.Models.Places; namespace Skybrud.Social.Facebook.Models.Photos { /// <summary> /// Class representing a Facebook photo. /// </summary> /// <see> /// <cref>https://developers.facebook.com/docs/graph-api/reference/v2.8/photo#Reading</cref> /// </see> public class FacebookPhoto : FacebookObject { #region Properties /// <summary> /// Gets the ID of the photo. /// </summary> public string Id { get; } /// <summary> /// Gets a reference to the album this photo is in. /// </summary> public FacebookAlbum Album { get; } /// <summary> /// Gets whether the <see cref="Album"/> property was included in the response. /// </summary> public bool HasAlbum => Album != null; /// <summary> /// Gets a user-specified time for when this object was created. /// </summary> public EssentialsTime BackdatedTime { get; } /// <summary> /// Gets whether the <see cref="Width"/> property was included in the response. /// </summary> public bool HasBackdatedTime => BackdatedTime != null; /// <summary> /// Gets how accurate the backdated time is. /// </summary> public string BackdatedTimeGranularity { get; } /// <summary> /// Gets whether the <see cref="BackdatedTimeGranularity"/> property was included in the response. /// </summary> public bool HasBackdatedTimeGranularity => string.IsNullOrWhiteSpace(BackdatedTimeGranularity) == false; /// <summary> /// Gets whether the viewer can backdate the photo. /// </summary> public bool CanBackdate { get; } /// <summary> /// Gets whether the <see cref="CanTag"/> property was included in the response. /// </summary> public bool HasCanBackdate => JObject.HasValue("can_backdate"); /// <summary> /// Gets whether the viewer can delete the photo. /// </summary> public bool CanDelete { get; } /// <summary> /// Gets whether the <see cref="CanDelete"/> property was included in the response. /// </summary> public bool HasCanDelete => JObject.HasValue("can_delete"); /// <summary> /// Gets whether the viewer can tag the photo. /// </summary> public bool CanTag { get; } /// <summary> /// Gets whether the <see cref="CanTag"/> property was included in the response. /// </summary> public bool HasCanTag => JObject.HasValue("can_tag"); /// <summary> /// Gets the time this photo was published. /// </summary> public EssentialsTime CreatedTime { get; } /// <summary> /// Gets whether the <see cref="CreatedTime"/> property was included in the response. /// </summary> public bool HasCreatedTime => CreatedTime != null; /// <summary> /// If this object has a place, the event associated with the place. /// </summary> public FacebookEvent Event { get; } /// <summary> /// Gets whether the <see cref="Event"/> property was included in the response. /// </summary> public bool HasEvent => Event != null; /// <summary> /// Gets a reference to the profile (user or page) that uploaded this photo. /// </summary> public FacebookEntity From { get; set; } /// <summary> /// Gets whether the <see cref="From"/> property was included in the response. /// </summary> public bool HasFrom => From != null; /// <summary> /// Gets the height of this photo in pixels. /// </summary> public int Height { get; } /// <summary> /// Gets whether the <see cref="Height"/> property was included in the response. /// </summary> public bool HasHeight => Height > 0; /// <summary> /// Gets the icon that Facebook displays when photos are published to News Feed. /// </summary> public string Icon { get; } /// <summary> /// Gets whether the <see cref="Icon"/> property was included in the response. /// </summary> public bool HasIcon => string.IsNullOrWhiteSpace(Icon) == false; /// <summary> /// Gets the different stored representations of the photo. Can vary in number based upon the size of the original photo. /// </summary> public FacebookImage[] Images { get; } /// <summary> /// Gets whether the <see cref="Width"/> property was included in the response. /// </summary> public bool HasImages => Images.Any(); /// <summary> /// Gets the link to the photo on Facebook. /// </summary> public string Link { get; } /// <summary> /// Gets whether the <see cref="Link"/> property was included in the response. /// </summary> public bool HasLink => string.IsNullOrWhiteSpace(Link) == false; /// <summary> /// Gets the user-provided caption given to this photo. Corresponds to <c>caption</c> when creating /// photos. /// </summary> public string Name { get; } /// <summary> /// Gets whether the <see cref="Name"/> property was included in the response. /// </summary> public bool HasName => string.IsNullOrWhiteSpace(Name) == false; // TODO: Add support for the "name_tags" field /// <summary> /// Gets the ID of the page story this corresponds to. May not be on all photos. Applies only to published /// photos. /// </summary> public string PageStoryId { get; } /// <summary> /// Gets whether the <see cref="PageStoryId"/> property was included in the response. /// </summary> public bool HasPageStoryId => string.IsNullOrWhiteSpace(PageStoryId) == false; /// <summary> /// Gets the link to the 100px wide representation of this photo. /// </summary> public string Picture { get; } /// <summary> /// Gets whether the <see cref="Picture"/> property was included in the response. /// </summary> public bool HasPicture => string.IsNullOrWhiteSpace(Picture) == false; /// <summary> /// Gets the place the photo was taken. It is possible to upload photos to Facebook without /// specifying a place, and in such cases the property will be <c>null</c>. /// </summary> public FacebookPlace Place { get; } /// <summary> /// Gets whether the <see cref="Place"/> property was included in the response. /// </summary> public bool HasPlace => Place != null; // TODO: Add support for the "target" field /// <summary> /// Gets the last time the photo was updated. /// </summary> public EssentialsTime UpdatedTime { get; } /// <summary> /// Gets whether the <see cref="UpdatedTime"/> property was included in the response. /// </summary> public bool HasUpdatedTime => UpdatedTime != null; /// <summary> /// Gets the different stored representations of the photo in webp format. Can vary in number based upon the /// size of the original photo. /// </summary> public FacebookImage[] WebpImages { get; } /// <summary> /// Gets whether the <see cref="WebpImages"/> property was included in the response. /// </summary> public bool HasWebpImages => WebpImages.Any(); /// <summary> /// Gets the width of this photo in pixels. /// </summary> public int Width { get; } /// <summary> /// Gets whether the <see cref="Width"/> property was included in the response. /// </summary> public bool HasWidth => Width > 0; #endregion #region Constructors private FacebookPhoto(JObject obj) : base(obj) { Id = obj.GetString("id"); Album = obj.GetObject("album", FacebookAlbum.Parse); BackdatedTime = obj.GetString("backdated_time", EssentialsTime.Parse); BackdatedTimeGranularity = obj.GetString("backdated_time_granularity"); CanBackdate = obj.GetBoolean("can_backdate"); CanDelete = obj.GetBoolean("can_delete"); CanTag = obj.GetBoolean("can_tag"); CreatedTime = obj.GetString("created_time", EssentialsTime.Parse); Event = obj.GetObject("event", FacebookEvent.Parse); From = obj.GetObject("from", FacebookEntity.Parse); Height = obj.GetInt32("height"); Icon = obj.GetString("icon"); Images = obj.GetArray("images", FacebookImage.Parse); Link = obj.GetString("link"); Name = obj.GetString("name"); // TODO: Add support for the "name_tags" field PageStoryId = obj.GetString("page_story_id"); Picture = obj.GetString("picture"); Place = obj.GetObject("place", FacebookPlace.Parse); // TODO: Add support for the "target" field UpdatedTime = obj.GetString("updated_time", EssentialsTime.Parse); WebpImages = obj.GetArray("webp_images", FacebookImage.Parse); Width = obj.GetInt32("width"); } #endregion #region Member methods /// <summary> /// Gets a best fit for an image that is larger than or equal to the specified <paramref name="width"/> and /// <paramref name="height"/>. /// </summary> /// <param name="width">The minimum width of the image.</param> /// <param name="height">The minimum height of the image.</param> /// <returns>An instance of <see cref="FacebookImage"/>, or <c>null</c> if no matching images were found.</returns> public FacebookImage GetImageGreaterThanOrEqualTo(int width, int height) { return Images.Reverse().FirstOrDefault(x => x.Width >= width && x.Height != height); } #endregion #region Static methods /// <summary> /// Parses the specified <paramref name="obj"/> into an instance of <see cref="FacebookPhoto"/>. /// </summary> /// <param name="obj">The instance of <see cref="JObject"/> to be parsed.</param> /// <returns>An instance of <see cref="FacebookPhoto"/>.</returns> public static FacebookPhoto Parse(JObject obj) { return obj == null ? null : new FacebookPhoto(obj); } #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 Xunit.Abstractions; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Xsl; using XmlCoreTest.Common; using OLEDB.Test.ModuleCore; using System.Runtime.Loader; namespace System.Xml.Tests { public class XsltcTestCaseBase : CTestCase { // Generic data for all derived test cases public string szDefaultNS = "urn:my-object"; public string szEmpty = ""; public string szInvalid = "*?%(){}[]&!@#$"; public string szLongNS = "http://www.microsoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/"; public string szLongString = "ThisIsAVeryLongStringToBeStoredAsAVariableToDetermineHowLargeThisBufferForAVariableNameCanBeAndStillFunctionAsExpected"; public string szSimple = "myArg"; public string[] szWhiteSpace = { " ", "\n", "\t", "\r", "\t\n \r\t" }; public string szXslNS = "http://www.w3.org/1999/XSL/Transform"; // Other global variables protected bool _createFromInputFile = false; // This is intiialized from a parameter passed from LTM as a dimension, that dictates whether the variation is to be created using an input file. protected bool _isInProc; // Is the current test run in proc or /Host None? private static ITestOutputHelper s_output; public XsltcTestCaseBase(ITestOutputHelper output) { s_output = output; } public static bool xsltcExeFound() { try { // Verify xsltc.exe is available XmlCoreTest.Common.XsltVerificationLibrary.SearchPath("xsltc.exe"); } catch (FileNotFoundException) { return false; } return true; } public override int Init(object objParam) { // initialize whether this run is in proc or not string executionMode = "File"; _createFromInputFile = executionMode.Equals("File"); return 1; } protected static void CompareOutput(string expected, Stream actualStream) { using (var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes(expected))) { CompareOutput(expectedStream, actualStream); } } private static string NormalizeLineEndings(string s) { return s.Replace("\r\n", "\n").Replace("\r", "\n"); } protected static void CompareOutput(Stream expectedStream, Stream actualStream, int count = 0) { actualStream.Seek(0, SeekOrigin.Begin); using (var expectedReader = new StreamReader(expectedStream)) using (var actualReader = new StreamReader(actualStream)) { for (int i = 0; i < count; i++) { actualReader.ReadLine(); expectedReader.ReadLine(); } string actual = NormalizeLineEndings(actualReader.ReadToEnd()); string expected = NormalizeLineEndings(expectedReader.ReadToEnd()); if (actual.Equals(expected)) { return; } throw new CTestFailedException("Output was not as expected.", actual, expected, null); } } protected bool LoadPersistedTransformAssembly(string asmName, string typeName, string baselineFile, bool pdb) { var other = (AssemblyLoader)Activator.CreateInstance(typeof(AssemblyLoader), typeof(AssemblyLoader).FullName); bool result = other.Verify(asmName, typeName, baselineFile, pdb); return result; } protected string ReplaceCurrentWorkingDirectory(string commandLine) { return commandLine.Replace(@"$(CurrentWorkingDirectory)", XsltcModule.TargetDirectory); } protected bool ShouldSkip(bool englishOnly) { // some test only applicable in English environment, so skip them if current cultral is not english return englishOnly && CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToLower() != "en"; } protected void VerifyTest(string cmdLine, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, string.Empty, false, string.Empty, baselineFile, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, string.Empty, false, baselineFile, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string pdbName, bool pdbCreated, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, pdbName, pdbCreated, baselineFile, true, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string pdbName, bool pdbCreated, string baselineFile, bool runAssemblyVerification, bool loadFromFile) { string targetDirectory = XsltcModule.TargetDirectory; string output = asmCreated ? TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, true, targetDirectory) : TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, false, targetDirectory); //verify assembly file existence if (asmName != null && string.CompareOrdinal(string.Empty, asmName) != 0) { if (File.Exists(GetPath(asmName)) != asmCreated) { throw new CTestFailedException("Assembly File Creation Check: FAILED"); } } //verify pdb existence if (pdbName != null && string.CompareOrdinal(string.Empty, pdbName) != 0) { if (File.Exists(GetPath(pdbName)) != pdbCreated) { throw new CTestFailedException("PDB File Creation Check: FAILED"); } } if (asmCreated && !string.IsNullOrEmpty(typeName)) { if (!LoadPersistedTransformAssembly(GetPath(asmName), typeName, baselineFile, pdbCreated)) { throw new CTestFailedException("Assembly loaded failed"); } } else { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms) { AutoFlush = true }) using (var expected = new FileStream(GetPath(baselineFile), FileMode.Open, FileAccess.Read)) { sw.Write(output); CompareOutput(expected, ms, 4); } } SafeDeleteFile(GetPath(pdbName)); SafeDeleteFile(GetPath(asmName)); return; } private static void SafeDeleteFile(string fileName) { try { var fileInfo = new FileInfo(fileName); if (fileInfo.Directory != null && !fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } if (fileInfo.Exists) { fileInfo.Delete(); } } catch (ArgumentException) { } catch (PathTooLongException) { } catch (Exception e) { s_output.WriteLine(e.Message); } } // Used to generate a unique name for an input file, and write that file, based on a specified command line. private string CreateInputFile(string commandLine) { string fileName = Path.Combine(XsltcModule.TargetDirectory, Guid.NewGuid() + ".ipf"); File.WriteAllText(fileName, commandLine); return fileName; } private string GetPath(string fileName) { return XsltcModule.TargetDirectory + Path.DirectorySeparatorChar + fileName; } /// <summary> /// Currently this method supports only 1 input file. For variations that require more than one input file to test /// @file /// functionality, custom-craft and write those input files in the body of the variation method, then pass an /// appropriate /// commandline such as @file1 @file2 @file3, along with createFromInputFile = false. /// </summary> /// <param name="commandLine"></param> /// <param name="createFromInputFile"></param> /// <param name="expectedToSucceed"></param> /// <param name="targetDirectory"></param> /// <returns></returns> private string TryCreatePersistedTransformAssembly(string commandLine, bool createFromInputFile, bool expectedToSucceed, string targetDirectory) { // If createFromInputFile is specified, create an input file now that the compiler can consume. string processArguments = createFromInputFile ? "@" + CreateInputFile(commandLine) : commandLine; var processStartInfo = new ProcessStartInfo { FileName = XsltVerificationLibrary.SearchPath("xsltc.exe"), Arguments = processArguments, //WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, WorkingDirectory = targetDirectory }; // Call xsltc to create persistant assembly. var compilerProcess = new Process { StartInfo = processStartInfo }; compilerProcess.Start(); string output = compilerProcess.StandardOutput.ReadToEnd(); compilerProcess.WaitForExit(); if (createFromInputFile) { SafeDeleteFile(processArguments.Substring(1)); } if (expectedToSucceed) { // The Assembly was created successfully if (compilerProcess.ExitCode == 0) { return output; } throw new CTestFailedException("Failed to create assembly: " + output); } return output; } public class AssemblyLoader //: MarshalByRefObject { public AssemblyLoader(string asmName) { } public bool Verify(string asmName, string typeName, string baselineFile, bool pdb) { try { var xslt = new XslCompiledTransform(); Assembly xsltasm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(asmName)); if (xsltasm == null) { //_output.WriteLine("Could not load file"); return false; } Type t = xsltasm.GetType(typeName); if (t == null) { //_output.WriteLine("No type loaded"); return false; } xslt.Load(t); var inputXml = new XmlDocument(); using (var stream = new MemoryStream()) using (var sw = new StreamWriter(stream) { AutoFlush = true }) { inputXml.LoadXml("<foo><bar>Hello, world!</bar></foo>"); xslt.Transform(inputXml, null, sw); if (!XsltVerificationLibrary.CompareXml(Path.Combine(XsltcModule.TargetDirectory, baselineFile), stream)) { //_output.WriteLine("Baseline file comparison failed"); return false; } } return true; } catch (Exception e) { s_output.WriteLine(e.Message); return false; } } private static byte[] loadFile(string filename) { using (var fs = new FileStream(filename, FileMode.Open)) { var buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); return buffer; } } } } }
// --------------------------------------------------------------------------- // <copyright file="FieldCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using System; using System.Collections; using System.Globalization; /// <summary> /// A Field Collection represents the set of fields that are in a given /// record. It can be used to efficiently navigate those fields. /// </summary> public class FieldCollection : DictionaryBase, IEnumerable { /// <summary> /// The location /// </summary> private Location location; /// <summary> /// The read only /// </summary> private bool readOnly = false; /// <summary> /// Gets a value indicating whether this field collection cannot be changed. /// </summary> public bool IsReadOnly { get { return this.readOnly; } } /// <summary> /// Gets the names. /// </summary> /// <value> /// The names. /// </value> public ICollection Names { get { return this.Dictionary.Keys; } } /// <summary> /// Gets or sets the location of the record that contained these fields. /// </summary> /// <value> /// The location. /// </value> public Location Location { get { return this.location; } set { this.CheckReadOnly(); this.location = value; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary" /> object has a fixed size. /// </summary> /// <returns>true if the <see cref="T:System.Collections.IDictionary" /> object has a fixed size; otherwise, false.</returns> public bool IsFixedSize { get { return this.readOnly; } } /// <summary> /// Sets a value indicating whether [read only]. /// </summary> /// <value> /// <c>true</c> if [read only]; otherwise, <c>false</c>. /// </value> internal bool ReadOnly { set { this.readOnly = value; } } /// <summary> /// The field values for the specified column. /// </summary> /// <value> /// The <see cref="FieldValueCollection"/>. /// </value> /// <param name="columnName">the name of the column whose field values are desired</param> /// <returns>A <see cref="FieldValueCollection"/> object to access values of this column.</returns> public FieldValueCollection this[string columnName] { get { return (FieldValueCollection)Dictionary[columnName.ToLower(CultureInfo.InvariantCulture)]; } set { this.Dictionary[columnName.ToLower(CultureInfo.InvariantCulture)] = value; } } /// <summary> /// The field values for the specified column /// </summary> /// <value> /// The <see cref="FieldValueCollection"/>. /// </value> /// <param name="column">the column ID whose field values are desired</param> /// <returns>A <see cref="FieldValueCollection"/> object to access values of this column.</returns> public FieldValueCollection this[Columnid column] { get { return (FieldValueCollection)Dictionary[column.Name.ToLower(CultureInfo.InvariantCulture)]; } set { this.Dictionary[column.Name.ToLower(CultureInfo.InvariantCulture)] = value; } } /// <summary> /// Fetches an enumerator containing all the fields for this record. /// </summary> /// <returns>An enumerator containing all the fields for this record.</returns> /// <remarks> /// This is the type safe version that may not work in other CLR /// languages. /// </remarks> public new RecordEnumerator GetEnumerator() { return new RecordEnumerator(Dictionary.GetEnumerator()); } /// <summary> /// Adds the specified values. /// </summary> /// <param name="values">The values.</param> public void Add(FieldValueCollection values) { this.Dictionary.Add(values.Name.ToLower(CultureInfo.InvariantCulture), values); } /// <summary> /// Returns whether the specifed column exists in the row. /// </summary> /// <param name="columnName">Name of the column.</param> /// <returns>Whether the specifed column exists in the row.</returns> public bool Contains(string columnName) { return this.Dictionary.Contains(columnName.ToLower(CultureInfo.InvariantCulture)); } /// <summary> /// Returns whether the specifed column exists in the row. /// </summary> /// <param name="column">The column.</param> /// <returns>Whether the specifed column exists in the row.</returns> public bool Contains(Columnid column) { return this.Dictionary.Contains(column.Name.ToLower(CultureInfo.InvariantCulture)); } /// <summary> /// Removes the specified column name. /// </summary> /// <param name="columnName">Name of the column.</param> public void Remove(string columnName) { this.Dictionary.Remove(columnName.ToLower(CultureInfo.InvariantCulture)); } /// <summary> /// Removes the specified column. /// </summary> /// <param name="column">The column.</param> public void Remove(Columnid column) { this.Dictionary.Remove(column.Name.ToLower(CultureInfo.InvariantCulture)); } /// <summary> /// Fetches an enumerator containing all the fields for this record /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> /// <remarks> /// This is the standard version that will work with other CLR /// languages. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator)this.GetEnumerator(); } /// <summary> /// Performs additional custom processes before clearing the contents of the <see cref="T:System.Collections.DictionaryBase" /> instance. /// </summary> protected override void OnClear() { this.CheckReadOnly(); } /// <summary> /// Performs additional custom processes before inserting a new element into the <see cref="T:System.Collections.DictionaryBase" /> instance. /// </summary> /// <param name="key">The key of the element to insert.</param> /// <param name="value">The value of the element to insert.</param> protected override void OnInsert(object key, object value) { this.CheckReadOnly(); } /// <summary> /// Performs additional custom processes before removing an element from the <see cref="T:System.Collections.DictionaryBase" /> instance. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <param name="value">The value of the element to remove.</param> protected override void OnRemove(object key, object value) { this.CheckReadOnly(); } /// <summary> /// Performs additional custom processes before setting a value in the <see cref="T:System.Collections.DictionaryBase" /> instance. /// </summary> /// <param name="key">The key of the element to locate.</param> /// <param name="oldValue">The old value of the element associated with <paramref name="key" />.</param> /// <param name="newValue">The new value of the element associated with <paramref name="key" />.</param> protected override void OnSet(object key, object oldValue, object newValue) { this.CheckReadOnly(); } /// <summary> /// Performs additional custom processes when validating the element with the specified key and value. /// </summary> /// <param name="key">The key of the element to validate.</param> /// <param name="value">The value of the element to validate.</param> /// <exception cref="System.ArgumentException"> /// key must be of type System.String;key /// or /// value must be of type FieldValueCollection;value /// or /// key must match value.Name;key /// </exception> protected override void OnValidate(object key, object value) { if (!(key is string)) { throw new ArgumentException("key must be of type System.String", "key"); } if (!(value is FieldValueCollection)) { throw new ArgumentException("value must be of type FieldValueCollection", "value"); } if (((string)key).ToLower(CultureInfo.InvariantCulture) != ((FieldValueCollection)value).Name.ToLower(CultureInfo.InvariantCulture)) { throw new ArgumentException("key must match value.Name", "key"); } } /// <summary> /// Checks the read only. /// </summary> /// <exception cref="System.NotSupportedException">this field collection cannot be changed</exception> private void CheckReadOnly() { if (this.readOnly) { throw new NotSupportedException("this field collection cannot be changed"); } } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSchemaElement.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.Collections; using Novell.Directory.Ldap.Utilclass; namespace Novell.Directory.Ldap { /// <summary> /// The LdapSchemaElement class is the base class representing schema /// elements (definitions) in Ldap. /// An LdapSchemaElement is read-only, single-valued LdapAttribute. /// Therefore, it does not support the addValue and removeValue methods from /// LdapAttribute. This class overrides those methods and throws /// <code>UnsupportedOperationException</code> if either of those methods are /// invoked by an application. /// </summary> /// <seealso cref="LdapSchema"> /// </seealso> /// <seealso cref="LdapConnection.FetchSchema"> /// </seealso> public abstract class LdapSchemaElement : LdapAttribute { private void InitBlock() { hashQualifier = new Hashtable(); } /// <summary> /// Returns an array of names for the element, or null if /// none is found. /// The getNames method accesses the NAME qualifier (from the BNF /// descriptions of Ldap schema definitions). The array consists of all /// values of the NAME qualifier. /// </summary> /// <returns> /// An array of names for the element, or null if none /// is found. /// </returns> public virtual string[] Names { get { if (names == null) return null; var generated_var = new string[names.Length]; names.CopyTo(generated_var, 0); return generated_var; } } /// <summary> /// Returns the description of the element. /// The getDescription method returns the value of the DESC qualifier /// (from the BNF descriptions of Ldap schema definitions). /// </summary> /// <returns> /// The description of the element. /// </returns> public virtual string Description { get { return description; } } /// <summary> /// Returns the unique object identifier (OID) of the element. /// </summary> /// <returns> /// The OID of the element. /// </returns> public virtual string ID { get { return oid; } } /// <summary> /// Returns an enumeration of all qualifiers of the element which are /// vendor specific (begin with "X-"). /// </summary> /// <returns> /// An enumeration of all qualifiers of the element. /// </returns> public virtual IEnumerator QualifierNames { get { return new EnumeratedIterator(new SupportClass.SetSupport(hashQualifier.Keys).GetEnumerator()); } } /// <summary> /// Returns whether the element has the OBSOLETE qualifier /// in its Ldap definition. /// </summary> /// <returns> /// True if the Ldap definition contains the OBSOLETE qualifier; /// false if OBSOLETE qualifier is not present. /// </returns> public virtual bool Obsolete { get { return obsolete; } } /// <summary> /// Creates an LdapSchemaElement by setting the name of the LdapAttribute. /// Because this is the only constructor, all extended classes are expected /// to call this constructor. The value of the LdapAttribute must be set /// by the setValue method. /// </summary> /// <param name="attrName"> /// The attribute name of the schema definition. Valid /// names are one of the following: /// "attributeTypes", "objectClasses", "ldapSyntaxes", /// "nameForms", "dITContentRules", "dITStructureRules", /// "matchingRules", or "matchingRuleUse" /// </param> protected internal LdapSchemaElement(string attrName) : base(attrName) { InitBlock(); } /// <summary> The names of the schema element.</summary> [CLSCompliant(false)] protected internal string[] names = {""}; /// <summary> The OID for the schema element.</summary> protected internal string oid = ""; /// <summary> The description for the schema element.</summary> [CLSCompliant(false)] protected internal string description = ""; /// <summary> /// If present, indicates that the element is obsolete, no longer in use in /// the directory. /// </summary> [CLSCompliant(false)] protected internal bool obsolete = false; /// <summary> /// A string array of optional, or vendor-specific, qualifiers for the /// schema element. /// These optional qualifiers begin with "X-"; the Novell eDirectory /// specific qualifiers begin with "X-NDS". /// </summary> protected internal string[] qualifier = {""}; /// <summary> /// A hash table that contains the vendor-specific qualifiers (for example, /// the X-NDS flags). /// </summary> protected internal Hashtable hashQualifier; /// <summary> /// Returns an array of all values of a specified optional or non- /// standard qualifier of the element. /// The getQualifier method may be used to access the values of /// vendor-specific qualifiers (which begin with "X-"). /// </summary> /// <param name="name"> /// The name of the qualifier, case-sensitive. /// </param> /// <returns> /// An array of values for the specified non-standard qualifier. /// </returns> public virtual string[] getQualifier(string name) { var attr = (AttributeQualifier) hashQualifier[name]; if (attr != null) { return attr.Values; } return null; } /// <summary> /// Returns a string in a format suitable for directly adding to a directory, /// as a value of the particular schema element. /// </summary> /// <returns> /// A string that can be used to add the element to the directory. /// </returns> public override string ToString() { return formatString(); } /// <summary> /// Implementations of formatString format a schema element into a string /// suitable for using in a modify (ADD) operation to the directory. /// ToString uses this method. This method is needed because a call to /// setQualifier requires reconstructing the string value of the schema /// element. /// </summary> protected internal abstract string formatString(); /// <summary> /// Sets the values of a specified optional or non-standard qualifier of /// the element. /// The setQualifier method is used to set the values of vendor- /// specific qualifiers (which begin with "X-"). /// </summary> /// <param name="name"> /// The name of the qualifier, case-sensitive. /// </param> /// <param name="values"> /// The values to set for the qualifier. /// </param> public virtual void setQualifier(string name, string[] values) { var attrQualifier = new AttributeQualifier(name, values); SupportClass.PutElement(hashQualifier, name, attrQualifier); /* * This is the only method that modifies the schema element. * We need to reset the attribute value since it has changed. */ Value = formatString(); } /// <summary> /// LdapSchemaElement is read-only and this method is over-ridden to /// throw an exception. /// @throws UnsupportedOperationException always thrown since /// LdapSchemaElement is read-only /// </summary> public override void addValue(string value_Renamed) { throw new NotSupportedException("addValue is not supported by LdapSchemaElement"); } /// <summary> /// LdapSchemaElement is read-only and this method is over-ridden to /// throw an exception. /// @throws UnsupportedOperationException always thrown since /// LdapSchemaElement is read-only /// </summary> public virtual void addValue(byte[] value_Renamed) { throw new NotSupportedException("addValue is not supported by LdapSchemaElement"); } /// <summary> /// LdapSchemaElement is read-only and this method is over-ridden to /// throw an exception. /// @throws UnsupportedOperationException always thrown since /// LdapSchemaElement is read-only /// </summary> public override void removeValue(string value_Renamed) { throw new NotSupportedException("removeValue is not supported by LdapSchemaElement"); } /// <summary> /// LdapSchemaElement is read-only and this method is over-ridden to /// throw an exception. /// @throws UnsupportedOperationException always thrown since /// LdapSchemaElement is read-only /// </summary> public virtual void removeValue(byte[] value_Renamed) { throw new NotSupportedException("removeValue is not supported by LdapSchemaElement"); } } }
#region Apache License // // 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. // #endregion using System; using System.Reflection; using log4net.Core; using log4net.Repository; namespace log4net { /// <summary> /// This class is used by client applications to request logger instances. /// </summary> /// <remarks> /// <para> /// This class has static methods that are used by a client to request /// a logger instance. The <see cref="M:GetLogger(string)"/> method is /// used to retrieve a logger. /// </para> /// <para> /// See the <see cref="ILog"/> interface for more details. /// </para> /// </remarks> /// <example>Simple example of logging messages /// <code lang="C#"> /// ILog log = LogManager.GetLogger("application-log"); /// /// log.Info("Application Start"); /// log.Debug("This is a debug message"); /// /// if (log.IsDebugEnabled) /// { /// log.Debug("This is another debug message"); /// } /// </code> /// </example> /// <threadsafety static="true" instance="true" /> /// <seealso cref="ILog"/> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LogManager { #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="LogManager" /> class. /// </summary> /// <remarks> /// Uses a private access modifier to prevent instantiation of this class. /// </remarks> private LogManager() { } #endregion Private Instance Constructors #region Type Specific Manager Methods #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). /// <overloads>Returns the named logger if it exists.</overloads> /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the default repository) then it /// returns a reference to the logger, otherwise it returns <c>null</c>. /// </para> /// </remarks> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns>The logger found, or <c>null</c> if no logger could be found.</returns> public static ILog Exists(string name) { return Exists(Assembly.GetCallingAssembly(), name); } /// <overloads>Get the currently defined loggers.</overloads> /// <summary> /// Returns all the currently defined loggers in the default repository. /// </summary> /// <remarks> /// <para>The root logger is <b>not</b> included in the returned array.</para> /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers() { return GetCurrentLoggers(Assembly.GetCallingAssembly()); } /// <overloads>Get or create a logger.</overloads> /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para>By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string name) { return GetLogger(Assembly.GetCallingAssembly(), name); } #endif // !NETSTANDARD1_3 /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the specified repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the logger doesn't exist in the specified /// repository. /// </returns> public static ILog Exists(string repository, string name) { return WrapLogger(LoggerManager.Exists(repository, name)); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <remarks> /// <para> /// If the named logger exists (in the repository for the specified assembly) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger, or <c>null</c> if the logger doesn't exist in the specified /// assembly's repository. /// </returns> public static ILog Exists(Assembly repositoryAssembly, string name) { return WrapLogger(LoggerManager.Exists(repositoryAssembly, name)); } /// <summary> /// Returns all the currently defined loggers in the specified repository. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <remarks> /// The root logger is <b>not</b> included in the returned array. /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers(string repository) { return WrapLoggers(LoggerManager.GetCurrentLoggers(repository)); } /// <summary> /// Returns all the currently defined loggers in the specified assembly's repository. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <remarks> /// The root logger is <b>not</b> included in the returned array. /// </remarks> /// <returns>All the defined loggers.</returns> public static ILog[] GetCurrentLoggers(Assembly repositoryAssembly) { return WrapLoggers(LoggerManager.GetCurrentLoggers(repositoryAssembly)); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieve a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string repository, string name) { return WrapLogger(LoggerManager.GetLogger(repository, name)); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <remarks> /// <para> /// Retrieve a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Assembly repositoryAssembly, string name) { return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, name)); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Get the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Type type) { #if NETSTANDARD1_3 return GetLogger(type.GetTypeInfo().Assembly, type.FullName); #else return GetLogger(Assembly.GetCallingAssembly(), type.FullName); #endif } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Gets the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="repository">The repository to lookup in.</param> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(string repository, Type type) { return WrapLogger(LoggerManager.GetLogger(repository, type)); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <remarks> /// Gets the logger for the fully qualified name of the type specified. /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="type">The full name of <paramref name="type"/> will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> public static ILog GetLogger(Assembly repositoryAssembly, Type type) { return WrapLogger(LoggerManager.GetLogger(repositoryAssembly, type)); } #endregion Type Specific Manager Methods #region Domain & Repository Manager Methods /// <summary> /// Shuts down the log4net system. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in all the /// default repositories. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void Shutdown() { LoggerManager.Shutdown(); } #if !NETSTANDARD1_3 /// <overloads>Shutdown a logger repository.</overloads> /// <summary> /// Shuts down the default repository. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// default repository. /// </para> /// <para>Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository() { ShutdownRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// <paramref name="repository"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para>The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> /// <param name="repository">The repository to shutdown.</param> public static void ShutdownRepository(string repository) { LoggerManager.ShutdownRepository(repository); } /// <summary> /// Shuts down the repository specified. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository. The repository is looked up using /// the <paramref name="repositoryAssembly"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> public static void ShutdownRepository(Assembly repositoryAssembly) { LoggerManager.ShutdownRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Reset the configuration of a repository</overloads> /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration() { ResetConfiguration(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Reset all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> /// <param name="repository">The repository to reset.</param> public static void ResetConfiguration(string repository) { LoggerManager.ResetConfiguration(repository); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <remarks> /// <para> /// Reset all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set to its default "off" value. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param> public static void ResetConfiguration(Assembly repositoryAssembly) { LoggerManager.ResetConfiguration(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Get the logger repository.</overloads> /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the callers assembly (<see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> instance for the default repository.</returns> [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] public static ILoggerRepository GetLoggerRepository() { return GetRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] public static ILoggerRepository GetLoggerRepository(string repository) { return GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repositoryAssembly"/> argument. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) { return GetRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Get a logger repository.</overloads> /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the callers assembly (<see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// </remarks> /// <returns>The <see cref="ILoggerRepository"/> instance for the default repository.</returns> public static ILoggerRepository GetRepository() { return GetRepository(Assembly.GetCallingAssembly()); } #endif /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> /// <param name="repository">The repository to lookup in.</param> public static ILoggerRepository GetRepository(string repository) { return LoggerManager.GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repositoryAssembly"/> argument. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> public static ILoggerRepository GetRepository(Assembly repositoryAssembly) { return LoggerManager.GetRepository(repositoryAssembly); } #if !NETSTANDARD1_3 /// <overloads>Create a domain</overloads> /// <summary> /// Creates a repository with the specified repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository()"/> will return /// the same repository instance. /// </para> /// </remarks> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(Type repositoryType) { return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); } /// <overloads>Create a logger repository.</overloads> /// <summary> /// Creates a repository with the specified repository type. /// </summary> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository()"/> will return /// the same repository instance. /// </para> /// </remarks> public static ILoggerRepository CreateRepository(Type repositoryType) { return CreateRepository(Assembly.GetCallingAssembly(), repositoryType); } #endif /// <summary> /// Creates a repository with the specified name. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v11.0.0.")] public static ILoggerRepository CreateDomain(string repository) { return LoggerManager.CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <remarks> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository) { return LoggerManager.CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(string repository, Type repositoryType) { return LoggerManager.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <remarks> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository, Type repositoryType) { return LoggerManager.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) { return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { return LoggerManager.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Gets the list of currently defined repositories. /// </summary> /// <remarks> /// <para> /// Get an array of all the <see cref="ILoggerRepository"/> objects that have been created. /// </para> /// </remarks> /// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns> public static ILoggerRepository[] GetAllRepositories() { return LoggerManager.GetAllRepositories(); } /// <summary> /// Flushes logging events buffered in all configured appenders in the default repository. /// </summary> /// <param name="millisecondsTimeout">The maximum time in milliseconds to wait for logging events from asycnhronous appenders to be flushed.</param> /// <returns><c>True</c> if all logging events were flushed successfully, else <c>false</c>.</returns> public static bool Flush(int millisecondsTimeout) { #if !NETSTANDARD1_3 // Excluded because GetCallingAssembly() is not available in CoreFX (https://github.com/dotnet/corefx/issues/2221). Appender.IFlushable flushableRepository = LoggerManager.GetRepository(Assembly.GetCallingAssembly()) as Appender.IFlushable; if (flushableRepository == null) { return false; } else { return flushableRepository.Flush(millisecondsTimeout); } #else return false; #endif } #endregion Domain & Repository Manager Methods #region Extension Handlers /// <summary> /// Looks up the wrapper object for the logger specified. /// </summary> /// <param name="logger">The logger to get the wrapper for.</param> /// <returns>The wrapper for the logger specified.</returns> private static ILog WrapLogger(ILogger logger) { return (ILog)s_wrapperMap.GetWrapper(logger); } /// <summary> /// Looks up the wrapper objects for the loggers specified. /// </summary> /// <param name="loggers">The loggers to get the wrappers for.</param> /// <returns>The wrapper objects for the loggers specified.</returns> private static ILog[] WrapLoggers(ILogger[] loggers) { ILog[] results = new ILog[loggers.Length]; for(int i=0; i<loggers.Length; i++) { results[i] = WrapLogger(loggers[i]); } return results; } /// <summary> /// Create the <see cref="ILoggerWrapper"/> objects used by /// this manager. /// </summary> /// <param name="logger">The logger to wrap.</param> /// <returns>The wrapper for the logger specified.</returns> private static ILoggerWrapper WrapperCreationHandler(ILogger logger) { return new LogImpl(logger); } #endregion #region Private Static Fields /// <summary> /// The wrapper map to use to hold the <see cref="LogImpl"/> objects. /// </summary> private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler)); #endregion Private Static Fields } }
/*============================================================================= * HttpTransport.cs * HTTP-based JSON-RPC request call. *============================================================================== * * Tested with .NET Framework 4.6 * * Copyright (c) 2015, Exosite LLC * All rights reserved. */ using System; using System.IO; using System.Text; using System.Net; namespace clronep { internal class HttpTransport : ITransport { private string Url; private int Timeout; private WebProxy ProxyServer = null; internal HttpTransport(string url, int timeout) { Url = url; Timeout = timeout; } public void set_proxy(string ip, int port, string user, string password) { if (null != ip && port > 0) { if (0 == ip.Length) return; this.ProxyServer = new WebProxy(ip, port); if (null != user && null != password) { this.ProxyServer.Credentials = new NetworkCredential(user, password); } System.Net.ServicePointManager.Expect100Continue = false; } } public string send(string message) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); if (null != this.ProxyServer) request.Proxy = this.ProxyServer; request.ContentType = "application/json; charset=utf-8"; request.Method = "POST"; request.Timeout = Timeout * 1000; byte[] bytes = Encoding.UTF8.GetBytes(message); request.ContentLength = bytes.Length; Stream stream = null; HttpWebResponse response = null; StreamReader reader = null; try { stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCRequestException("Unable to make http request."); } finally { if (stream != null) { stream.Close(); } } try { response = (HttpWebResponse)request.GetResponse(); if (response == null) { return null; } reader = new StreamReader(response.GetResponseStream()); string recv = reader.ReadToEnd(); return recv; } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCResponseException("Unable to get http response."); } finally { if (response != null) { response.Close(); } if (reader != null) { reader.Close(); } } } public string[] provisionSend(string message, string method, string url, WebHeaderCollection headers) { url = Url + url; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (null != this.ProxyServer) request.Proxy = this.ProxyServer; request.Method = method; request.Timeout = Timeout * 1000; if (headers["Accept"] != null) { request.Accept = headers["Accept"]; headers.Remove("Accept"); } if (headers["Connection"] != null) { request.Connection = headers["Connection"]; headers.Remove("Connection"); } if (headers["Content-Length"] != null) { request.ContentLength = Convert.ToInt64(headers["Content-Length"]); headers.Remove("Content-Length"); } if (headers["Content-Type"] != null) { request.ContentType = headers["Content-Type"]; headers.Remove("Content-Type"); } if (headers["Expect"] != null) { request.Expect = headers["Expect"]; headers.Remove("Expect"); } if (headers["If-Modified-Since"] != null) { request.IfModifiedSince = Convert.ToDateTime(headers["If-Modified-Since"]); headers.Remove("If-Modified-Since"); } if (headers["Range"] != null) { request.AddRange(Convert.ToInt32(headers["Range"])); headers.Remove("Range"); } if (headers["Referer"] != null) { request.Referer = headers["Referer"]; headers.Remove("Referer"); } if (headers["Transfer-Encoding"] != null) { request.TransferEncoding = headers["Transfer-Encoding"]; headers.Remove("Transfer-Encoding"); } if (headers["User-Agent"] != null) { request.UserAgent = headers["User-Agent"]; headers.Remove("User-Agent"); } foreach (string key in headers.Keys) { if (request.Headers[key] != null) { request.Headers.Set(key, headers[key]); } else request.Headers.Add(key, headers[key]); } HttpWebResponse response = null; StreamReader reader = null; Stream stream = null; byte[] bytes = null; if (message != null) { bytes = Encoding.UTF8.GetBytes(message); request.ContentLength = bytes.Length; try { stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCRequestException("Unable to make http request."); } finally { if (stream != null) { stream.Close(); } } } try { response = (HttpWebResponse)request.GetResponse(); if (response == null) { return null; } reader = new StreamReader(response.GetResponseStream()); string recv = reader.ReadToEnd(); string statuscode; if (HttpStatusCode.OK == response.StatusCode || HttpStatusCode.ResetContent == response.StatusCode || HttpStatusCode.NoContent == response.StatusCode) { statuscode = response.StatusCode.ToString(); recv = statuscode + "\r\n" + recv; } else { statuscode = "FAIL"; recv = statuscode + "\r\n" + recv; } return new string[2] {statuscode, recv}; } catch (System.Exception e) { Console.WriteLine(e.Message); throw new HttpRPCResponseException("Unable to get http response."); } finally { if (response != null) { response.Close(); } if (reader != null) { reader.Close(); } } } } }
using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Public Enum /// <summary> /// Compression Level as an enum for safer use /// </summary> public enum CompressionLevel { /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> BEST_COMPRESSION = Deflater.BEST_COMPRESSION, /// <summary> /// The worst but fastest compression level. /// </summary> BEST_SPEED = Deflater.BEST_SPEED, /// <summary> /// The default compression level. /// </summary> DEFAULT_COMPRESSION = Deflater.DEFAULT_COMPRESSION, /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> NO_COMPRESSION = Deflater.NO_COMPRESSION, /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> DEFLATED = Deflater.DEFLATED } #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException(nameof(level)); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public long TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException(nameof(level)); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (;;) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { switch (state) { case BUSY_STATE: // We need more input now return origLength - length; case FLUSHING_STATE: if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; break; case FINISHING_STATE: pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; break; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; /// <summary> /// The pending output. /// </summary> DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> DeflaterEngine engine; #endregion } }
namespace Azure.ResourceManager.DigitalTwins { public partial class DigitalTwinsCreateOrUpdateOperation : Azure.Operation<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> { internal DigitalTwinsCreateOrUpdateOperation() { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsDeleteOperation : Azure.Operation<Azure.Response> { internal DigitalTwinsDeleteOperation() { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.Response Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsEndpointCreateOrUpdateOperation : Azure.Operation<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource> { internal DigitalTwinsEndpointCreateOrUpdateOperation() { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsEndpointDeleteOperation : Azure.Operation<Azure.Response> { internal DigitalTwinsEndpointDeleteOperation() { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.Response Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.Response>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsEndpointOperations { protected DigitalTwinsEndpointOperations() { } public virtual Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource> Get(string resourceGroupName, string resourceName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource>> GetAsync(string resourceGroupName, string resourceName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource> List(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource> ListAsync(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsEndpointCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string resourceName, string endpointName, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties properties = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.DigitalTwins.DigitalTwinsEndpointCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string resourceName, string endpointName, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties properties = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsEndpointDeleteOperation StartDelete(string resourceGroupName, string resourceName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.DigitalTwins.DigitalTwinsEndpointDeleteOperation> StartDeleteAsync(string resourceGroupName, string resourceName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsManagementClient { protected DigitalTwinsManagementClient() { } public DigitalTwinsManagementClient(string subscriptionId, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.DigitalTwins.DigitalTwinsManagementClientOptions options = null) { } public DigitalTwinsManagementClient(string subscriptionId, System.Uri endpoint, Azure.Core.TokenCredential tokenCredential, Azure.ResourceManager.DigitalTwins.DigitalTwinsManagementClientOptions options = null) { } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsOperations DigitalTwins { get { throw null; } } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsEndpointOperations DigitalTwinsEndpoint { get { throw null; } } public virtual Azure.ResourceManager.DigitalTwins.Operations Operations { get { throw null; } } } public partial class DigitalTwinsManagementClientOptions : Azure.Core.ClientOptions { public DigitalTwinsManagementClientOptions() { } } public partial class DigitalTwinsOperations { protected DigitalTwinsOperations() { } public virtual Azure.Response<Azure.ResourceManager.DigitalTwins.Models.CheckNameResult> CheckNameAvailability(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.CheckNameResult>> CheckNameAvailabilityAsync(string location, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> Get(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription>> GetAsync(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> List(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> ListAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> ListByResourceGroup(string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> ListByResourceGroupAsync(string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsCreateOrUpdateOperation StartCreateOrUpdate(string resourceGroupName, string resourceName, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription digitalTwinsCreate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.DigitalTwins.DigitalTwinsCreateOrUpdateOperation> StartCreateOrUpdateAsync(string resourceGroupName, string resourceName, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription digitalTwinsCreate, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsDeleteOperation StartDelete(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.DigitalTwins.DigitalTwinsDeleteOperation> StartDeleteAsync(string resourceGroupName, string resourceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DigitalTwins.DigitalTwinsUpdateOperation StartUpdate(string resourceGroupName, string resourceName, System.Collections.Generic.IDictionary<string, string> tags = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.DigitalTwins.DigitalTwinsUpdateOperation> StartUpdateAsync(string resourceGroupName, string resourceName, System.Collections.Generic.IDictionary<string, string> tags = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DigitalTwinsUpdateOperation : Azure.Operation<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> { internal DigitalTwinsUpdateOperation() { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class Operations { protected Operations() { } public virtual Azure.Pageable<Azure.ResourceManager.DigitalTwins.Models.Operation> List(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DigitalTwins.Models.Operation> ListAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } namespace Azure.ResourceManager.DigitalTwins.Models { public partial class CheckNameRequest { public CheckNameRequest(string name) { } public string Name { get { throw null; } } public string Type { get { throw null; } } } public partial class CheckNameResult { internal CheckNameResult() { } public string Message { get { throw null; } } public string Name { get { throw null; } } public bool? NameAvailable { get { throw null; } } public Azure.ResourceManager.DigitalTwins.Models.Reason? Reason { get { throw null; } } } public partial class DigitalTwinsDescription : Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsResource { public DigitalTwinsDescription(string location) : base (default(string)) { } public System.DateTimeOffset? CreatedTime { get { throw null; } } public string HostName { get { throw null; } } public System.DateTimeOffset? LastUpdatedTime { get { throw null; } } public Azure.ResourceManager.DigitalTwins.Models.ProvisioningState? ProvisioningState { get { throw null; } } } public partial class DigitalTwinsDescriptionListResult { internal DigitalTwinsDescriptionListResult() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsDescription> Value { get { throw null; } } } public partial class DigitalTwinsEndpointResource : Azure.ResourceManager.DigitalTwins.Models.ExternalResource { public DigitalTwinsEndpointResource() { } public Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties Properties { get { throw null; } set { } } } public partial class DigitalTwinsEndpointResourceListResult { internal DigitalTwinsEndpointResourceListResult() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResource> Value { get { throw null; } } } public partial class DigitalTwinsEndpointResourceProperties { public DigitalTwinsEndpointResourceProperties() { } public System.DateTimeOffset? CreatedTime { get { throw null; } } public Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState? ProvisioningState { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class DigitalTwinsPatchDescription { public DigitalTwinsPatchDescription() { } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } } } public partial class DigitalTwinsResource { public DigitalTwinsResource(string location) { } public string Id { get { throw null; } } public string Location { get { throw null; } set { } } public string Name { get { throw null; } } public Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSkuInfo Sku { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Tags { get { throw null; } set { } } public string Type { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DigitalTwinsSku : System.IEquatable<Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku> { private readonly object _dummy; private readonly int _dummyPrimitive; public DigitalTwinsSku(string value) { throw null; } public static Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku F1 { get { throw null; } } public bool Equals(Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku left, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku right) { throw null; } public static implicit operator Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku left, Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku right) { throw null; } public override string ToString() { throw null; } } public partial class DigitalTwinsSkuInfo { public DigitalTwinsSkuInfo(Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku name) { } public Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsSku Name { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct EndpointProvisioningState : System.IEquatable<Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public EndpointProvisioningState(string value) { throw null; } public static Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState Canceled { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState Deleting { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState Failed { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState Provisioning { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState Succeeded { get { throw null; } } public bool Equals(Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState left, Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState left, Azure.ResourceManager.DigitalTwins.Models.EndpointProvisioningState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct EndpointType : System.IEquatable<Azure.ResourceManager.DigitalTwins.Models.EndpointType> { private readonly object _dummy; private readonly int _dummyPrimitive; public EndpointType(string value) { throw null; } public static Azure.ResourceManager.DigitalTwins.Models.EndpointType EventGrid { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointType EventHub { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.EndpointType ServiceBus { get { throw null; } } public bool Equals(Azure.ResourceManager.DigitalTwins.Models.EndpointType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DigitalTwins.Models.EndpointType left, Azure.ResourceManager.DigitalTwins.Models.EndpointType right) { throw null; } public static implicit operator Azure.ResourceManager.DigitalTwins.Models.EndpointType (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DigitalTwins.Models.EndpointType left, Azure.ResourceManager.DigitalTwins.Models.EndpointType right) { throw null; } public override string ToString() { throw null; } } public partial class EventGrid : Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties { public EventGrid(string accessKey1, string accessKey2) { } public string AccessKey1 { get { throw null; } set { } } public string AccessKey2 { get { throw null; } set { } } public string TopicEndpoint { get { throw null; } set { } } } public partial class EventHub : Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties { public EventHub(string connectionStringPrimaryKey, string connectionStringSecondaryKey) { } public string ConnectionStringPrimaryKey { get { throw null; } set { } } public string ConnectionStringSecondaryKey { get { throw null; } set { } } } public partial class ExternalResource { public ExternalResource() { } public string Id { get { throw null; } } public string Name { get { throw null; } } public string Type { get { throw null; } } } public partial class Operation { internal Operation() { } public Azure.ResourceManager.DigitalTwins.Models.OperationDisplay Display { get { throw null; } } public string Name { get { throw null; } } } public partial class OperationDisplay { internal OperationDisplay() { } public string Description { get { throw null; } } public string Operation { get { throw null; } } public string Provider { get { throw null; } } public string Resource { get { throw null; } } } public partial class OperationListResult { internal OperationListResult() { } public string NextLink { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.ResourceManager.DigitalTwins.Models.Operation> Value { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ProvisioningState : System.IEquatable<Azure.ResourceManager.DigitalTwins.Models.ProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public ProvisioningState(string value) { throw null; } public static Azure.ResourceManager.DigitalTwins.Models.ProvisioningState Canceled { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.ProvisioningState Deleting { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.ProvisioningState Failed { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.ProvisioningState Provisioning { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.ProvisioningState Succeeded { get { throw null; } } public bool Equals(Azure.ResourceManager.DigitalTwins.Models.ProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DigitalTwins.Models.ProvisioningState left, Azure.ResourceManager.DigitalTwins.Models.ProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.DigitalTwins.Models.ProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DigitalTwins.Models.ProvisioningState left, Azure.ResourceManager.DigitalTwins.Models.ProvisioningState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct Reason : System.IEquatable<Azure.ResourceManager.DigitalTwins.Models.Reason> { private readonly object _dummy; private readonly int _dummyPrimitive; public Reason(string value) { throw null; } public static Azure.ResourceManager.DigitalTwins.Models.Reason AlreadyExists { get { throw null; } } public static Azure.ResourceManager.DigitalTwins.Models.Reason Invalid { get { throw null; } } public bool Equals(Azure.ResourceManager.DigitalTwins.Models.Reason other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DigitalTwins.Models.Reason left, Azure.ResourceManager.DigitalTwins.Models.Reason right) { throw null; } public static implicit operator Azure.ResourceManager.DigitalTwins.Models.Reason (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DigitalTwins.Models.Reason left, Azure.ResourceManager.DigitalTwins.Models.Reason right) { throw null; } public override string ToString() { throw null; } } public partial class ServiceBus : Azure.ResourceManager.DigitalTwins.Models.DigitalTwinsEndpointResourceProperties { public ServiceBus(string primaryConnectionString, string secondaryConnectionString) { } public string PrimaryConnectionString { get { throw null; } set { } } public string SecondaryConnectionString { get { throw null; } set { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for RoleAssignmentsOperations. /// </summary> public static partial class RoleAssignmentsOperationsExtensions { /// <summary> /// Gets all the role assignments for the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> public static IPage<RoleAssignmentResourceFormat> ListByHub(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName) { return operations.ListByHubAsync(resourceGroupName, hubName).GetAwaiter().GetResult(); } /// <summary> /// Gets all the role assignments for the specified hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<RoleAssignmentResourceFormat>> ListByHubAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByHubWithHttpMessagesAsync(resourceGroupName, hubName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The assignment name /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate RoleAssignment operation. /// </param> public static RoleAssignmentResourceFormat CreateOrUpdate(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, RoleAssignmentResourceFormat parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, hubName, assignmentName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The assignment name /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate RoleAssignment operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleAssignmentResourceFormat> CreateOrUpdateAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, RoleAssignmentResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, assignmentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The name of the role assignment. /// </param> public static RoleAssignmentResourceFormat Get(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName) { return operations.GetAsync(resourceGroupName, hubName, assignmentName).GetAwaiter().GetResult(); } /// <summary> /// Gets the role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The name of the role assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleAssignmentResourceFormat> GetAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, hubName, assignmentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The name of the role assignment. /// </param> public static void Delete(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName) { operations.DeleteAsync(resourceGroupName, hubName, assignmentName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The name of the role assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, hubName, assignmentName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The assignment name /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate RoleAssignment operation. /// </param> public static RoleAssignmentResourceFormat BeginCreateOrUpdate(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, RoleAssignmentResourceFormat parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, hubName, assignmentName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a role assignment in the hub. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='assignmentName'> /// The assignment name /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate RoleAssignment operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<RoleAssignmentResourceFormat> BeginCreateOrUpdateAsync(this IRoleAssignmentsOperations operations, string resourceGroupName, string hubName, string assignmentName, RoleAssignmentResourceFormat parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, hubName, assignmentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the role assignments for the specified hub. /// </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<RoleAssignmentResourceFormat> ListByHubNext(this IRoleAssignmentsOperations operations, string nextPageLink) { return operations.ListByHubNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the role assignments for the specified hub. /// </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<RoleAssignmentResourceFormat>> ListByHubNextAsync(this IRoleAssignmentsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByHubNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Text; using System.Net; using System.Reflection; using System.IO; using System.Security.Cryptography.X509Certificates; using TKCode123.Net.Http; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware.NetduinoPlus; using Microsoft.SPOT.Net.NetworkInformation; using Microsoft.SPOT; namespace NetduinoWeb { class Server : TinyWeb { protected readonly OutputPort _onboardLED; protected readonly InterruptPort _button; protected bool _withSDCard; public Server(int port, X509Certificate certificate) : base(port, certificate) { _onboardLED = new OutputPort(Pins.ONBOARD_LED, false); _button = new InterruptPort(Pins.ONBOARD_SW1, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh); AddVariable(new InputPortVariable("Button", _button)); AddVariable(new MachineTime()); Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged; Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged; } public override void Dispose() { Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged -= NetworkChange_NetworkAvailabilityChanged; Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged -= NetworkChange_NetworkAddressChanged; if (_onboardLED != null) _onboardLED.Dispose(); if (_button != null) _button.Dispose(); base.Dispose(); } void NetworkChange_NetworkAddressChanged(object sender, EventArgs e) { Shutdown("Network Address Changed"); } void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e) { Shutdown("Network Availablity Changed"); } protected override void PreHandle() { if (_onboardLED != null) _onboardLED.Write(true); } protected override void PostHandle() { if (_onboardLED != null) _onboardLED.Write(false); } protected virtual TinyContext CreateContext(HttpListenerContext c) { return new NetduinoContext(c, this); } class NetduinoContext : TinyContext { internal NetduinoContext(HttpListenerContext r, Server s) : base(r, s) { } internal string Content { get; set; } public override string ReplaceSymbol(string source) { if ("CONTENT".Equals(source)) return Content ?? ""; return base.ReplaceSymbol(source); } } class VariableBase : TinyWeb.IVariable { readonly string _name; protected VariableBase(string name) { _name = name; } public virtual bool IsReadOnly { get { return true; } } public string Name { get { return _name; } } public virtual string ValueString { get { return ""; } set { throw new NotImplementedException(); } } } class MachineTime : VariableBase { internal MachineTime() : base("MachineTime") { } public override string ValueString { get { return Microsoft.SPOT.Hardware.Utility.GetMachineTime().ToString(); } set { base.ValueString = value; } } } class InputPortVariable : VariableBase { private readonly InputPort _port; internal InputPortVariable(string name, InputPort port) : base(name) { _port = port; } public override string ValueString { get { return _port.Read() ? "1" : "0"; } } } protected override bool Handle(TinyContext context) { string url = context.ClientContext.Request.RawUrl.ToUpper(); if (context.ClientContext.Request.HttpMethod == "GET") { if (url == "/TEST") { return Respond(context, System.Net.HttpStatusCode.OK, true, "text/html", true, "<html><head></head><body>Button={@Button@} {@MachineTime@}</body></html>"); } if (url == "/RESET") { using (var resp = context.ClientContext.Response) { resp.StatusCode = (int)HttpStatusCode.ResetContent; } return false; } if (url == "/") url = "/DEFAULT.HTM"; bool withSyms = true; string contentType = "text/html"; var st = Statics.Find(url, ref withSyms, ref contentType); if (st != null) { return Respond(context, HttpStatusCode.OK, withSyms, contentType, url == "/DEFAULT.HTM", st); } if (_withSDCard && ((st = FindSDCard(url, ref withSyms, ref contentType)) != null)) { return Respond(context, HttpStatusCode.OK, withSyms, contentType, url == "/DEFAULT.HTM", st); } ((NetduinoContext)context).Content = "Page '{@RAWURL@}' not found.<br>You should update {@REFERER@}."; return Respond(context, HttpStatusCode.NotFound, true, "text/html", true, Statics.HTML._DEFAULT_HTM); } return base.Handle(context); } protected static object FindSDCard(string name, ref bool withSyms, ref string contentType) { StringBuilder sb = new StringBuilder("\\SD\\"); sb.Append(name); sb.Replace('/', '\\'); string replaced = sb.ToString(); try { if (new FileInfo(replaced).Exists) { int dot = replaced.LastIndexOf('.'); if (dot >= 0 && replaced.Length > dot + 1) { var ext = replaced.Substring(dot); if (ext == ".HTM") { contentType = "text/html; charset=UTF-8;"; withSyms = true; } else if (ext == ".CSS") { contentType = "text/css; charset=UTF-8;"; withSyms = false; } else if (ext == ".JS") { contentType = "text/javascript; charset=UTF-8;"; withSyms = false; } else if (ext == ".ICO") { contentType = "image/x-icon"; } else if (ext == ".PNG") { contentType = "image/png"; } } return File.ReadAllBytes(replaced); } } catch { } return null; } public override string Title { get { return "NETDUINO WEB"; } } class Statics { public static object Find(string name, ref bool withSyms, ref string contentType) { if (name == "/NETDUINOWEB.APPCACHE") { contentType = "text/cache-manifest"; return APPCACHE; } StringBuilder sb = new StringBuilder(name); sb.Replace('.', '_'); sb.Replace('/', '_'); string repl = sb.ToString(); FieldInfo fi; if ((fi = typeof(HTML).GetField(repl)) != null) { withSyms = true; contentType = "text/html; charset=UTF-8;"; return (string)fi.GetValue(null); } if ((fi = typeof(CSS).GetField(repl)) != null) { withSyms = false; contentType = "text/css; charset=UTF-8;"; return (string)fi.GetValue(null); } if ((fi = typeof(JAVASCRIPT).GetField(repl)) != null) { withSyms = false; contentType = "application/javascript; charset=UTF-8;"; return (string)fi.GetValue(null); } if ((fi = typeof(BINARY).GetField(repl)) != null) { withSyms = false; if (repl[repl.Length-1] == 'O') contentType = "image/x-icon"; else if (repl[repl.Length-1] == 'G') contentType = "image/png"; return System.Convert.FromBase64String((string)fi.GetValue(null)); } return null; } internal static readonly string APPCACHE = @"CACHE MANIFEST # {@SERVERSTART@} CACHE: #DEFAULT.CSS FAVICON.ICO NETWORK: #DEFAULT.JS DEFAULT.CS * FALLBACK: "; internal class CSS { public static readonly string _DEFAULT_CSS = @"<style type='text/css'> body { margin:0px; background-color:#dcdcdc; font-family:sans-serif; } a { color:#003366; } a:hover { background-color:#eeeeff; } #content { float:left; } #menu { background-color:#cce0ff; width:80px; float:left; } #footer { background-color:#b2d1ff; color:Black; clear:both; text-align:center; } #header { background-color:#b2d1ff; color:DarkBlue; padding:0px; margin:0px; } #container { background-color:#dcdcdc; overflow:auto; width:100%; height:100%; } </style> "; } internal class HTML { public static readonly string _DEFAULT_HTM = @"<!DOCTYPE html> <html manifest='NETDUINOWEB.APPCACHE'> <head> <meta charset='UTF-8' /> <meta name='generator' content='{@GENERATOR@}' /> <link rel='icon' href='FAVICON.ICO' type='image/x-icon'> <title>{@TITLE@}</title> <meta name='viewport' content='height=device-height, width=device-width'> <link rel='stylesheet' href='DEFAULT.CSS' type='text/css'> </head> <body> <div id='container' > <div id='header'> <b>Welcome to {@SERVERLINK@}.</b> </div> <div id='menu'> <b>Menu</b><br> <a href='RESET'>RESET</a><br> <a href='lkjl'>CSS</a><br> <a href='ABOUT'>About</a> </div> <div id='content'> {@CONTENT@} </div> <div id='footer'> <small>{@CURRENTDATETIME@} Calls:{@CALLS@} Duration:{@DURATION@}</small> </div> </div> </body> </html> "; } internal class JAVASCRIPT { public static readonly string _DEFAULT_JS = @"<script></script>"; } internal class BINARY { public static readonly string _FAVICON_ICO = @"AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAD3zosAAAAAAPD29wCl5/AAcICCAIqdoQDe3t4AW1peAFdUXgDr7dMA0tbWAEZESgDt7e0AAAAAAAAAAAAAAAAAFmZmZmZmZmEWMzMzMAAzYRYzMzMwADNhFjMzMzAAM2EWM5mjNAAzYRYzlaMwADNhFjOVozAAM2Emw6qjMAA8YkJsMzMzM8YktCbDMzM8YksbQmwzM8YksRG0JsM8YksREXhCYzYksRERt7QmYksRERF7G0IksREREbcRtEsRERGAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAAAAAAAAAAAAAAAAAgAEAAMADAADABwAAwA8AAMgfAADMPwAA"; } } } }
namespace Epi.Windows.MakeView.Forms { partial class CheckCode { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CheckCode)); this.tvCodeBlocks = new System.Windows.Forms.TreeView(); this.codeText = new System.Windows.Forms.RichTextBox(); this.CommandContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CheckCodeStatusBar = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.LineNumberLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.ColumnNumberLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.ContextLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel6 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.basicToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.advancedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripStatusLabel3 = new System.Windows.Forms.ToolStripStatusLabel(); this.PositionNumberLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.ValidateCodeToolStripButton = new System.Windows.Forms.ToolStripButton(); this.btnCancel = new System.Windows.Forms.ToolStripButton(); this.btnSave = new System.Windows.Forms.ToolStripButton(); this.btnPrint = new System.Windows.Forms.ToolStripButton(); this.AddCodeBlockToolStripButton = new System.Windows.Forms.ToolStripButton(); this.mainImageList = new System.Windows.Forms.ImageList(this.components); this.StatusTextBox = new System.Windows.Forms.RichTextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.btnAddBlock = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.Commands = new System.Windows.Forms.ListBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.CheckCodeMenu = new System.Windows.Forms.MenuStrip(); this.mnuFile = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFileValidate = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFileSave = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFileSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFilePrint = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFileClose = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEdit = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditUndo = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditRedo = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.mnuEditCut = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditCopy = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditPaste = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.mnuEditFind = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditFindNext = new System.Windows.Forms.ToolStripMenuItem(); this.mnuEditReplace = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFonts = new System.Windows.Forms.ToolStripMenuItem(); this.mnuFontsSetEditorFont = new System.Windows.Forms.ToolStripMenuItem(); this.validationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.enableVariableValidationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CheckCodeFontDialog = new System.Windows.Forms.FontDialog(); this.CommandContextMenu.SuspendLayout(); this.CheckCodeStatusBar.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.CheckCodeMenu.SuspendLayout(); this.SuspendLayout(); // // tvCodeBlocks // resources.ApplyResources(this.tvCodeBlocks, "tvCodeBlocks"); this.tvCodeBlocks.HideSelection = false; this.tvCodeBlocks.Name = "tvCodeBlocks"; // // codeText // this.codeText.AcceptsTab = true; resources.ApplyResources(this.codeText, "codeText"); this.codeText.AutoWordSelection = true; this.codeText.BorderStyle = System.Windows.Forms.BorderStyle.None; this.codeText.ContextMenuStrip = this.CommandContextMenu; this.codeText.ForeColor = System.Drawing.Color.Blue; this.codeText.HideSelection = false; this.codeText.Name = "codeText"; this.codeText.ShowSelectionMargin = true; this.codeText.TextChanged += new System.EventHandler(this.codeText_TextChanged); this.codeText.KeyUp += new System.Windows.Forms.KeyEventHandler(this.codeText_KeyUp); this.codeText.MouseDown += new System.Windows.Forms.MouseEventHandler(this.codeText_MouseDown); // // CommandContextMenu // this.CommandContextMenu.ImageScalingSize = new System.Drawing.Size(20, 20); this.CommandContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cutToolStripMenuItem, this.copyToolStripMenuItem, this.pasteToolStripMenuItem, this.deleteToolStripMenuItem}); this.CommandContextMenu.Name = "contextMenuStrip1"; resources.ApplyResources(this.CommandContextMenu, "CommandContextMenu"); // // cutToolStripMenuItem // this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; resources.ApplyResources(this.cutToolStripMenuItem, "cutToolStripMenuItem"); this.cutToolStripMenuItem.Click += new System.EventHandler(this.CutToolStripMenuItem_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem"); this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; resources.ApplyResources(this.pasteToolStripMenuItem, "pasteToolStripMenuItem"); this.pasteToolStripMenuItem.Click += new System.EventHandler(this.pasteToolStripMenuItem_Click); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem"); this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click); // // CheckCodeStatusBar // this.CheckCodeStatusBar.ImageScalingSize = new System.Drawing.Size(20, 20); this.CheckCodeStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.LineNumberLabel, this.toolStripStatusLabel2, this.ColumnNumberLabel, this.ContextLabel, this.toolStripStatusLabel6, this.toolStripDropDownButton1, this.toolStripStatusLabel3, this.PositionNumberLabel}); resources.ApplyResources(this.CheckCodeStatusBar, "CheckCodeStatusBar"); this.CheckCodeStatusBar.Name = "CheckCodeStatusBar"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; resources.ApplyResources(this.toolStripStatusLabel1, "toolStripStatusLabel1"); // // LineNumberLabel // this.LineNumberLabel.Name = "LineNumberLabel"; resources.ApplyResources(this.LineNumberLabel, "LineNumberLabel"); // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; resources.ApplyResources(this.toolStripStatusLabel2, "toolStripStatusLabel2"); // // ColumnNumberLabel // this.ColumnNumberLabel.Name = "ColumnNumberLabel"; resources.ApplyResources(this.ColumnNumberLabel, "ColumnNumberLabel"); // // ContextLabel // this.ContextLabel.Name = "ContextLabel"; resources.ApplyResources(this.ContextLabel, "ContextLabel"); // // toolStripStatusLabel6 // this.toolStripStatusLabel6.Name = "toolStripStatusLabel6"; resources.ApplyResources(this.toolStripStatusLabel6, "toolStripStatusLabel6"); // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.basicToolStripMenuItem, this.advancedToolStripMenuItem}); resources.ApplyResources(this.toolStripDropDownButton1, "toolStripDropDownButton1"); this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; // // basicToolStripMenuItem // resources.ApplyResources(this.basicToolStripMenuItem, "basicToolStripMenuItem"); this.basicToolStripMenuItem.Name = "basicToolStripMenuItem"; // // advancedToolStripMenuItem // resources.ApplyResources(this.advancedToolStripMenuItem, "advancedToolStripMenuItem"); this.advancedToolStripMenuItem.Name = "advancedToolStripMenuItem"; // // toolStripStatusLabel3 // this.toolStripStatusLabel3.Name = "toolStripStatusLabel3"; resources.ApplyResources(this.toolStripStatusLabel3, "toolStripStatusLabel3"); // // PositionNumberLabel // this.PositionNumberLabel.Name = "PositionNumberLabel"; resources.ApplyResources(this.PositionNumberLabel, "PositionNumberLabel"); // // toolStrip1 // this.toolStrip1.GripMargin = new System.Windows.Forms.Padding(0); this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ValidateCodeToolStripButton, this.btnCancel, this.btnSave, this.btnPrint, this.AddCodeBlockToolStripButton}); resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.Name = "toolStrip1"; // // ValidateCodeToolStripButton // resources.ApplyResources(this.ValidateCodeToolStripButton, "ValidateCodeToolStripButton"); this.ValidateCodeToolStripButton.Name = "ValidateCodeToolStripButton"; this.ValidateCodeToolStripButton.Click += new System.EventHandler(this.ValidateCodeToolStripButton_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnSave // resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.Name = "btnSave"; this.btnSave.Click += new System.EventHandler(this.SaveHandler); // // btnPrint // resources.ApplyResources(this.btnPrint, "btnPrint"); this.btnPrint.Name = "btnPrint"; this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click); // // AddCodeBlockToolStripButton // this.AddCodeBlockToolStripButton.Name = "AddCodeBlockToolStripButton"; resources.ApplyResources(this.AddCodeBlockToolStripButton, "AddCodeBlockToolStripButton"); // // mainImageList // this.mainImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("mainImageList.ImageStream"))); this.mainImageList.TransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.mainImageList.Images.SetKeyName(0, "OpenFolder.bmp"); this.mainImageList.Images.SetKeyName(1, "ClosedFolder.bmp"); this.mainImageList.Images.SetKeyName(2, "CodeSnippet.bmp"); this.mainImageList.Images.SetKeyName(3, "deleteSmall.bmp"); // // StatusTextBox // resources.ApplyResources(this.StatusTextBox, "StatusTextBox"); this.StatusTextBox.Name = "StatusTextBox"; this.StatusTextBox.ReadOnly = true; this.StatusTextBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.StatusTextBox_MouseMove); this.StatusTextBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.StatusTextBox_MouseUp); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.btnAddBlock); this.groupBox1.Controls.Add(this.tvCodeBlocks); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // btnAddBlock // resources.ApplyResources(this.btnAddBlock, "btnAddBlock"); this.btnAddBlock.Name = "btnAddBlock"; this.btnAddBlock.UseVisualStyleBackColor = true; this.btnAddBlock.Click += new System.EventHandler(this.btnAddBlock_Click); // // groupBox2 // resources.ApplyResources(this.groupBox2, "groupBox2"); this.groupBox2.Controls.Add(this.Commands); this.groupBox2.Name = "groupBox2"; this.groupBox2.TabStop = false; // // Commands // resources.ApplyResources(this.Commands, "Commands"); this.Commands.FormattingEnabled = true; this.Commands.Items.AddRange(new object[] { resources.GetString("Commands.Items"), resources.GetString("Commands.Items1"), resources.GetString("Commands.Items2"), resources.GetString("Commands.Items3"), resources.GetString("Commands.Items4"), resources.GetString("Commands.Items5"), resources.GetString("Commands.Items6"), resources.GetString("Commands.Items7"), resources.GetString("Commands.Items8"), resources.GetString("Commands.Items9"), resources.GetString("Commands.Items10"), resources.GetString("Commands.Items11"), resources.GetString("Commands.Items12"), resources.GetString("Commands.Items13"), resources.GetString("Commands.Items14"), resources.GetString("Commands.Items15"), resources.GetString("Commands.Items16"), resources.GetString("Commands.Items17"), resources.GetString("Commands.Items18"), resources.GetString("Commands.Items19"), resources.GetString("Commands.Items20"), resources.GetString("Commands.Items21"), resources.GetString("Commands.Items22"), resources.GetString("Commands.Items23")}); this.Commands.Name = "Commands"; this.Commands.SelectedIndexChanged += new System.EventHandler(this.Commands_SelectedIndexChanged); // // groupBox3 // resources.ApplyResources(this.groupBox3, "groupBox3"); this.groupBox3.Controls.Add(this.StatusTextBox); this.groupBox3.Name = "groupBox3"; this.groupBox3.TabStop = false; // // splitContainer1 // resources.ApplyResources(this.splitContainer1, "splitContainer1"); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.codeText); this.splitContainer1.Panel1.Controls.Add(this.groupBox3); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); // // splitContainer2 // resources.ApplyResources(this.splitContainer2, "splitContainer2"); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.groupBox1); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.groupBox2); // // CheckCodeMenu // this.CheckCodeMenu.ImageScalingSize = new System.Drawing.Size(20, 20); this.CheckCodeMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuFile, this.mnuEdit, this.mnuFonts, this.validationToolStripMenuItem}); resources.ApplyResources(this.CheckCodeMenu, "CheckCodeMenu"); this.CheckCodeMenu.Name = "CheckCodeMenu"; // // mnuFile // this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuFileValidate, this.mnuFileSave, this.mnuFileSaveAs, this.mnuFilePrint, this.mnuFileClose}); this.mnuFile.Name = "mnuFile"; resources.ApplyResources(this.mnuFile, "mnuFile"); // // mnuFileValidate // this.mnuFileValidate.Name = "mnuFileValidate"; resources.ApplyResources(this.mnuFileValidate, "mnuFileValidate"); this.mnuFileValidate.Click += new System.EventHandler(this.ValidateCodeToolStripButton_Click); // // mnuFileSave // this.mnuFileSave.Name = "mnuFileSave"; resources.ApplyResources(this.mnuFileSave, "mnuFileSave"); this.mnuFileSave.Click += new System.EventHandler(this.SaveHandler); // // mnuFileSaveAs // this.mnuFileSaveAs.Name = "mnuFileSaveAs"; resources.ApplyResources(this.mnuFileSaveAs, "mnuFileSaveAs"); this.mnuFileSaveAs.Click += new System.EventHandler(this.mnuFileSaveAs_Click); // // mnuFilePrint // this.mnuFilePrint.Name = "mnuFilePrint"; resources.ApplyResources(this.mnuFilePrint, "mnuFilePrint"); this.mnuFilePrint.Click += new System.EventHandler(this.btnPrint_Click); // // mnuFileClose // this.mnuFileClose.Name = "mnuFileClose"; resources.ApplyResources(this.mnuFileClose, "mnuFileClose"); this.mnuFileClose.Click += new System.EventHandler(this.btnCancel_Click); // // mnuEdit // this.mnuEdit.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuEditUndo, this.mnuEditRedo, this.toolStripMenuItem2, this.mnuEditCut, this.mnuEditCopy, this.mnuEditPaste, this.toolStripMenuItem1, this.mnuEditFind, this.mnuEditFindNext, this.mnuEditReplace}); this.mnuEdit.Name = "mnuEdit"; resources.ApplyResources(this.mnuEdit, "mnuEdit"); // // mnuEditUndo // this.mnuEditUndo.Name = "mnuEditUndo"; resources.ApplyResources(this.mnuEditUndo, "mnuEditUndo"); this.mnuEditUndo.Click += new System.EventHandler(this.mnuEditUndo_Click); // // mnuEditRedo // this.mnuEditRedo.Name = "mnuEditRedo"; resources.ApplyResources(this.mnuEditRedo, "mnuEditRedo"); this.mnuEditRedo.Click += new System.EventHandler(this.mnuEditRedo_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; resources.ApplyResources(this.toolStripMenuItem2, "toolStripMenuItem2"); // // mnuEditCut // this.mnuEditCut.Name = "mnuEditCut"; resources.ApplyResources(this.mnuEditCut, "mnuEditCut"); this.mnuEditCut.Click += new System.EventHandler(this.mnuEditCut_Click); // // mnuEditCopy // this.mnuEditCopy.Name = "mnuEditCopy"; resources.ApplyResources(this.mnuEditCopy, "mnuEditCopy"); this.mnuEditCopy.Click += new System.EventHandler(this.mnuEditCopy_Click); // // mnuEditPaste // this.mnuEditPaste.Name = "mnuEditPaste"; resources.ApplyResources(this.mnuEditPaste, "mnuEditPaste"); this.mnuEditPaste.Click += new System.EventHandler(this.mnuEditPaste_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1"); // // mnuEditFind // this.mnuEditFind.Name = "mnuEditFind"; resources.ApplyResources(this.mnuEditFind, "mnuEditFind"); this.mnuEditFind.Click += new System.EventHandler(this.mnuEditFind_Click); // // mnuEditFindNext // this.mnuEditFindNext.Name = "mnuEditFindNext"; resources.ApplyResources(this.mnuEditFindNext, "mnuEditFindNext"); this.mnuEditFindNext.Click += new System.EventHandler(this.mnuEditFindNext_Click); // // mnuEditReplace // this.mnuEditReplace.Name = "mnuEditReplace"; resources.ApplyResources(this.mnuEditReplace, "mnuEditReplace"); this.mnuEditReplace.Click += new System.EventHandler(this.mnuEditReplace_Click); // // mnuFonts // this.mnuFonts.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuFontsSetEditorFont}); this.mnuFonts.Name = "mnuFonts"; resources.ApplyResources(this.mnuFonts, "mnuFonts"); // // mnuFontsSetEditorFont // this.mnuFontsSetEditorFont.Name = "mnuFontsSetEditorFont"; resources.ApplyResources(this.mnuFontsSetEditorFont, "mnuFontsSetEditorFont"); this.mnuFontsSetEditorFont.Click += new System.EventHandler(this.mnuFontsSetEditorFont_Click); // // validationToolStripMenuItem // this.validationToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.enableVariableValidationToolStripMenuItem}); this.validationToolStripMenuItem.Name = "validationToolStripMenuItem"; resources.ApplyResources(this.validationToolStripMenuItem, "validationToolStripMenuItem"); // // enableVariableValidationToolStripMenuItem // this.enableVariableValidationToolStripMenuItem.CheckOnClick = true; this.enableVariableValidationToolStripMenuItem.Name = "enableVariableValidationToolStripMenuItem"; resources.ApplyResources(this.enableVariableValidationToolStripMenuItem, "enableVariableValidationToolStripMenuItem"); this.enableVariableValidationToolStripMenuItem.Click += new System.EventHandler(this.enableVariableValidationToolStripMenuItem_Click); // // CheckCode // resources.ApplyResources(this, "$this"); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.CheckCodeStatusBar); this.Controls.Add(this.CheckCodeMenu); this.MainMenuStrip = this.CheckCodeMenu; this.MinimizeBox = false; this.Name = "CheckCode"; this.ShowIcon = false; this.ShowInTaskbar = false; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.CheckCode_FormClosing); this.Shown += new System.EventHandler(this.CheckCode_Shown); this.ResizeEnd += new System.EventHandler(this.CheckCode_ResizeEnd); this.CommandContextMenu.ResumeLayout(false); this.CheckCodeStatusBar.ResumeLayout(false); this.CheckCodeStatusBar.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); this.CheckCodeMenu.ResumeLayout(false); this.CheckCodeMenu.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.TreeView tvCodeBlocks; public System.Windows.Forms.RichTextBox codeText; private System.Windows.Forms.StatusStrip CheckCodeStatusBar; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripStatusLabel LineNumberLabel; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; private System.Windows.Forms.ToolStripStatusLabel ColumnNumberLabel; private System.Windows.Forms.ToolStripStatusLabel ContextLabel; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel6; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem basicToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem advancedToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton btnCancel; private System.Windows.Forms.ToolStripButton btnSave; private System.Windows.Forms.ToolStripButton btnPrint; private System.Windows.Forms.ToolStripButton AddCodeBlockToolStripButton; private System.Windows.Forms.ContextMenuStrip CommandContextMenu; private System.Windows.Forms.ToolStripMenuItem cutToolStripMenuItem; private System.Windows.Forms.ImageList mainImageList; private System.Windows.Forms.RichTextBox StatusTextBox; private System.Windows.Forms.ToolStripButton ValidateCodeToolStripButton; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Button btnAddBlock; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.ListBox Commands; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pasteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3; private System.Windows.Forms.ToolStripStatusLabel PositionNumberLabel; private System.Windows.Forms.MenuStrip CheckCodeMenu; private System.Windows.Forms.ToolStripMenuItem mnuEdit; private System.Windows.Forms.ToolStripMenuItem mnuEditFind; private System.Windows.Forms.ToolStripMenuItem mnuEditReplace; private System.Windows.Forms.ToolStripMenuItem mnuEditFindNext; private System.Windows.Forms.ToolStripMenuItem mnuEditUndo; private System.Windows.Forms.ToolStripMenuItem mnuEditRedo; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem mnuEditCut; private System.Windows.Forms.ToolStripMenuItem mnuEditCopy; private System.Windows.Forms.ToolStripMenuItem mnuEditPaste; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem mnuFile; private System.Windows.Forms.ToolStripMenuItem mnuFonts; private System.Windows.Forms.ToolStripMenuItem mnuFileValidate; private System.Windows.Forms.ToolStripMenuItem mnuFileSave; private System.Windows.Forms.ToolStripMenuItem mnuFileSaveAs; private System.Windows.Forms.ToolStripMenuItem mnuFilePrint; private System.Windows.Forms.ToolStripMenuItem mnuFileClose; private System.Windows.Forms.ToolStripMenuItem mnuFontsSetEditorFont; private System.Windows.Forms.FontDialog CheckCodeFontDialog; private System.Windows.Forms.ToolStripMenuItem validationToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem enableVariableValidationToolStripMenuItem; } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace Glass.Mapper.Tests { [TestFixture] public class UtilitiesFixture { #region SplitOnFirstOccurance [Test] public void SplitOnFirstOccurance_SplitInMiddleOfString_ReturnsTwoParts() { //Arrange var input = "hello?world?hi"; var first = "hello"; var second = "world?hi"; var separator = '?'; //Act var result = Utilities.SplitOnFirstOccurance(input, separator); //Assert Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } [Test] public void SplitOnFirstOccurance_NoSeparator_ReturnsTwoParts() { //Arrange var input = "helloworldhi"; var first = "helloworldhi"; var second = string.Empty; var separator = '?'; //Act var result = Utilities.SplitOnFirstOccurance(input, separator); //Assert Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } [Test] public void SplitOnFirstOccurance_SeparatorAtEnd_ReturnsTwoParts() { //Arrange var input = "helloworldhi?"; var first = "helloworldhi"; var second = string.Empty; var separator = '?'; //Act var result = Utilities.SplitOnFirstOccurance(input, separator); //Assert Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } [Test] public void SplitOnFirstOccurance_SeparatorAtStart_ReturnsTwoParts() { //Arrange var input = "?helloworldhi?"; var first = string.Empty; var second = "helloworldhi?"; var separator = '?'; //Act var result = Utilities.SplitOnFirstOccurance(input, separator); //Assert Assert.AreEqual(first, result[0]); Assert.AreEqual(second, result[1]); } #endregion #region Method - CreateConstructorDelegates [Test] public void CreateConstructorDelegates_NoParameters_CreatesSingleConstructor() { //Assign Type type = typeof (StubNoParameters); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(0, result.First().Key.GetParameters().Length); } [Test] public void CreateConstructorDelegates_OneParameters_CreatesSingleConstructor() { //Assign Type type = typeof(StubOneParameter); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(1, result.First().Key.GetParameters().Length); } [Test] public void CreateConstructorDelegates_OneParametersInvoked_CreatesSingleConstructor() { //Assign Type type = typeof(StubOneParameter); var param1 = "hello world"; //Act var result = Utilities.CreateConstructorDelegates(type); var obj = result.First().Value.DynamicInvoke(param1) as StubOneParameter; //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(1, result.First().Key.GetParameters().Length); Assert.AreEqual(param1, obj.Param1); } [Test] public void CreateConstructorDelegates_TwoParameters_CreatesSingleConstructor() { //Assign Type type = typeof(StubTwoParameters); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(2, result.First().Key.GetParameters().Length); } [Test] public void CreateConstructorDelegates_TwoParametersInvoke_CreatesSingleConstructor() { //Assign Type type = typeof(StubTwoParameters); var param1 = "hello world"; var param2 = 456; //Act var result = Utilities.CreateConstructorDelegates(type); var obj = result.First().Value.DynamicInvoke(param1, param2) as StubTwoParameters; //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(2, result.First().Key.GetParameters().Length); Assert.AreEqual(param1, obj.Param1); Assert.AreEqual(param2, obj.Param2); } [Test] public void CreateConstructorDelegates_ThreeParameters_CreatesSingleConstructor() { //Assign Type type = typeof(StubThreeParameters); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(3, result.First().Key.GetParameters().Length); } [Test] public void CreateConstructorDelegates_FourParameters_CreatesSingleConstructor() { //Assign Type type = typeof(StubFourParameters); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); Assert.AreEqual(4, result.First().Key.GetParameters().Length); } [Test] public void CreateConstructorDelegates_GenericClassNoGenericParam_CreatesSingleConstructor() { //Assign Type type = typeof(StubWithGeneric<>); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(0, result.Count); } [Test] public void CreateConstructorDelegates_GenericClassWithGenericParam_CreatesSingleConstructor() { //Assign Type type = typeof(StubWithGeneric<string>); //Act var result = Utilities.CreateConstructorDelegates(type); //Assert Assert.AreEqual(1, result.Count); } #endregion #region Method - GetProperty [Test] public void GetProperty_GetPropertyOnClass_ReturnsProperty() { //Assign string name = "Property"; Type type = typeof (StubClass); //Act var result = Utilities.GetProperty(type, name); //Assert Assert.IsNotNull(result); Assert.AreEqual(name, result.Name); } [Test] public void GetProperty_GetPropertyOnSubClass_ReturnsProperty() { //Assign string name = "Property"; Type type = typeof(StubSubClass); //Act var result = Utilities.GetProperty(type, name); //Assert Assert.IsNotNull(result); Assert.AreEqual(name, result.Name); } [Test] public void GetProperty_GetPropertyOnInterface_ReturnsProperty() { //Assign string name = "Property"; Type type = typeof (StubInterface); //Act var result = Utilities.GetProperty(type, name); //Assert Assert.IsNotNull(result); Assert.AreEqual(name, result.Name); } [Test] public void GetProperty_GetPropertyOnSubInterface_ReturnsProperty() { //Assign string name = "Property"; Type type = typeof(StubSubInterface); //Act var result = Utilities.GetProperty(type, name); //Assert Assert.IsNotNull(result); Assert.AreEqual(name, result.Name); } #endregion #region Stubs public class StubWithGeneric<T> { public StubWithGeneric() { } } public class StubNoParameters { public StubNoParameters() { } } public class StubOneParameter { public string Param1 { get; set; } public StubOneParameter(string param1) { Param1 = param1; } } public class StubTwoParameters { public string Param1 { get; set; } public int Param2 { get; set; } public StubTwoParameters(string param1, int param2) { Param1 = param1; Param2 = param2; } } public class StubThreeParameters { public StubThreeParameters(string param1, string param2, string param3) { } } public class StubFourParameters { public StubFourParameters(string param1, string param2, string param3, string param4) { } } public class StubFiveParameters { public StubFiveParameters(string param1, string param2, string param3, string param4, string param5) { } } public class StubClass { public string Property { get; set; } } public class StubSubClass : StubClass { } public interface StubInterface { string Property { get; set; } } public interface StubSubInterface : StubInterface { } #endregion } }
/*============================================================================== Copyright (c) 2012 QUALCOMM Austria Research Center GmbH. All Rights Reserved. Qualcomm Confidential and Proprietary ==============================================================================*/ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; public class MarkerTracker : Tracker { #region PRIVATE_MEMBER_VARIABLES // Dictionary that contains Markers. private Dictionary<int, MarkerBehaviour> mMarkerBehaviourDict = new Dictionary<int, MarkerBehaviour>(); #endregion // PRIVATE_MEMBER_VARIABLES #region PUBLIC_METHODS // Starts the tracker. // The tracker needs to be stopped before Trackables can be modified. public override bool Start() { if (markerTrackerStart() == 0) { Debug.LogError("Could not start tracker."); return false; } return true; } // Stops the tracker. // The tracker needs to be stopped before Trackables can be modified. public override void Stop() { markerTrackerStop(); } // Creates a marker with the given id, name, and size. // Registers the marker at native code. // Returns a MarkerBehaviour object to receive updates. public MarkerBehaviour CreateMarker(int markerID, String trackableName, float size) { int trackableID = RegisterMarker(markerID, trackableName, size); if (trackableID == -1) { Debug.LogError("Could not create marker with id " + markerID + "."); return null; } // Alternatively instantiate Trackable Prefabs. GameObject markerObject = new GameObject(); MarkerBehaviour newMB = markerObject.AddComponent<MarkerBehaviour>(); Debug.Log("Creating Marker with values: " + "\n MarkerID: " + markerID + "\n TrackableID: " + trackableID + "\n Name: " + trackableName + "\n Size: " + size + "x" + size); newMB.InitializeID(trackableID); newMB.MarkerID = markerID; newMB.TrackableName = trackableName; newMB.transform.localScale = new Vector3(size, size, size); // Add newly created Marker to dictionary. mMarkerBehaviourDict[trackableID] = newMB; return newMB; } // Creates a marker with the given id, name, and size. // Registers the marker at native code. // Returns the unique trackable id. public int RegisterMarker(int markerID, String trackableName, float size) { int result = markerTrackerCreateMarker(markerID, trackableName, size); // Tell QCARManager to reinitialize its trackable array. QCARManager.Instance.Reinit(); return result; } // Destroys the marker associated with the given MarkerBehaviour // at native code. public bool DestroyMarker(MarkerBehaviour marker, bool destroyGameObject) { if (markerTrackerDestroyMarker(marker.TrackableID) == 0) { Debug.LogError("Could not destroy marker with id " + marker.MarkerID + "."); return false; } mMarkerBehaviourDict.Remove(marker.TrackableID); if (destroyGameObject) { GameObject.Destroy(marker.gameObject); } // Tell QCARManager to reinitialize its trackable array. QCARManager.Instance.Reinit(); return true; } // Returns the total number of markers registered at native. public int GetNumMarkers() { return markerTrackerGetNumMarkers(); } // Returns the Marker at the given index. public MarkerBehaviour GetMarker(int index) { Dictionary<int, MarkerBehaviour>.Enumerator enumerator = mMarkerBehaviourDict.GetEnumerator(); MarkerBehaviour mb = null; for (int i = 0; i <= index; ++i) { if (!enumerator.MoveNext()) { Debug.LogError("Marker index invalid."); mb = null; break; } mb = enumerator.Current.Value; } return mb; } // Returns the Marker with the given unique ID. // Unique IDs for Markers are created when markers are registered. public bool TryGetMarkerByID(int id, out MarkerBehaviour marker) { return mMarkerBehaviourDict.TryGetValue(id, out marker); } public void AddMarkers(MarkerBehaviour[] markerBehaviours) { foreach (MarkerBehaviour marker in markerBehaviours) { if (marker.TrackableName == null) { Debug.LogError("Found Marker without name."); continue; } int id = RegisterMarker(marker.MarkerID, marker.TrackableName, marker.GetSize().x); if (id == -1) { Debug.LogWarning("Marker named " + marker.TrackableName + " could not be registered, disabling."); marker.enabled = false; } else { marker.InitializeID(id); if (!mMarkerBehaviourDict.ContainsKey(id)) { mMarkerBehaviourDict[id] = marker; Debug.Log("Found Marker named " + marker.TrackableName + " with id " + marker.TrackableID); } marker.enabled = true; } } } public void DestroyAllMarkers(bool destroyGameObject) { int numMarkers = GetNumMarkers(); for (int i = 0; i < numMarkers; i++) { MarkerBehaviour marker = GetMarker(i); if (markerTrackerDestroyMarker(marker.TrackableID) == 0) { Debug.LogError("Could not destroy marker with id " + marker.MarkerID + "."); } if (destroyGameObject) { GameObject.Destroy(marker.gameObject); } } mMarkerBehaviourDict.Clear(); // Tell QCARManager to reinitialize its trackable array. QCARManager.Instance.Reinit(); } public void RemoveDisabledTrackablesFromQueue(ref LinkedList<int> trackableIDs) { LinkedListNode<int> idNode = trackableIDs.First; while (idNode != null) { LinkedListNode<int> next = idNode.Next; MarkerBehaviour markerBehaviour; if (TryGetMarkerByID(idNode.Value, out markerBehaviour)) { if (markerBehaviour.enabled == false) { trackableIDs.Remove(idNode); } } idNode = next; } } public void UpdateCameraPose(Camera arCamera, QCARManager.TrackableData[] trackableDataArray, int originTrackableID) { // If there is a World Center Trackable use it to position the camera. if (originTrackableID >= 0) { foreach (QCARManager.TrackableData trackableData in trackableDataArray) { if (trackableData.id == originTrackableID) { if (trackableData.status == TrackableBehaviour.Status.DETECTED || trackableData.status == TrackableBehaviour.Status.TRACKED) { MarkerBehaviour originTrackable = null; if (TryGetMarkerByID(originTrackableID, out originTrackable)) { if (originTrackable.enabled) { PositionCamera(originTrackable, arCamera, trackableData.pose); } } } break; } } } } // Method used to update poses of all active Markers // in the scene public void UpdateTrackablePoses(Camera arCamera, QCARManager.TrackableData[] trackableDataArray, int originTrackableID) { foreach (QCARManager.TrackableData trackableData in trackableDataArray) { // For each Trackable data struct from native MarkerBehaviour markerBehaviour; if (TryGetMarkerByID(trackableData.id, out markerBehaviour)) { // If this is the world center skip it, we never move the // world center Trackable in the scene if (trackableData.id == originTrackableID) { continue; } if ((trackableData.status == TrackableBehaviour.Status.DETECTED || trackableData.status == TrackableBehaviour.Status.TRACKED) && markerBehaviour.enabled) { // The Trackable object is visible and enabled, // move it into position in relation to the camera // (which we moved earlier) PositionTrackable(markerBehaviour, arCamera, trackableData.pose); } } } // Update each Trackable // Do this once all Trackables have been moved into place foreach (QCARManager.TrackableData trackableData in trackableDataArray) { MarkerBehaviour markerBehaviour; if (TryGetMarkerByID(trackableData.id, out markerBehaviour)) { if (markerBehaviour.enabled) { markerBehaviour.OnTrackerUpdate( trackableData.status); } } } } #endregion // PUBLIC_METHODS #region NATIVE_FUNCTIONS #if !UNITY_EDITOR [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerTrackerStart(); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern void markerTrackerStop(); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerTrackerCreateMarker(int id, String trackableName, float size); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerTrackerDestroyMarker(int trackableId); [DllImport(QCARMacros.PLATFORM_DLL)] private static extern int markerTrackerGetNumMarkers(); #else // !UNITY_EDITOR private static int markerTrackerStart() { return 0; } private static void markerTrackerStop() { } private static int markerTrackerCreateMarker(int id, String trackableName, float size) { return 0; } private static int markerTrackerDestroyMarker(int trackableIndex) { return 0; } private static int markerTrackerGetNumMarkers() { return 0; } #endif // !UNITY_EDITOR #endregion // NATIVE_FUNCTIONS }
// 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.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.IO.Tests { [PlatformSpecific(TestPlatforms.Windows)] public partial class PathTests_Windows : PathTestsBase { [Fact] public void GetDirectoryName_DevicePath() { if (PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\?\C:", Path.GetDirectoryName(@"\\?\C:\foo")); } else { Assert.Equal(@"\\?\C:\", Path.GetDirectoryName(@"\\?\C:\foo")); } } [Theory, MemberData(nameof(TestData_GetDirectoryName_Windows))] public void GetDirectoryName(string path, string expected) { Assert.Equal(expected, Path.GetDirectoryName(path)); } [Theory, InlineData("B:", ""), InlineData("A:.", ".")] public static void GetFileName_Volume(string path, string expected) { // With a valid drive letter followed by a colon, we have a root, but only on Windows. Assert.Equal(expected, Path.GetFileName(path)); } [ActiveIssue(27552)] [Theory, MemberData(nameof(TestData_GetPathRoot_Windows)), MemberData(nameof(TestData_GetPathRoot_Unc)), MemberData(nameof(TestData_GetPathRoot_DevicePaths))] public void GetPathRoot_Windows(string value, string expected) { Assert.Equal(expected, Path.GetPathRoot(value)); if (value.Length != expected.Length) { // The string overload normalizes the separators Assert.Equal(expected, Path.GetPathRoot(value.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))); // UNCs and device paths will have their semantics changed if we double up separators if (!value.StartsWith(@"\\")) Assert.Equal(expected, Path.GetPathRoot(value.Replace(@"\", @"\\"))); } } public static IEnumerable<string[]> GetTempPath_SetEnvVar_Data() { yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp" }; yield return new string[] { @"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\" }; yield return new string[] { @"C:\", @"C:\" }; yield return new string[] { @"C:\tmp\", @"C:\tmp" }; yield return new string[] { @"C:\tmp\", @"C:\tmp\" }; } [Fact] public void GetTempPath_SetEnvVar() { RemoteExecutor.Invoke(() => { foreach (string[] tempPath in GetTempPath_SetEnvVar_Data()) { GetTempPath_SetEnvVar("TMP", tempPath[0], tempPath[1]); } }).Dispose(); } [Theory, MemberData(nameof(TestData_Spaces))] public void GetFullPath_TrailingSpacesCut(string component) { // Windows cuts off any simple white space added to a path string path = "C:\\Test" + component; Assert.Equal("C:\\Test", Path.GetFullPath(path)); } [Fact] public void GetFullPath_NormalizedLongPathTooLong() { // Try out a long path that normalizes down to more than MaxPath string curDir = Directory.GetCurrentDirectory(); const int Iters = 260; var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4)); for (int i = 0; i < Iters; i++) { longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.'); } if (PathFeatures.AreAllLongPathsAvailable()) { // Now no longer throws unless over ~32K Assert.NotNull(Path.GetFullPath(longPath.ToString())); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(longPath.ToString())); } } [Theory, InlineData(@"C:..."), InlineData(@"C:...\somedir"), InlineData(@"\.. .\"), InlineData(@"\. .\"), InlineData(@"\ .\")] public void GetFullPath_LegacyArgumentExceptionPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // We didn't allow these paths on < 4.6.2 AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { // These paths are legitimate Windows paths that can be created without extended syntax. // We now allow them through. Path.GetFullPath(path); } } [Fact] public void GetFullPath_MaxPathNotTooLong() { string value = @"C:\" + new string('a', 255) + @"\"; if (PathFeatures.AreAllLongPathsAvailable()) { // Shouldn't throw anymore Path.GetFullPath(value); } else { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(value)); } } [Fact] public void GetFullPath_PathTooLong() { Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\")); } [Theory, InlineData(@"C:\", @"C:\"), InlineData(@"C:\.", @"C:\"), InlineData(@"C:\..", @"C:\"), InlineData(@"C:\..\..", @"C:\"), InlineData(@"C:\A\..", @"C:\"), InlineData(@"C:\..\..\A\..", @"C:\")] public void GetFullPath_RelativeRoot(string path, string expected) { Assert.Equal(Path.GetFullPath(path), expected); } [Fact] public void GetFullPath_StrangeButLegalPaths() { // These are legal and creatable without using extended syntax if you use a trailing slash // (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from // being blocked when they hit these paths. string curDir = Directory.GetCurrentDirectory(); if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy path Path.GetFullePath() ignores . when there is less or more that two, when there is .. in the path it returns one directory up. Assert.Equal( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.Equal( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } else { Assert.NotEqual( Path.GetFullPath(curDir + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar)); Assert.NotEqual( Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar), Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar)); } } [Theory, InlineData(@"\\?\C:\ "), InlineData(@"\\?\C:\ \ "), InlineData(@"\\?\C:\ ."), InlineData(@"\\?\C:\ .."), InlineData(@"\\?\C:\..."), InlineData(@"\\?\GLOBALROOT\"), InlineData(@"\\?\"), InlineData(@"\\?\."), InlineData(@"\\?\.."), InlineData(@"\\?\\"), InlineData(@"\\?\C:\\"), InlineData(@"\\?\C:\|"), InlineData(@"\\?\C:\."), InlineData(@"\\?\C:\.."), InlineData(@"\\?\C:\Foo1\."), InlineData(@"\\?\C:\Foo2\.."), InlineData(@"\\?\UNC\"), InlineData(@"\\?\UNC\server1"), InlineData(@"\\?\UNC\server2\"), InlineData(@"\\?\UNC\server3\\"), InlineData(@"\\?\UNC\server4\.."), InlineData(@"\\?\UNC\server5\share\."), InlineData(@"\\?\UNC\server6\share\.."), InlineData(@"\\?\UNC\a\b\\"), InlineData(@"\\.\"), InlineData(@"\\.\."), InlineData(@"\\.\.."), InlineData(@"\\.\\"), InlineData(@"\\.\C:\\"), InlineData(@"\\.\C:\|"), InlineData(@"\\.\C:\."), InlineData(@"\\.\C:\.."), InlineData(@"\\.\C:\Foo1\."), InlineData(@"\\.\C:\Foo2\..")] public void GetFullPath_ValidExtendedPaths(string path) { if (PathFeatures.IsUsingLegacyPathNormalization()) { // Legacy Path doesn't support any of these paths. AssertExtensions.ThrowsAny<ArgumentException, NotSupportedException>(() => Path.GetFullPath(path)); return; } // None of these should throw if (path.StartsWith(@"\\?\")) { Assert.Equal(path, Path.GetFullPath(path)); } else { Path.GetFullPath(path); } } [Theory, InlineData(@"\\.\UNC\"), InlineData(@"\\.\UNC\LOCALHOST"), InlineData(@"\\.\UNC\localHOST\"), InlineData(@"\\.\UNC\LOcaLHOST\\"), InlineData(@"\\.\UNC\lOCALHOST\.."), InlineData(@"\\.\UNC\LOCALhost\share\."), InlineData(@"\\.\UNC\loCALHOST\share\.."), InlineData(@"\\.\UNC\a\b\\")] public static void GetFullPath_ValidLegacy_ValidExtendedPaths(string path) { // should not throw Path.GetFullPath(path); } [Theory, // https://github.com/dotnet/corefx/issues/11965 InlineData(@"\\LOCALHOST\share\test.txt.~SS", @"\\LOCALHOST\share\test.txt.~SS"), InlineData(@"\\LOCALHOST\share1", @"\\LOCALHOST\share1"), InlineData(@"\\LOCALHOST\share3\dir", @"\\LOCALHOST\share3\dir"), InlineData(@"\\LOCALHOST\share4\.", @"\\LOCALHOST\share4"), InlineData(@"\\LOCALHOST\share5\..", @"\\LOCALHOST\share5"), InlineData(@"\\LOCALHOST\share6\ ", @"\\LOCALHOST\share6\"), InlineData(@"\\LOCALHOST\ share7\", @"\\LOCALHOST\ share7\"), InlineData(@"\\?\UNC\LOCALHOST\share8\test.txt.~SS", @"\\?\UNC\LOCALHOST\share8\test.txt.~SS"), InlineData(@"\\?\UNC\LOCALHOST\share9", @"\\?\UNC\LOCALHOST\share9"), InlineData(@"\\?\UNC\LOCALHOST\shareA\dir", @"\\?\UNC\LOCALHOST\shareA\dir"), InlineData(@"\\?\UNC\LOCALHOST\shareB\. ", @"\\?\UNC\LOCALHOST\shareB\. "), InlineData(@"\\?\UNC\LOCALHOST\shareC\.. ", @"\\?\UNC\LOCALHOST\shareC\.. "), InlineData(@"\\?\UNC\LOCALHOST\shareD\ ", @"\\?\UNC\LOCALHOST\shareD\ "), InlineData(@"\\.\UNC\LOCALHOST\ shareE\", @"\\.\UNC\LOCALHOST\ shareE\"), InlineData(@"\\.\UNC\LOCALHOST\shareF\test.txt.~SS", @"\\.\UNC\LOCALHOST\shareF\test.txt.~SS"), InlineData(@"\\.\UNC\LOCALHOST\shareG", @"\\.\UNC\LOCALHOST\shareG"), InlineData(@"\\.\UNC\LOCALHOST\shareH\dir", @"\\.\UNC\LOCALHOST\shareH\dir"), InlineData(@"\\.\UNC\LOCALHOST\shareK\ ", @"\\.\UNC\LOCALHOST\shareK\"), InlineData(@"\\.\UNC\LOCALHOST\ shareL\", @"\\.\UNC\LOCALHOST\ shareL\")] public void GetFullPath_UNC_Valid(string path, string expected) { if (path.StartsWith(@"\\?\") && PathFeatures.IsUsingLegacyPathNormalization()) { AssertExtensions.Throws<ArgumentException>(null, () => Path.GetFullPath(path)); } else { Assert.Equal(expected, Path.GetFullPath(path)); } } [Theory, InlineData(@"\\.\UNC\LOCALHOST\shareI\. ", @"\\.\UNC\LOCALHOST\shareI\", @"\\.\UNC\LOCALHOST\shareI"), InlineData(@"\\.\UNC\LOCALHOST\shareJ\.. ", @"\\.\UNC\LOCALHOST\shareJ\", @"\\.\UNC\LOCALHOST")] public static void GetFullPath_Windows_UNC_Valid_LegacyPathSupport(string path, string normalExpected, string legacyExpected) { string expected = PathFeatures.IsUsingLegacyPathNormalization() ? legacyExpected : normalExpected; Assert.Equal(expected, Path.GetFullPath(path)); } [Fact] public static void GetFullPath_Windows_83Paths() { // Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened. string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt"); File.Create(tempFilePath).Dispose(); try { // Get its short name var sb = new StringBuilder(260); if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name { string shortName = sb.ToString(); // Make sure the shortened name expands back to the original one // Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); Assert.Equal(tempFilePath, shortName); // Should work with device paths that aren't well-formed extended syntax if (!PathFeatures.IsUsingLegacyPathNormalization()) { Assert.Equal(@"\\.\" + tempFilePath, Path.GetFullPath(@"\\.\" + shortName)); Assert.Equal(@"\\?\" + tempFilePath, Path.GetFullPath(@"//?/" + shortName)); // Shouldn't mess with well-formed extended syntax Assert.Equal(@"\\?\" + shortName, Path.GetFullPath(@"\\?\" + shortName)); } // Validate case where short name doesn't expand to a real file string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp"; Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName)); // Same thing, but with a long path that normalizes down to a short enough one const int Iters = 1000; var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2)); for (int i = 0; i < Iters; i++) { shortLongName.Append(Path.DirectorySeparatorChar).Append('.'); } Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString())); } } finally { File.Delete(tempFilePath); } } // Windows-only P/Invoke to create 8.3 short names from long names [DllImport("kernel32.dll", EntryPoint = "GetShortPathNameW", CharSet = CharSet.Unicode)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SubtractUInt32() { var test = new SimpleBinaryOpTest__SubtractUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SubtractUInt32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<UInt32> _fld1; public Vector256<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SubtractUInt32 testClass) { var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SubtractUInt32 testClass) { fixed (Vector256<UInt32>* pFld1 = &_fld1) fixed (Vector256<UInt32>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SubtractUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public SimpleBinaryOpTest__SubtractUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Subtract( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Subtract( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Subtract), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector256<UInt32>* pClsVar2 = &_clsVar2) { var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(pClsVar1)), Avx.LoadVector256((UInt32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Subtract(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SubtractUInt32(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__SubtractUInt32(); fixed (Vector256<UInt32>* pFld1 = &test._fld1) fixed (Vector256<UInt32>* pFld2 = &test._fld2) { var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<UInt32>* pFld1 = &_fld1) fixed (Vector256<UInt32>* pFld2 = &_fld2) { var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(pFld1)), Avx.LoadVector256((UInt32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Subtract( Avx.LoadVector256((UInt32*)(&test._fld1)), Avx.LoadVector256((UInt32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt32> op1, Vector256<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((uint)(left[0] - right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(left[i] - right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Subtract)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Security { using System.Diagnostics; using System.IO; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.Xml; sealed class SecurityVerifiedMessage : DelegatingMessage { byte[] decryptedBuffer; XmlDictionaryReader cachedDecryptedBodyContentReader; XmlAttributeHolder[] envelopeAttributes; XmlAttributeHolder[] headerAttributes; XmlAttributeHolder[] bodyAttributes; string envelopePrefix; bool bodyDecrypted; BodyState state = BodyState.Created; string bodyPrefix; bool isDecryptedBodyStatusDetermined; bool isDecryptedBodyFault; bool isDecryptedBodyEmpty; XmlDictionaryReader cachedReaderAtSecurityHeader; readonly ReceiveSecurityHeader securityHeader; XmlBuffer messageBuffer; bool canDelegateCreateBufferedCopyToInnerMessage; public SecurityVerifiedMessage(Message messageToProcess, ReceiveSecurityHeader securityHeader) : base(messageToProcess) { this.securityHeader = securityHeader; if (securityHeader.RequireMessageProtection) { XmlDictionaryReader messageReader; BufferedMessage bufferedMessage = this.InnerMessage as BufferedMessage; if (bufferedMessage != null && this.Headers.ContainsOnlyBufferedMessageHeaders) { messageReader = bufferedMessage.GetMessageReader(); } else { this.messageBuffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = this.messageBuffer.OpenSection(this.securityHeader.ReaderQuotas); this.InnerMessage.WriteMessage(writer); this.messageBuffer.CloseSection(); this.messageBuffer.Close(); messageReader = this.messageBuffer.GetReader(0); } MoveToSecurityHeader(messageReader, securityHeader.HeaderIndex, true); this.cachedReaderAtSecurityHeader = messageReader; this.state = BodyState.Buffered; } else { this.envelopeAttributes = XmlAttributeHolder.emptyArray; this.headerAttributes = XmlAttributeHolder.emptyArray; this.bodyAttributes = XmlAttributeHolder.emptyArray; this.canDelegateCreateBufferedCopyToInnerMessage = true; } } public override bool IsEmpty { get { if (this.IsDisposed) { // PreSharp Bug: Property get methods should not throw exceptions. #pragma warning suppress 56503 throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); } if (!this.bodyDecrypted) { return this.InnerMessage.IsEmpty; } EnsureDecryptedBodyStatusDetermined(); return this.isDecryptedBodyEmpty; } } public override bool IsFault { get { if (this.IsDisposed) { // PreSharp Bug: Property get methods should not throw exceptions. #pragma warning suppress 56503 throw TraceUtility.ThrowHelperError(CreateMessageDisposedException(), this); } if (!this.bodyDecrypted) { return this.InnerMessage.IsFault; } EnsureDecryptedBodyStatusDetermined(); return this.isDecryptedBodyFault; } } internal byte[] PrimarySignatureValue { get { return this.securityHeader.PrimarySignatureValue; } } internal ReceiveSecurityHeader ReceivedSecurityHeader { get { return this.securityHeader; } } Exception CreateBadStateException(string operation) { return new InvalidOperationException(SR.GetString(SR.MessageBodyOperationNotValidInBodyState, operation, this.state)); } public XmlDictionaryReader CreateFullBodyReader() { switch (this.state) { case BodyState.Buffered: return CreateFullBodyReaderFromBufferedState(); case BodyState.Decrypted: return CreateFullBodyReaderFromDecryptedState(); default: throw TraceUtility.ThrowHelperError(CreateBadStateException("CreateFullBodyReader"), this); } } XmlDictionaryReader CreateFullBodyReaderFromBufferedState() { if (this.messageBuffer != null) { XmlDictionaryReader reader = this.messageBuffer.GetReader(0); MoveToBody(reader); return reader; } else { return ((BufferedMessage) this.InnerMessage).GetBufferedReaderAtBody(); } } XmlDictionaryReader CreateFullBodyReaderFromDecryptedState() { XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(this.decryptedBuffer, 0, this.decryptedBuffer.Length, this.securityHeader.ReaderQuotas); MoveToBody(reader); return reader; } void EnsureDecryptedBodyStatusDetermined() { if (!this.isDecryptedBodyStatusDetermined) { XmlDictionaryReader reader = CreateFullBodyReader(); if (Message.ReadStartBody(reader, this.InnerMessage.Version.Envelope, out this.isDecryptedBodyFault, out this.isDecryptedBodyEmpty)) { this.cachedDecryptedBodyContentReader = reader; } else { reader.Close(); } this.isDecryptedBodyStatusDetermined = true; } } public XmlAttributeHolder[] GetEnvelopeAttributes() { return this.envelopeAttributes; } public XmlAttributeHolder[] GetHeaderAttributes() { return this.headerAttributes; } XmlDictionaryReader GetReaderAtEnvelope() { if (this.messageBuffer != null) { return this.messageBuffer.GetReader(0); } else { return ((BufferedMessage) this.InnerMessage).GetMessageReader(); } } public XmlDictionaryReader GetReaderAtFirstHeader() { XmlDictionaryReader reader = GetReaderAtEnvelope(); MoveToHeaderBlock(reader, false); reader.ReadStartElement(); return reader; } public XmlDictionaryReader GetReaderAtSecurityHeader() { if (this.cachedReaderAtSecurityHeader != null) { XmlDictionaryReader result = this.cachedReaderAtSecurityHeader; this.cachedReaderAtSecurityHeader = null; return result; } return this.Headers.GetReaderAtHeader(this.securityHeader.HeaderIndex); } void MoveToBody(XmlDictionaryReader reader) { if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } reader.ReadStartElement(); if (reader.IsStartElement(XD.MessageDictionary.Header, this.Version.Envelope.DictionaryNamespace)) { reader.Skip(); } if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } } void MoveToHeaderBlock(XmlDictionaryReader reader, bool captureAttributes) { if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } if (captureAttributes) { this.envelopePrefix = reader.Prefix; this.envelopeAttributes = XmlAttributeHolder.ReadAttributes(reader); } reader.ReadStartElement(); reader.MoveToStartElement(XD.MessageDictionary.Header, this.Version.Envelope.DictionaryNamespace); if (captureAttributes) { this.headerAttributes = XmlAttributeHolder.ReadAttributes(reader); } } void MoveToSecurityHeader(XmlDictionaryReader reader, int headerIndex, bool captureAttributes) { MoveToHeaderBlock(reader, captureAttributes); reader.ReadStartElement(); while (true) { if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } if (headerIndex == 0) { break; } reader.Skip(); headerIndex--; } } protected override void OnBodyToString(XmlDictionaryWriter writer) { if (this.state == BodyState.Created) { base.OnBodyToString(writer); } else { OnWriteBodyContents(writer); } } protected override void OnClose() { if (this.cachedDecryptedBodyContentReader != null) { try { this.cachedDecryptedBodyContentReader.Close(); } catch (System.IO.IOException exception) { // // We only want to catch and log the I/O exception here // assuming reader only throw those exceptions // DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning); } finally { this.cachedDecryptedBodyContentReader = null; } } if (this.cachedReaderAtSecurityHeader != null) { try { this.cachedReaderAtSecurityHeader.Close(); } catch (System.IO.IOException exception) { // // We only want to catch and log the I/O exception here // assuming reader only throw those exceptions // DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning); } finally { this.cachedReaderAtSecurityHeader = null; } } this.messageBuffer = null; this.decryptedBuffer = null; this.state = BodyState.Disposed; this.InnerMessage.Close(); } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { if (this.state == BodyState.Created) { return this.InnerMessage.GetReaderAtBodyContents(); } if (this.bodyDecrypted) { EnsureDecryptedBodyStatusDetermined(); } if (this.cachedDecryptedBodyContentReader != null) { XmlDictionaryReader result = this.cachedDecryptedBodyContentReader; this.cachedDecryptedBodyContentReader = null; return result; } else { XmlDictionaryReader reader = CreateFullBodyReader(); reader.ReadStartElement(); reader.MoveToContent(); return reader; } } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { if (this.canDelegateCreateBufferedCopyToInnerMessage && this.InnerMessage is BufferedMessage) { return this.InnerMessage.CreateBufferedCopy(maxBufferSize); } else { return base.OnCreateBufferedCopy(maxBufferSize); } } internal void OnMessageProtectionPassComplete(bool atLeastOneHeaderOrBodyEncrypted) { this.canDelegateCreateBufferedCopyToInnerMessage = !atLeastOneHeaderOrBodyEncrypted; } internal void OnUnencryptedPart(string name, string ns) { if (ns == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotEncrypted, name)), this); } else { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotEncryptedNs, name, ns)), this); } } internal void OnUnsignedPart(string name, string ns) { if (ns == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotSigned, name)), this); } else { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.RequiredMessagePartNotSignedNs, name, ns)), this); } } protected override void OnWriteStartBody(XmlDictionaryWriter writer) { if (this.state == BodyState.Created) { this.InnerMessage.WriteStartBody(writer); return; } XmlDictionaryReader reader = CreateFullBodyReader(); reader.MoveToContent(); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); reader.Close(); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { if (this.state == BodyState.Created) { this.InnerMessage.WriteBodyContents(writer); return; } XmlDictionaryReader reader = CreateFullBodyReader(); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) writer.WriteNode(reader, false); reader.ReadEndElement(); reader.Close(); } public void SetBodyPrefixAndAttributes(XmlDictionaryReader bodyReader) { this.bodyPrefix = bodyReader.Prefix; this.bodyAttributes = XmlAttributeHolder.ReadAttributes(bodyReader); } public void SetDecryptedBody(byte[] decryptedBodyContent) { if (this.state != BodyState.Buffered) { throw TraceUtility.ThrowHelperError(CreateBadStateException("SetDecryptedBody"), this); } MemoryStream stream = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream); writer.WriteStartElement(this.envelopePrefix, XD.MessageDictionary.Envelope, this.Version.Envelope.DictionaryNamespace); XmlAttributeHolder.WriteAttributes(this.envelopeAttributes, writer); writer.WriteStartElement(this.bodyPrefix, XD.MessageDictionary.Body, this.Version.Envelope.DictionaryNamespace); XmlAttributeHolder.WriteAttributes(this.bodyAttributes, writer); writer.WriteString(" "); // ensure non-empty element writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); this.decryptedBuffer = ContextImportHelper.SpliceBuffers(decryptedBodyContent, stream.GetBuffer(), (int) stream.Length, 2); this.bodyDecrypted = true; this.state = BodyState.Decrypted; } enum BodyState { Created, Buffered, Decrypted, Disposed, } } // Adding wrapping tags using a writer is a temporary feature to // support interop with a partner. Eventually, the serialization // team will add a feature to XmlUTF8TextReader to directly // support the addition of outer namespaces before creating a // Reader. This roundabout way of supporting context-sensitive // decryption can then be removed. static class ContextImportHelper { internal static XmlDictionaryReader CreateSplicedReader(byte[] decryptedBuffer, XmlAttributeHolder[] outerContext1, XmlAttributeHolder[] outerContext2, XmlAttributeHolder[] outerContext3, XmlDictionaryReaderQuotas quotas) { const string wrapper1 = "x"; const string wrapper2 = "y"; const string wrapper3 = "z"; const int wrappingDepth = 3; MemoryStream stream = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream); writer.WriteStartElement(wrapper1); WriteNamespaceDeclarations(outerContext1, writer); writer.WriteStartElement(wrapper2); WriteNamespaceDeclarations(outerContext2, writer); writer.WriteStartElement(wrapper3); WriteNamespaceDeclarations(outerContext3, writer); writer.WriteString(" "); // ensure non-empty element writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); byte[] splicedBuffer = SpliceBuffers(decryptedBuffer, stream.GetBuffer(), (int) stream.Length, wrappingDepth); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(splicedBuffer, quotas); reader.ReadStartElement(wrapper1); reader.ReadStartElement(wrapper2); reader.ReadStartElement(wrapper3); if (reader.NodeType != XmlNodeType.Element) { reader.MoveToContent(); } return reader; } internal static string GetPrefixIfNamespaceDeclaration(string prefix, string localName) { if (prefix == "xmlns") { return localName; } if (prefix.Length == 0 && localName == "xmlns") { return string.Empty; } return null; } static bool IsNamespaceDeclaration(string prefix, string localName) { return GetPrefixIfNamespaceDeclaration(prefix, localName) != null; } internal static byte[] SpliceBuffers(byte[] middle, byte[] wrapper, int wrapperLength, int wrappingDepth) { const byte openChar = (byte) '<'; int openCharsFound = 0; int openCharIndex; for (openCharIndex = wrapperLength - 1; openCharIndex >= 0; openCharIndex--) { if (wrapper[openCharIndex] == openChar) { openCharsFound++; if (openCharsFound == wrappingDepth) { break; } } } Fx.Assert(openCharIndex > 0, ""); byte[] splicedBuffer = DiagnosticUtility.Utility.AllocateByteArray(checked(middle.Length + wrapperLength - 1)); int offset = 0; int count = openCharIndex - 1; Buffer.BlockCopy(wrapper, 0, splicedBuffer, offset, count); offset += count; count = middle.Length; Buffer.BlockCopy(middle, 0, splicedBuffer, offset, count); offset += count; count = wrapperLength - openCharIndex; Buffer.BlockCopy(wrapper, openCharIndex, splicedBuffer, offset, count); return splicedBuffer; } static void WriteNamespaceDeclarations(XmlAttributeHolder[] attributes, XmlWriter writer) { if (attributes != null) { for (int i = 0; i < attributes.Length; i++) { XmlAttributeHolder a = attributes[i]; if (IsNamespaceDeclaration(a.Prefix, a.LocalName)) { a.WriteTo(writer); } } } } } }
using System; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Windows; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using MaterialDesignThemes.Wpf; using Slamby.SDK.Net.Models; using Slamby.TAU.Design; using Slamby.TAU.Enum; using Slamby.TAU.Helper; using Slamby.TAU.Model; using System.Reflection; using System.Collections.Concurrent; using System.Diagnostics; using System.Timers; using System.Windows.Controls; using Slamby.TAU.Logger; using System.Windows.Input; using System.Windows.Media; using Dragablz; using Dragablz.Dockablz; using Slamby.TAU.Resources; using GalaSoft.MvvmLight.Threading; using Slamby.TAU.View; using FontAwesome.WPF; using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; using Slamby.SDK.Net.Helpers; using Slamby.SDK.Net.Managers.Interfaces; using Slamby.SDK.Net.Models.Enums; using MenuItem = Slamby.TAU.Model.MenuItem; using Process = Slamby.SDK.Net.Models.Process; namespace Slamby.TAU.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel(IProcessManager processManager, DialogHandler dialogHandler) { IsEnable = false; Mouse.SetCursor(Cursors.Wait); _processManager = processManager; _dialogHandler = dialogHandler; if (Application.Current != null) Application.Current.DispatcherUnhandledException += DispatcherUnhandledException; if (Properties.Settings.Default.UpdateSettings) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpdateSettings = false; Properties.Settings.Default.Save(); } Messenger.Default.Register<StatusMessage>(this, sm => { Messages += $"{sm.Timestamp.ToString("yy.MM.dd. HH:mm:ss")} -- {sm.Message}{Environment.NewLine}"; }); Messenger.Default.Register<UpdateMessage>(this, message => { switch (message.UpdateType) { case UpdateType.NewProcessCreated: var currentProcess = (Process)message.Parameter; currentProcess.Start = currentProcess.Start.ToLocalTime(); currentProcess.End = currentProcess.End.ToLocalTime(); DispatcherHelper.CheckBeginInvokeOnUI(() => ActiveProcessesList.Add(currentProcess)); break; case UpdateType.OpenNewTab: var newTab = (HeaderedItemViewModel)message.Parameter; Tabs.Add(newTab); SelectedTab = newTab; break; case UpdateType.DatasetRename: var oldName = message.Parameter.ToString(); var tabsToClose = Tabs.Where(t => t.Header.ToString() == oldName + " -Data").ToList(); foreach (var tab in tabsToClose) { Tabs.Remove(tab); } break; } }); IsInSettingsMode = false; ChangeSettingsModeCommand = new RelayCommand(() => IsInSettingsMode = !IsInSettingsMode); RefreshCommand = new RelayCommand(async () => { Log.Info(LogMessages.MainRefreshCommand); await ((ViewModelLocator)App.Current.Resources["Locator"]).EndpointUpdate(); }); AboutCommand = new RelayCommand(async () => { var version = Assembly.GetExecutingAssembly().GetName().Version; var sdkVersion = Assembly.LoadFrom("Slamby.SDK.Net.dll").GetName().Version; var apiVersion = Version.Parse(SimpleIoc.Default.GetInstance<ResourcesMonitorViewModel>().EndPointStatus.Status.ApiVersion); await _dialogHandler.Show(new CommonDialog { DataContext = new CommonDialogViewModel { Header = "About", Content = $"Tau version: {version.Major}.{version.Minor}.{version.Build}{Environment.NewLine}SDK version: {sdkVersion.Major}.{sdkVersion.Minor}.{sdkVersion.Build}{Environment.NewLine}Api version: {apiVersion.Major}.{apiVersion.Minor}.{apiVersion.Build}", Buttons = ButtonsEnum.Ok } }, "RootDialog"); }); HelpCommand = new RelayCommand(() => { System.Diagnostics.Process.Start("http://developers.slamby.com"); }); SizeChangedCommand = new RelayCommand(() => { if (LogWindowIsOpen) { LogWindowIsOpen = false; LogWindowIsOpen = true; } }); DoubleClickCommand = new RelayCommand(() => { object content = null; switch (SelectedMenuItem.Name.ToLower()) { case "datasets": content = new ManageDataSet(); break; case "services": content = new ManageService(); break; case "processes": content = new ManageProcess(); break; case "resourcesmonitor": content = new ResourcesMonitor(); break; } Messenger.Default.Send(new UpdateMessage(UpdateType.OpenNewTab, new HeaderedItemViewModel(SelectedMenuItem.Name, content, true))); }); ExpandStatusCommand = new RelayCommand(() => Messenger.Default.Send(new UpdateMessage(UpdateType.OpenNewTab, new HeaderedItemViewModel("ResourcesMonitor", new ResourcesMonitor(), true)))); RefreshProcessCommand = new RelayCommand<string>(async id => { if (string.IsNullOrEmpty(id)) return; try { var processResponse = await _processManager.GetProcessAsync(id); if (ResponseValidator.Validate(processResponse)) { var selectedItem = ActiveProcessesList.FirstOrDefault(p => p.Id == id); if (selectedItem != null) { ActiveProcessesList[ActiveProcessesList.IndexOf(selectedItem)] = processResponse.ResponseObject; ActiveProcessesList = new ObservableCollection<Process>(ActiveProcessesList); if (processResponse.ResponseObject.Status != ProcessStatusEnum.InProgress) { Task.Run(async () => { await Task.Delay(20000); DispatcherHelper.CheckBeginInvokeOnUI(() => { var itemToRemove = ActiveProcessesList.FirstOrDefault(p => p.Id == id); if (itemToRemove != null) ActiveProcessesList.Remove(itemToRemove); }); }); } } } } catch (Exception exception) { Messenger.Default.Send(exception); } }); CancelProcessCommand = new RelayCommand<Process>(async process => { var processResponse = await _processManager.CancelProcessAsync(process.Id); if (ResponseValidator.Validate(processResponse)) { var selectedItem = ActiveProcessesList.FirstOrDefault(p => p.Id == process.Id); if (selectedItem != null) { selectedItem.Status = ProcessStatusEnum.Cancelled; ActiveProcessesList = new ObservableCollection<Process>(ActiveProcessesList); Task.Run(async () => { await Task.Delay(20000); DispatcherHelper.CheckBeginInvokeOnUI(() => { var itemToRemove = ActiveProcessesList.FirstOrDefault(p => p.Id == process.Id); if (itemToRemove != null) ActiveProcessesList.Remove(itemToRemove); }); }); } } }); SelectionChangedCommand = new RelayCommand(() => { Mouse.SetCursor(Cursors.Wait); }); InitData(); Tabs = new ObservableCollection<HeaderedItemViewModel> { new HeaderedItemViewModel("DataSet", new ManageDataSet(), true) }; SelectedTab = Tabs.First(); } private void DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { DispatcherHelper.CheckBeginInvokeOnUI(() => Messenger.Default.Send(e.Exception)); e.Handled = true; } public RelayCommand SelectionChangedCommand { get; private set; } public RelayCommand DoubleClickCommand { get; private set; } public RelayCommand ExpandStatusCommand { get; private set; } public RelayCommand<string> RefreshProcessCommand { get; private set; } public RelayCommand<Process> CancelProcessCommand { get; private set; } private bool _isEnable; public bool IsEnable { get { return _isEnable; } set { Set(() => IsEnable, ref _isEnable, value); } } private ObservableCollection<Process> _activeProcessesList = new ObservableCollection<Process>(); public ObservableCollection<Process> ActiveProcessesList { get { return _activeProcessesList; } set { Set(() => ActiveProcessesList, ref _activeProcessesList, value); } } private async Task InitData() { try { var processResponse = await _processManager.GetProcessesAsync(); if (ResponseValidator.Validate(processResponse)) { ActiveProcessesList = new ObservableCollection<Process>( processResponse.ResponseObject.Where(p => p.Status == ProcessStatusEnum.InProgress)); } MenuItems = new ObservableCollection<MenuItem>(); InitMenuItems(); DataSets = ServiceLocator.Current.GetInstance<ManageDataSetViewModel>().DataSets; } catch (Exception exception) { DispatcherHelper.CheckBeginInvokeOnUI(() => Messenger.Default.Send(exception)); } finally { Mouse.SetCursor(Cursors.Arrow); IsEnable = true; } } private void InitMenuItems() { MenuItems.Clear(); MenuItems.Add(new MenuItem { Name = "DataSets", Icon = ImageAwesome.CreateImageSource(FontAwesomeIcon.Database, Brushes.WhiteSmoke), Content = new ManageDataSet() }); //MenuItems.Add(new MenuItem //{ // Name = "Data", // Icon = ImageAwesome.CreateImageSource(FontAwesomeIcon.FilesOutline, Brushes.WhiteSmoke), // Content = new ManageData() //}); MenuItems.Add(new MenuItem { Name = "Services", Icon = ImageAwesome.CreateImageSource(FontAwesomeIcon.Tasks, Brushes.WhiteSmoke), Content = new ManageService() }); MenuItems.Add(new MenuItem { Name = "Processes", Icon = ImageAwesome.CreateImageSource(FontAwesomeIcon.Spinner, Brushes.WhiteSmoke), Content = new ManageProcess() }); MenuItems.Add(new MenuItem { Name = "ResourcesMonitor", Icon = ImageAwesome.CreateImageSource(FontAwesomeIcon.AreaChart, Brushes.WhiteSmoke), Content = new ResourcesMonitor() }); } private IProcessManager _processManager; private IDataSetManager _dataSetManager; private DialogHandler _dialogHandler; private ObservableCollection<MenuItem> _menuItems; public ObservableCollection<MenuItem> MenuItems { get { return _menuItems; } set { Set(() => MenuItems, ref _menuItems, value); } } private MenuItem _selectedMenuItem; public MenuItem SelectedMenuItem { get { return _selectedMenuItem; } set { Set(() => SelectedMenuItem, ref _selectedMenuItem, value); } } private ObservableCollection<DataSet> _dataSets; public ObservableCollection<DataSet> DataSets { get { return _dataSets; } set { Set(() => DataSets, ref _dataSets, value); } } private bool _isInSettingsMode; public bool IsInSettingsMode { get { return _isInSettingsMode; } set { Set(() => IsInSettingsMode, ref _isInSettingsMode, value); } } public RelayCommand ChangeSettingsModeCommand { get; private set; } public RelayCommand RefreshCommand { get; private set; } public RelayCommand AboutCommand { get; private set; } public RelayCommand HelpCommand { get; private set; } private bool _logWindowIsOpen; public bool LogWindowIsOpen { get { return _logWindowIsOpen; } set { if (Set(() => LogWindowIsOpen, ref _logWindowIsOpen, value)) { if (value) { RawMessagePublisher.Instance.AddSubscriber(_debugSubscriber); } else { RawMessagePublisher.Instance.RemoveSubscriber(_debugSubscriber); } } } } private Logger.DebugSubscriber _debugSubscriber = new Logger.DebugSubscriber(); private string _messages = ""; public string Messages { get { return _messages; } set { Set(() => Messages, ref _messages, value); } } public RelayCommand SizeChangedCommand { get; private set; } private Status _status = new Status(); public Status Status { get { return _status; } set { Set(() => Status, ref _status, value); } } private IInterTabClient _interTabClient = new InterTabClient(); public IInterTabClient InterTabClient { get { return _interTabClient; } set { Set(() => InterTabClient, ref _interTabClient, value); } } public ItemActionCallback ClosingTabItemHandler => ClosingTabItemHandlerImpl; private static void ClosingTabItemHandlerImpl(ItemActionCallbackArgs<TabablzControl> args) { //here's your view model: var viewModel = args.DragablzItem.DataContext as HeaderedItemViewModel; Debug.Assert(viewModel != null); } public ClosingFloatingItemCallback ClosingFloatingItemHandler { get { return ClosingFloatingItemHandlerImpl; } } /// <summary> /// Callback to handle floating toolbar/MDI window closing. /// </summary> private static void ClosingFloatingItemHandlerImpl(ItemActionCallbackArgs<Layout> args) { //here's your view model: var disposable = args.DragablzItem.DataContext as IDisposable; if (disposable != null) disposable.Dispose(); } public ObservableCollection<HeaderedItemViewModel> Tabs { get; set; } private HeaderedItemViewModel _selectedTab; public HeaderedItemViewModel SelectedTab { get { return _selectedTab; } set { Set(() => SelectedTab, ref _selectedTab, value); } } } }
using ReMi.BusinessEntities.ReleasePlan; using ReMi.Common.Utils; using ReMi.Common.Utils.Repository; using ReMi.DataAccess.Exceptions; using ReMi.DataEntities.ReleaseCalendar; using ReMi.DataEntities.ReleasePlan; using System; using System.Collections.Generic; using System.Linq; using BusinessCheckListQuestion = ReMi.BusinessEntities.ReleasePlan.CheckListQuestion; using CheckListQuestion = ReMi.DataEntities.ReleasePlan.CheckListQuestion; namespace ReMi.DataAccess.BusinessEntityGateways.ReleasePlan { public class CheckListGateway : BaseGateway, ICheckListGateway { public IRepository<CheckListQuestion> CheckListQuestionRepository { get; set; } public IRepository<CheckList> CheckListRepository { get; set; } public IRepository<ReleaseWindow> ReleaseWindowRepository { get; set; } public IRepository<CheckListQuestionToProduct> CheckListQuestionToProductRepository { get; set; } public override void OnDisposing() { CheckListQuestionRepository.Dispose(); CheckListQuestionToProductRepository.Dispose(); CheckListRepository.Dispose(); ReleaseWindowRepository.Dispose(); base.OnDisposing(); } public IEnumerable<CheckListItemView> GetCheckList(Guid releaseWindowId) { var result = ReleaseWindowRepository .GetAllSatisfiedBy(r => r.ExternalId == releaseWindowId) .FirstOrDefault(); return result != null ? result.CheckList.Select(x => new CheckListItemView { Checked = x.Checked, CheckListQuestion = x.CheckListQuestion.Content, Comment = x.Comment, ReleaseWindowId = x.ReleaseWindow.ExternalId, ExternalId = x.ExternalId, LastChangedBy = x.LastChangedBy }).ToList() : null; } public CheckListItemView GetCheckListItem(Guid checkListId) { var checkListItem = CheckListRepository.GetSatisfiedBy(c => c.ExternalId == checkListId); return new CheckListItemView { Checked = checkListItem.Checked, CheckListQuestion = checkListItem.CheckListQuestion.Content, Comment = checkListItem.Comment, ReleaseWindowId = checkListItem.ReleaseWindow.ExternalId, ExternalId = checkListItem.ExternalId, LastChangedBy = checkListItem.LastChangedBy }; } public List<BusinessCheckListQuestion> GetCheckListAdditionalQuestions(Guid releaseWindowId) { var questions = CheckListQuestionRepository.GetAllSatisfiedBy( c => c.CheckLists.All(ch => ch.ReleaseWindow.ExternalId != releaseWindowId)) .Select(c => new BusinessCheckListQuestion { ExternalId = c.ExternalId, Question = c.Content }) .ToList(); return questions; } public List<string> GetCheckListQuestions() { return CheckListQuestionRepository.Entities.Select(c => c.Content).ToList(); } public void Create(Guid releaseWindowId) { var releaseWindow = ReleaseWindowRepository .GetAllSatisfiedBy(r => r.ExternalId == releaseWindowId) .FirstOrDefault(); if (releaseWindow != null && releaseWindow.ReleaseProducts.Any() && (releaseWindow.CheckList == null || !releaseWindow.CheckList.Any())) { var localProducts = releaseWindow.ReleaseProducts.Select(x => x.Product.Description).ToArray(); var productQuestions = CheckListQuestionToProductRepository.GetAllSatisfiedBy(c => localProducts.Contains(c.Product.Description)).ToList(); var questions = CheckListQuestionRepository.Entities.ToList(); var checkListQuestions = questions .Where(c => productQuestions.Any(q => q.CheckListQuestionId == c.CheckListQuestionId)) .ToList(); foreach (var checkListQuestion in checkListQuestions) { var checkListItem = new CheckList { ExternalId = Guid.NewGuid(), ReleaseWindowId = releaseWindow.ReleaseWindowId, CheckListQuestionId = checkListQuestion.CheckListQuestionId }; CheckListRepository.Insert(checkListItem); } } } public void UpdateAnswer(CheckListItem checkListItem) { var checkListToUpdate = CheckListRepository.GetSatisfiedBy(x => x.ExternalId == checkListItem.ExternalId); checkListToUpdate.Checked = checkListItem.Checked; checkListToUpdate.LastChangedBy = checkListItem.LastChangedBy; CheckListRepository.Update(checkListToUpdate); } public void UpdateComment(CheckListItem checkListItem) { var checkListToUpdate = CheckListRepository.GetSatisfiedBy(x => x.ExternalId == checkListItem.ExternalId); checkListToUpdate.Comment = checkListItem.Comment; checkListToUpdate.LastChangedBy = checkListItem.LastChangedBy; CheckListRepository.Update(checkListToUpdate); } public void AddCheckListQuestions(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId) { if (questions.IsNullOrEmpty()) return; CheckListQuestionRepository.Insert(questions .Select(x => new CheckListQuestion { Content = x.Question, ExternalId = x.ExternalId })); AssociateCheckListQuestionWithPackage(questions, releaseWindowId); } public void AssociateCheckListQuestionWithPackage(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId) { if (questions.IsNullOrEmpty()) return; var window = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId); if (window == null) throw new EntityNotFoundException(typeof(ReleaseWindow), releaseWindowId); var packageIds = window.ReleaseProducts.Select(x => x.ProductId).ToArray(); var questionExternalIds = questions.Select(x => x.ExternalId).ToArray(); var dataQuestions = CheckListQuestionRepository .GetAllSatisfiedBy(c => questionExternalIds.Any(id => id == c.ExternalId)) .ToArray(); var questionsToAdd = packageIds.SelectMany(x => dataQuestions, (id, q) => new {PackageId = id, Question = q}) .Where(x => !CheckListQuestionToProductRepository.Entities .Any(c => c.ProductId == x.PackageId && c.CheckListQuestionId == x.Question.CheckListQuestionId)) .Select(x => new CheckListQuestionToProduct { ProductId = x.PackageId, CheckListQuestionId = x.Question.CheckListQuestionId, }) .ToArray(); CheckListQuestionToProductRepository.Insert(questionsToAdd); var checkListItemsToAdd = (from bq in questions join dq in dataQuestions on bq.ExternalId equals dq.ExternalId where window.CheckList.All(x => x.CheckListQuestionId != dq.CheckListQuestionId) select new CheckList { ExternalId = bq.CheckListId, ReleaseWindowId = window.ReleaseWindowId, CheckListQuestionId = dq.CheckListQuestionId, }).ToArray(); CheckListRepository.Insert(checkListItemsToAdd); } public void RemoveCheckListQuestion(Guid checkListItemId) { var checkListItem = CheckListRepository.GetSatisfiedBy( q => q.ExternalId == checkListItemId); if (checkListItem == null) throw new EntityNotFoundException(typeof(CheckList), checkListItemId); CheckListRepository.Delete(checkListItem); } public void RemoveCheckListQuestionForPackage(Guid checkListItemId) { var checkListItem = CheckListRepository.GetSatisfiedBy( q => q.ExternalId == checkListItemId); if (checkListItem == null) throw new EntityNotFoundException(typeof(CheckList), checkListItemId); var window = checkListItem.ReleaseWindow; var windowPackageIds = window.ReleaseProducts.Select(x => x.ProductId).ToArray(); var questionToProducts = checkListItem.CheckListQuestion.CheckListQuestionsToProducts .Where(x => windowPackageIds.Any(p => p == x.ProductId)) .ToList(); questionToProducts.ForEach(x => CheckListQuestionToProductRepository.Delete(x.CheckListQuestionsToProductsId)); CheckListRepository.Delete(checkListItem); } } }
using UnityEngine; using System.Collections; /// <summary> /// Use this to access the easing functions /// </summary> public class OTEasing { /// <summary> /// Linear easing function /// </summary> public static OTEase Linear { get { if (linear==null) linear = new OTEaseLinear(); return linear; } } /// <summary> /// Bounce In Easing function /// </summary> public static OTEase BounceIn { get { if (bounceIn == null) bounceIn = new OTEaseBounceIn(); return bounceIn; } } /// <summary> /// Bounce Out Easing function /// </summary> public static OTEase BounceOut { get { if (bounceOut == null) bounceOut = new OTEaseBounceOut(); return bounceOut; } } /// <summary> /// Bounce In Out Easing function /// </summary> public static OTEase BounceInOut { get { if (bounceInOut == null) bounceInOut = new OTEaseBounceInOut(); return bounceInOut; } } /// <summary> /// Back In Easing function /// </summary> public static OTEase BackIn { get { if (backIn == null) backIn = new OTEaseBackIn(); return backIn; } } /// <summary> /// Back Out Easing function /// </summary> public static OTEase BackOut { get { if (backOut == null) backOut = new OTEaseBackOut(); return backOut; } } /// <summary> /// Back In Out Easing function /// </summary> public static OTEase BackInOut { get { if (backInOut == null) backInOut = new OTEaseBackInOut(); return backInOut; } } /// <summary> /// Circ In Easing function /// </summary> public static OTEase CircIn { get { if (circIn == null) circIn = new OTEaseCircIn(); return circIn; } } /// <summary> /// Circ Out Easing function /// </summary> public static OTEase CircOut { get { if (circOut == null) circOut = new OTEaseCircOut(); return circOut; } } /// <summary> /// Circ In Out Easing function /// </summary> public static OTEase CircInOut { get { if (circInOut == null) circInOut = new OTEaseCircInOut(); return circInOut; } } /// <summary> /// Strong In Easing function /// </summary> public static OTEase StrongIn { get { if (strongIn == null) strongIn = new OTEaseStrongIn(); return strongIn; } } /// <summary> /// Strong Out Easing function /// </summary> public static OTEase StrongOut { get { if (strongOut == null) strongOut = new OTEaseStrongOut(); return strongOut; } } /// <summary> /// Strong In Out Easing function /// </summary> public static OTEase StrongInOut { get { if (strongInOut == null) strongInOut = new OTEaseStrongInOut(); return strongInOut; } } /// <summary> /// Sine In Easing function /// </summary> public static OTEase SineIn { get { if (sineIn == null) sineIn = new OTEaseSineIn(); return sineIn; } } /// <summary> /// Sine Out Easing function /// </summary> public static OTEase SineOut { get { if (sineOut == null) sineOut = new OTEaseSineOut(); return sineOut; } } /// <summary> /// Sine In Out Easing function /// </summary> public static OTEase SineInOut { get { if (sineInOut == null) sineInOut = new OTEaseSineInOut(); return sineInOut; } } /// <summary> /// Quad In Easing function /// </summary> public static OTEase QuadIn { get { if (quadIn == null) quadIn = new OTEaseQuadIn(); return quadIn; } } /// <summary> /// Quad Out Easing function /// </summary> public static OTEase QuadOut { get { if (quadOut == null) quadOut = new OTEaseQuadOut(); return quadOut; } } /// <summary> /// Quad In Out Easing function /// </summary> public static OTEase QuadInOut { get { if (quadInOut == null) quadInOut = new OTEaseQuadInOut(); return quadInOut; } } /// <summary> /// Quart In Easing function /// </summary> public static OTEase QuartIn { get { if (quartIn == null) quartIn = new OTEaseQuartIn(); return quartIn; } } /// <summary> /// Quart Out Easing function /// </summary> public static OTEase QuartOut { get { if (quartOut == null) quartOut = new OTEaseQuartOut(); return quartOut; } } /// <summary> /// Quart In Out Easing function /// </summary> public static OTEase QuartInOut { get { if (quartInOut == null) quartInOut = new OTEaseQuartInOut(); return quartInOut; } } /// <summary> /// Quint In Easing function /// </summary> public static OTEase QuintIn { get { if (quintIn == null) quintIn = new OTEaseQuintIn(); return quintIn; } } /// <summary> /// Quint Out Easing function /// </summary> public static OTEase QuintOut { get { if (quintOut == null) quintOut = new OTEaseQuintOut(); return quintOut; } } /// <summary> /// Quint In Out Easing function /// </summary> public static OTEase QuintInOut { get { if (quintInOut == null) quintInOut = new OTEaseQuintInOut(); return quintInOut; } } /// <summary> /// Expo In Easing function /// </summary> public static OTEase ExpoIn { get { if (expoIn == null) expoIn = new OTEaseExpoIn(); return expoIn; } } /// <summary> /// Expo Out Easing function /// </summary> public static OTEase ExpoOut { get { if (expoOut == null) expoOut = new OTEaseExpoOut(); return expoOut; } } /// <summary> /// Expo In Out Easing function /// </summary> public static OTEase ExpoInOut { get { if (expoInOut == null) expoInOut = new OTEaseExpoInOut(); return expoInOut; } } /// <summary> /// Cubic In Easing function /// </summary> public static OTEase CubicIn { get { if (cubicIn == null) cubicIn = new OTEaseCubicIn(); return cubicIn; } } /// <summary> /// Cubic Out Easing function /// </summary> public static OTEase CubicOut { get { if (cubicOut == null) cubicOut = new OTEaseCubicOut(); return cubicOut; } } /// <summary> /// Cubic In Out Easing function /// </summary> public static OTEase CubicInOut { get { if (cubicInOut == null) cubicInOut = new OTEaseCubicInOut(); return cubicInOut; } } /// <summary> /// Elastic In Easing function /// </summary> public static OTEase ElasticIn { get { //if (elasticIn == null) elasticIn = new OTEaseElasticIn(); return elasticIn; } } /// <summary> /// Elastic Out Easing function /// </summary> public static OTEase ElasticOut { get { //if (elasticOut == null) elasticOut = new OTEaseElasticOut(); return elasticOut; } } /// <summary> /// Elastic In Out Easing function /// </summary> public static OTEase ElasticInOut { get { //if (elasticInOut == null) elasticInOut = new OTEaseElasticInOut(); return elasticInOut; } } private static OTEase linear = null; private static OTEase backIn = null; private static OTEase backInOut = null; private static OTEase backOut = null; private static OTEase bounceIn = null; private static OTEase bounceInOut = null; private static OTEase bounceOut = null; private static OTEase circIn = null; private static OTEase circInOut = null; private static OTEase circOut = null; private static OTEase cubicIn = null; private static OTEase cubicInOut = null; private static OTEase cubicOut = null; private static OTEase elasticIn = null; private static OTEase elasticInOut = null; private static OTEase elasticOut = null; private static OTEase quadIn = null; private static OTEase quadInOut = null; private static OTEase quadOut = null; private static OTEase quartIn = null; private static OTEase quartInOut = null; private static OTEase quartOut = null; private static OTEase quintIn = null; private static OTEase quintInOut = null; private static OTEase quintOut = null; private static OTEase strongIn = null; private static OTEase strongInOut = null; private static OTEase strongOut = null; private static OTEase sineIn = null; private static OTEase sineInOut = null; private static OTEase sineOut = null; private static OTEase expoIn = null; private static OTEase expoInOut = null; private static OTEase expoOut = null; }
using System; using System.Collections.Generic; using System.Linq; using Signum.Utilities; using Signum.Entities.DynamicQuery; using System.Text.RegularExpressions; using Signum.Utilities.Reflection; using Signum.Utilities.DataStructures; using Signum.Entities.UserAssets; using System.Text.Json.Serialization; using System.Text.Json; using System.Collections.Immutable; namespace Signum.Entities.Omnibox { public class DynamicQueryOmniboxResultGenerator :OmniboxResultGenerator<DynamicQueryOmniboxResult> { private static List<FilterSyntax> SyntaxSequence(Match m) { return m.Groups["filter"].Captures().Select(filter => new FilterSyntax { Index = filter.Index, TokenLength = m.Groups["token"].Captures().Single(filter.Contains).Length, Length = filter.Length, Completion = m.Groups["val"].Captures().Any(filter.Contains) ? FilterSyntaxCompletion.Complete : m.Groups["op"].Captures().Any(filter.Contains) ? FilterSyntaxCompletion.Operation : FilterSyntaxCompletion.Token, }).ToList(); } Regex regex = new Regex(@"^I(?<filter>(?<token>I(\.I)*)(\.|((?<op>=)(?<val>[ENSIG])?))?)*$", RegexOptions.ExplicitCapture); public override IEnumerable<DynamicQueryOmniboxResult> GetResults(string rawQuery, List<OmniboxToken> tokens, string tokenPattern) { Match m = regex.Match(tokenPattern); if (!m.Success) yield break; string pattern = tokens[0].Value; bool isPascalCase = OmniboxUtils.IsPascalCasePattern(pattern); List<FilterSyntax>? syntaxSequence = null; foreach (var match in OmniboxUtils.Matches(OmniboxParser.Manager.GetQueries(), OmniboxParser.Manager.AllowedQuery, pattern, isPascalCase).OrderBy(ma => ma.Distance)) { var queryName = match.Value; if (syntaxSequence == null) syntaxSequence = SyntaxSequence(m); if (syntaxSequence.Any()) { QueryDescription description = OmniboxParser.Manager.GetDescription(match.Value); IEnumerable<IEnumerable<OmniboxFilterResult>> bruteFilters = syntaxSequence.Select(a => GetFilterQueries(rawQuery, description, a, tokens)); foreach (var list in bruteFilters.CartesianProduct()) { yield return new DynamicQueryOmniboxResult { QueryName = match.Value, QueryNameMatch = match, Distance = match.Distance + list.Average(a => a.Distance), Filters = list.ToList(), }; } } else { if (match.Text == pattern && tokens.Count == 1 && tokens[0].Next(rawQuery) == ' ') { QueryDescription description = OmniboxParser.Manager.GetDescription(match.Value); foreach (var qt in QueryUtils.SubTokens(null, description, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement)) { yield return new DynamicQueryOmniboxResult { QueryName = match.Value, QueryNameMatch = match, Distance = match.Distance, Filters = new List<OmniboxFilterResult> { new OmniboxFilterResult(0, null, qt, null) }, }; } } else { yield return new DynamicQueryOmniboxResult { QueryName = match.Value, QueryNameMatch = match, Distance = match.Distance, Filters = new List<OmniboxFilterResult>() }; } } } } protected IEnumerable<OmniboxFilterResult> GetFilterQueries(string rawQuery, QueryDescription queryDescription, FilterSyntax syntax, List<OmniboxToken> tokens) { List<OmniboxFilterResult> result = new List<OmniboxFilterResult>(); int operatorIndex = syntax.Index + syntax.TokenLength; List<(QueryToken token, ImmutableStack<OmniboxMatch> stack)> ambiguousTokens = GetAmbiguousTokens(null, ImmutableStack<OmniboxMatch>.Empty, queryDescription, tokens, syntax.Index, operatorIndex).ToList(); foreach ((QueryToken token, ImmutableStack<OmniboxMatch> stack) pair in ambiguousTokens) { var distance = pair.stack.Sum(a => a.Distance); var tokenMatches = pair.stack.Reverse().ToArray(); var token = pair.token; if (syntax.Completion == FilterSyntaxCompletion.Token) { if (tokens[operatorIndex - 1].Next(rawQuery) == '.' && pair.stack.All(a => ((QueryToken)a.Value).ToString().ToOmniboxPascal() == a.Text)) { foreach (var qt in QueryUtils.SubTokens(pair.token, queryDescription, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement)) { result.Add(new OmniboxFilterResult(distance, syntax, qt, tokenMatches)); } } else { result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches)); } } else { string? canFilter = QueryUtils.CanFilter(pair.token); if (canFilter.HasText()) { result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches) { CanFilter = canFilter, }); } else { FilterOperation operation = FilterValueConverter.ParseOperation(tokens[operatorIndex].Value); if (syntax.Completion == FilterSyntaxCompletion.Operation) { var suggested = SugestedValues(pair.token); if (suggested == null) { result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches) { Operation = operation, }); } else { foreach (var item in suggested) { result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches) { Operation = operation, Value = item.Value }); } } } else { var values = GetValues(pair.token, tokens[operatorIndex + 1]); foreach (var value in values) { result.Add(new OmniboxFilterResult(distance, syntax, token, tokenMatches) { Operation = operation, Value = value.Value, ValueMatch = value.Match, }); } } } } } return result; } public static readonly string UnknownValue = "??UNKNOWN??"; public struct ValueTuple { public object? Value; public OmniboxMatch? Match; } protected virtual ValueTuple[]? SugestedValues(QueryToken queryToken) { var ft = QueryUtils.GetFilterType(queryToken.Type); switch (ft) { case FilterType.Integer: case FilterType.Decimal: return new[] { new ValueTuple { Value = Activator.CreateInstance(queryToken.Type.UnNullify()), Match = null } }; case FilterType.String: return new[] { new ValueTuple { Value = "", Match = null } }; case FilterType.DateTime: return new[] { new ValueTuple { Value = DateTime.Today, Match = null } }; case FilterType.Time: return new[] { new ValueTuple { Value = TimeSpan.Zero, Match = null } }; case FilterType.Lite: case FilterType.Embedded: break; case FilterType.Boolean: return new[] { new ValueTuple { Value = true, Match = null }, new ValueTuple { Value = false, Match = null } }; case FilterType.Enum: return EnumEntity.GetValues(queryToken.Type.UnNullify()).Select(e => new ValueTuple { Value = e, Match = null }).ToArray(); case FilterType.Guid: break; } return null; } public int AutoCompleteLimit = 5; protected virtual ValueTuple[] GetValues(QueryToken queryToken, OmniboxToken omniboxToken) { if (omniboxToken.IsNull()) return new[] { new ValueTuple { Value = null, Match = null } }; var ft = QueryUtils.GetFilterType(queryToken.Type); switch (ft) { case FilterType.Integer: case FilterType.Decimal: if (omniboxToken.Type == OmniboxTokenType.Number) { if (ReflectionTools.TryParse(omniboxToken.Value, queryToken.Type, out object? result)) return new[] { new ValueTuple { Value = result, Match = null } }; } break; case FilterType.String: if (omniboxToken.Type == OmniboxTokenType.String) return new[] { new ValueTuple { Value = OmniboxUtils.CleanCommas(omniboxToken.Value), Match = null } }; break; case FilterType.DateTime: case FilterType.Time: if (omniboxToken.Type == OmniboxTokenType.String) { var str = OmniboxUtils.CleanCommas(omniboxToken.Value); if (ReflectionTools.TryParse(str, queryToken.Type, out object? result)) return new[] { new ValueTuple { Value = result, Match = null } }; } break; case FilterType.Lite: if (omniboxToken.Type == OmniboxTokenType.String) { var patten = OmniboxUtils.CleanCommas(omniboxToken.Value); var result = OmniboxParser.Manager.Autocomplete(queryToken.GetImplementations()!.Value, patten, AutoCompleteLimit); return result.Select(lite => new ValueTuple { Value = lite, Match = OmniboxUtils.Contains(lite, lite.ToString()!, patten) }).ToArray(); } else if (omniboxToken.Type == OmniboxTokenType.Entity) { var error = Lite.TryParseLite(omniboxToken.Value, out Lite<Entity>? lite); if (string.IsNullOrEmpty(error)) return new []{new ValueTuple { Value = lite }}; } else if (omniboxToken.Type == OmniboxTokenType.Number) { var imp = queryToken.GetImplementations()!.Value; if (!imp.IsByAll) { return imp.Types.Select(t => CreateLite(t, omniboxToken.Value)) .NotNull().Select(t => new ValueTuple { Value = t }).ToArray(); } }break; case FilterType.Embedded: case FilterType.Boolean: bool? boolean = ParseBool(omniboxToken.Value); if (boolean.HasValue) return new []{ new ValueTuple{ Value = boolean.Value} }; break; case FilterType.Enum: if (omniboxToken.Type == OmniboxTokenType.String || omniboxToken.Type == OmniboxTokenType.Identifier) { string value = omniboxToken.Type == OmniboxTokenType.Identifier ? omniboxToken.Value : OmniboxUtils.CleanCommas(omniboxToken.Value); bool isPascalValue = OmniboxUtils.IsPascalCasePattern(value); Type enumType = queryToken.Type.UnNullify(); var dic = EnumEntity.GetValues(enumType).ToOmniboxPascalDictionary(a => a.NiceToString(), a => (object)a); var result = OmniboxUtils.Matches(dic, e => true, value, isPascalValue) .Select(m => new ValueTuple { Value = m.Value, Match = m }) .ToArray(); return result; } break; case FilterType.Guid: if (omniboxToken.Type == OmniboxTokenType.Guid) { if (Guid.TryParse(omniboxToken.Value, out Guid result)) return new[] { new ValueTuple { Value = result, Match = null } }; } else if (omniboxToken.Type == OmniboxTokenType.String) { var str = OmniboxUtils.CleanCommas(omniboxToken.Value); if (Guid.TryParse(str, out Guid result)) return new[] { new ValueTuple { Value = result, Match = null } }; } break; default: break; } return new[] { new ValueTuple { Value = UnknownValue, Match = null } }; } Lite<Entity>? CreateLite(Type type, string value) { if (PrimaryKey.TryParse(value, type, out PrimaryKey id)) return Lite.Create(type, id, "{0} {1}".FormatWith(type.NiceName(), id)); return null; } bool? ParseBool(string val) { val = val.ToLower().RemoveDiacritics(); if (val == "true" || val == "t" || val == "yes" || val == "y" || val == OmniboxMessage.Yes.NiceToString()) return true; if (val == "false" || val == "f" || val == "no" || val == "n" || val == OmniboxMessage.No.NiceToString()) return false; return null; } protected virtual IEnumerable<(QueryToken token, ImmutableStack<OmniboxMatch> stack)> GetAmbiguousTokens(QueryToken? queryToken, ImmutableStack<OmniboxMatch> distancePack, QueryDescription queryDescription, List<OmniboxToken> omniboxTokens, int index, int operatorIndex) { OmniboxToken omniboxToken = omniboxTokens[index]; bool isPascal = OmniboxUtils.IsPascalCasePattern(omniboxToken.Value); var dic = QueryUtils.SubTokens(queryToken, queryDescription, SubTokensOptions.CanAnyAll | SubTokensOptions.CanElement).ToOmniboxPascalDictionary(qt => qt.ToString(), qt => qt); var matches = OmniboxUtils.Matches(dic, qt => qt.IsAllowed() == null, omniboxToken.Value, isPascal); if (index == operatorIndex - 1) { foreach (var m in matches) { var token = (QueryToken)m.Value; yield return (token: token, stack: distancePack.Push(m)); } } else { foreach (var m in matches) foreach (var newPair in GetAmbiguousTokens((QueryToken)m.Value, distancePack.Push(m), queryDescription, omniboxTokens, index + 2, operatorIndex)) yield return newPair; } } public static string ToStringValue(object? p) { if (p == null) return "null"; switch (QueryUtils.GetFilterType(p.GetType())) { case FilterType.Integer: case FilterType.Decimal: return p.ToString()!; case FilterType.String: return "\"" + p.ToString() + "\""; case FilterType.DateTime: return "'" + p.ToString() + "'"; case FilterType.Time: return "'" + p.ToString() + "'"; case FilterType.Lite: return ((Lite<Entity>)p).Key(); case FilterType.Embedded: throw new InvalidOperationException("Impossible to translate not null Embedded entity to string"); case FilterType.Boolean: return p.ToString()!; case FilterType.Enum: return ((Enum)p).NiceToString().SpacePascal(); case FilterType.Guid: return "\"" + p.ToString() + "\""; } throw new InvalidOperationException("Unexpected value type {0}".FormatWith(p.GetType())); } public override List<HelpOmniboxResult> GetHelp() { var resultType = typeof(DynamicQueryOmniboxResult); var queryName = OmniboxMessage.Omnibox_Query.NiceToString(); var field = OmniboxMessage.Omnibox_Field.NiceToString(); var value = OmniboxMessage.Omnibox_Value.NiceToString(); return new List<HelpOmniboxResult> { new HelpOmniboxResult { Text = "{0}".FormatWith(queryName), ReferencedType = resultType }, new HelpOmniboxResult { Text = "{0} {1}='{2}'".FormatWith(queryName, field, value), ReferencedType = resultType }, new HelpOmniboxResult { Text = "{0} {1}1='{2}1' {1}2='{2}2'".FormatWith(queryName, field, value), ReferencedType = resultType }, }; } } public class DynamicQueryOmniboxResult : OmniboxResult { [JsonConverter(typeof(QueryNameJsonConverter))] public object QueryName { get; set; } public OmniboxMatch QueryNameMatch { get; set; } public List<OmniboxFilterResult> Filters { get; set; } public override string ToString() { string queryName = QueryUtils.GetNiceName(QueryName).ToOmniboxPascal(); string filters = Filters.ToString(" "); if (string.IsNullOrEmpty(filters)) return queryName; else return queryName + " " + filters; } } public class OmniboxFilterResult { public OmniboxFilterResult(float distance, FilterSyntax? syntax, DynamicQuery.QueryToken queryToken, OmniboxMatch[]? omniboxMatch) { this.Distance = distance; this.Syntax = syntax; this.QueryToken = queryToken; this.QueryTokenMatches = omniboxMatch; } public float Distance { get; set; } public FilterSyntax? Syntax {get; set;} [JsonConverter(typeof(QueryTokenJsonConverter))] public QueryToken QueryToken { get; set; } public string? QueryTokenOmniboxPascal => QueryToken?.Follow(a => a.Parent).Reverse().ToString(a => a.ToString().ToOmniboxPascal(), "."); public OmniboxMatch[]? QueryTokenMatches { get; set; } public FilterOperation? Operation { get; set; } public string? OperationToString => this.Operation == null ? null : FilterValueConverter.ToStringOperation(this.Operation.Value); public string? ValueToString => this.Value == null ? null : DynamicQueryOmniboxResultGenerator.ToStringValue(this.Value); public object? Value { get; set; } public OmniboxMatch? ValueMatch { get; set; } public string CanFilter { get; set; } public override string ToString() { string token = QueryToken.Follow(q => q.Parent).Reverse().Select(a => a.ToString().ToOmniboxPascal()).ToString("."); if (Syntax == null || Syntax.Completion == FilterSyntaxCompletion.Token || CanFilter.HasText()) return token; string oper = FilterValueConverter.ToStringOperation(Operation!.Value); if ((Syntax.Completion == FilterSyntaxCompletion.Operation && Value == null) || (Value as string == DynamicQueryOmniboxResultGenerator.UnknownValue)) return token + oper; return token + oper + DynamicQueryOmniboxResultGenerator.ToStringValue(Value); } } public class FilterSyntax { public int Index; public int TokenLength; public int Length; public FilterSyntaxCompletion Completion; } public enum FilterSyntaxCompletion { Token, Operation, Complete, } //User 2 //ped cus.per.add.cit=="London" fj>'2012' //FVL N="hola" public class QueryNameJsonConverter : JsonConverter<object> { public static Func<object, string> GetQueryKey; public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) { writer.WriteStringValue(GetQueryKey(value!)); } } public class QueryTokenJsonConverter : JsonConverter<QueryToken> { public static Func<QueryToken, object> GetQueryTokenTS; public override QueryToken? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { throw new NotImplementedException(); } public override void Write(Utf8JsonWriter writer, QueryToken value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, GetQueryTokenTS((QueryToken)value!), options); } } }
// 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.Diagnostics; using System.Xml.XPath; namespace MS.Internal.Xml.XPath { internal class XPathParser { XPathScanner scanner; private XPathParser(XPathScanner scanner) { this.scanner = scanner; } public static AstNode ParseXPathExpresion(string xpathExpresion) { XPathScanner scanner = new XPathScanner(xpathExpresion); XPathParser parser = new XPathParser(scanner); AstNode result = parser.ParseExpresion(null); if (scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText); } return result; } public static AstNode ParseXPathPattern(string xpathPattern) { XPathScanner scanner = new XPathScanner(xpathPattern); XPathParser parser = new XPathParser(scanner); AstNode result = parser.ParsePattern(); if (scanner.Kind != XPathScanner.LexKind.Eof) { throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText); } return result; } // --------------- Expression Parsing ---------------------- //The recursive is like //ParseOrExpr->ParseAndExpr->ParseEqualityExpr->ParseRelationalExpr...->ParseFilterExpr->ParsePredicate->ParseExpresion //So put 200 limitation here will max cause about 2000~3000 depth stack. private int parseDepth = 0; private const int MaxParseDepth = 200; private AstNode ParseExpresion(AstNode qyInput) { if (++parseDepth > MaxParseDepth) { throw XPathException.Create(SR.Xp_QueryTooComplex); } AstNode result = ParseOrExpr(qyInput); --parseDepth; return result; } //>> OrExpr ::= ( OrExpr 'or' )? AndExpr private AstNode ParseOrExpr(AstNode qyInput) { AstNode opnd = ParseAndExpr(qyInput); do { if (!TestOp("or")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.OR, opnd, ParseAndExpr(qyInput)); } while (true); } //>> AndExpr ::= ( AndExpr 'and' )? EqualityExpr private AstNode ParseAndExpr(AstNode qyInput) { AstNode opnd = ParseEqualityExpr(qyInput); do { if (!TestOp("and")) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.AND, opnd, ParseEqualityExpr(qyInput)); } while (true); } //>> EqualityOp ::= '=' | '!=' //>> EqualityExpr ::= ( EqualityExpr EqualityOp )? RelationalExpr private AstNode ParseEqualityExpr(AstNode qyInput) { AstNode opnd = ParseRelationalExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Eq ? Operator.Op.EQ : this.scanner.Kind == XPathScanner.LexKind.Ne ? Operator.Op.NE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseRelationalExpr(qyInput)); } while (true); } //>> RelationalOp ::= '<' | '>' | '<=' | '>=' //>> RelationalExpr ::= ( RelationalExpr RelationalOp )? AdditiveExpr private AstNode ParseRelationalExpr(AstNode qyInput) { AstNode opnd = ParseAdditiveExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Lt ? Operator.Op.LT : this.scanner.Kind == XPathScanner.LexKind.Le ? Operator.Op.LE : this.scanner.Kind == XPathScanner.LexKind.Gt ? Operator.Op.GT : this.scanner.Kind == XPathScanner.LexKind.Ge ? Operator.Op.GE : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseAdditiveExpr(qyInput)); } while (true); } //>> AdditiveOp ::= '+' | '-' //>> AdditiveExpr ::= ( AdditiveExpr AdditiveOp )? MultiplicativeExpr private AstNode ParseAdditiveExpr(AstNode qyInput) { AstNode opnd = ParseMultiplicativeExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Plus ? Operator.Op.PLUS : this.scanner.Kind == XPathScanner.LexKind.Minus ? Operator.Op.MINUS : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseMultiplicativeExpr(qyInput)); } while (true); } //>> MultiplicativeOp ::= '*' | 'div' | 'mod' //>> MultiplicativeExpr ::= ( MultiplicativeExpr MultiplicativeOp )? UnaryExpr private AstNode ParseMultiplicativeExpr(AstNode qyInput) { AstNode opnd = ParseUnaryExpr(qyInput); do { Operator.Op op = ( this.scanner.Kind == XPathScanner.LexKind.Star ? Operator.Op.MUL : TestOp("div") ? Operator.Op.DIV : TestOp("mod") ? Operator.Op.MOD : /*default :*/ Operator.Op.INVALID ); if (op == Operator.Op.INVALID) { return opnd; } NextLex(); opnd = new Operator(op, opnd, ParseUnaryExpr(qyInput)); } while (true); } //>> UnaryExpr ::= UnionExpr | '-' UnaryExpr private AstNode ParseUnaryExpr(AstNode qyInput) { bool minus = false; while (this.scanner.Kind == XPathScanner.LexKind.Minus) { NextLex(); minus = !minus; } if (minus) { return new Operator(Operator.Op.MUL, ParseUnionExpr(qyInput), new Operand(-1)); } else { return ParseUnionExpr(qyInput); } } //>> UnionExpr ::= ( UnionExpr '|' )? PathExpr private AstNode ParseUnionExpr(AstNode qyInput) { AstNode opnd = ParsePathExpr(qyInput); do { if (this.scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); AstNode opnd2 = ParsePathExpr(qyInput); CheckNodeSet(opnd.ReturnType); CheckNodeSet(opnd2.ReturnType); opnd = new Operator(Operator.Op.UNION, opnd, opnd2); } while (true); } private static bool IsNodeType(XPathScanner scaner) { return ( scaner.Prefix.Length == 0 && ( scaner.Name == "node" || scaner.Name == "text" || scaner.Name == "processing-instruction" || scaner.Name == "comment" ) ); } //>> PathOp ::= '/' | '//' //>> PathExpr ::= LocationPath | //>> FilterExpr ( PathOp RelativeLocationPath )? private AstNode ParsePathExpr(AstNode qyInput) { AstNode opnd; if (IsPrimaryExpr(this.scanner)) { // in this moment we should distinct LocationPas vs FilterExpr (which starts from is PrimaryExpr) opnd = ParseFilterExpr(qyInput); if (this.scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); opnd = ParseRelativeLocationPath(opnd); } else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); opnd = ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } } else { opnd = ParseLocationPath(null); } return opnd; } //>> FilterExpr ::= PrimaryExpr | FilterExpr Predicate private AstNode ParseFilterExpr(AstNode qyInput) { AstNode opnd = ParsePrimaryExpr(qyInput); while (this.scanner.Kind == XPathScanner.LexKind.LBracket) { // opnd must be a query opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } //>> Predicate ::= '[' Expr ']' private AstNode ParsePredicate(AstNode qyInput) { AstNode opnd; // we have predicates. Check that input type is NodeSet CheckNodeSet(qyInput.ReturnType); PassToken(XPathScanner.LexKind.LBracket); opnd = ParseExpresion(qyInput); PassToken(XPathScanner.LexKind.RBracket); return opnd; } //>> LocationPath ::= RelativeLocationPath | AbsoluteLocationPath private AstNode ParseLocationPath(AstNode qyInput) { if (this.scanner.Kind == XPathScanner.LexKind.Slash) { NextLex(); AstNode opnd = new Root(); if (IsStep(this.scanner.Kind)) { opnd = ParseRelativeLocationPath(opnd); } return opnd; } else if (this.scanner.Kind == XPathScanner.LexKind.SlashSlash) { NextLex(); return ParseRelativeLocationPath(new Axis(Axis.AxisType.DescendantOrSelf, new Root())); } else { return ParseRelativeLocationPath(qyInput); } } // ParseLocationPath //>> PathOp ::= '/' | '//' //>> RelativeLocationPath ::= ( RelativeLocationPath PathOp )? Step private AstNode ParseRelativeLocationPath(AstNode qyInput) { AstNode opnd = qyInput; do { opnd = ParseStep(opnd); if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind) { NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); } else if (XPathScanner.LexKind.Slash == this.scanner.Kind) { NextLex(); } else { break; } } while (true); return opnd; } private static bool IsStep(XPathScanner.LexKind lexKind) { return ( lexKind == XPathScanner.LexKind.Dot || lexKind == XPathScanner.LexKind.DotDot || lexKind == XPathScanner.LexKind.At || lexKind == XPathScanner.LexKind.Axe || lexKind == XPathScanner.LexKind.Star || lexKind == XPathScanner.LexKind.Name // NodeTest is also Name ); } //>> Step ::= '.' | '..' | ( AxisName '::' | '@' )? NodeTest Predicate* private AstNode ParseStep(AstNode qyInput) { AstNode opnd; if (XPathScanner.LexKind.Dot == this.scanner.Kind) { //>> '.' NextLex(); opnd = new Axis(Axis.AxisType.Self, qyInput); } else if (XPathScanner.LexKind.DotDot == this.scanner.Kind) { //>> '..' NextLex(); opnd = new Axis(Axis.AxisType.Parent, qyInput); } else { //>> ( AxisName '::' | '@' )? NodeTest Predicate* Axis.AxisType axisType = Axis.AxisType.Child; switch (this.scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : // axisType == Axis.AxisType.Namespace ? XPathNodeType.Namespace : // No Idea why it's this way but otherwise Axes doesn't work /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == this.scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } } return opnd; } //>> NodeTest ::= NameTest | 'comment ()' | 'text ()' | 'node ()' | 'processing-instruction (' Literal ? ')' private AstNode ParseNodeTest(AstNode qyInput, Axis.AxisType axisType, XPathNodeType nodeType) { string nodeName, nodePrefix; switch (this.scanner.Kind) { case XPathScanner.LexKind.Name: if (this.scanner.CanBeFunction && IsNodeType(this.scanner)) { nodePrefix = string.Empty; nodeName = string.Empty; nodeType = ( this.scanner.Name == "comment" ? XPathNodeType.Comment : this.scanner.Name == "text" ? XPathNodeType.Text : this.scanner.Name == "node" ? XPathNodeType.All : this.scanner.Name == "processing-instruction" ? XPathNodeType.ProcessingInstruction : /* default: */ XPathNodeType.Root ); Debug.Assert(nodeType != XPathNodeType.Root); NextLex(); PassToken(XPathScanner.LexKind.LParens); if (nodeType == XPathNodeType.ProcessingInstruction) { if (this.scanner.Kind != XPathScanner.LexKind.RParens) { //>> 'processing-instruction (' Literal ')' CheckToken(XPathScanner.LexKind.String); nodeName = this.scanner.StringValue; NextLex(); } } PassToken(XPathScanner.LexKind.RParens); } else { nodePrefix = this.scanner.Prefix; nodeName = this.scanner.Name; NextLex(); if (nodeName == "*") { nodeName = string.Empty; } } break; case XPathScanner.LexKind.Star: nodePrefix = string.Empty; nodeName = string.Empty; NextLex(); break; default: throw XPathException.Create(SR.Xp_NodeSetExpected, this.scanner.SourceText); } return new Axis(axisType, qyInput, nodePrefix, nodeName, nodeType); } private static bool IsPrimaryExpr(XPathScanner scanner) { return ( scanner.Kind == XPathScanner.LexKind.String || scanner.Kind == XPathScanner.LexKind.Number || scanner.Kind == XPathScanner.LexKind.Dollar || scanner.Kind == XPathScanner.LexKind.LParens || scanner.Kind == XPathScanner.LexKind.Name && scanner.CanBeFunction && !IsNodeType(scanner) ); } //>> PrimaryExpr ::= Literal | Number | VariableReference | '(' Expr ')' | FunctionCall private AstNode ParsePrimaryExpr(AstNode qyInput) { Debug.Assert(IsPrimaryExpr(this.scanner)); AstNode opnd = null; switch (this.scanner.Kind) { case XPathScanner.LexKind.String: opnd = new Operand(this.scanner.StringValue); NextLex(); break; case XPathScanner.LexKind.Number: opnd = new Operand(this.scanner.NumberValue); NextLex(); break; case XPathScanner.LexKind.Dollar: NextLex(); CheckToken(XPathScanner.LexKind.Name); opnd = new Variable(this.scanner.Name, this.scanner.Prefix); NextLex(); break; case XPathScanner.LexKind.LParens: NextLex(); opnd = ParseExpresion(qyInput); if (opnd.Type != AstNode.AstType.ConstantOperand) { opnd = new Group(opnd); } PassToken(XPathScanner.LexKind.RParens); break; case XPathScanner.LexKind.Name: if (this.scanner.CanBeFunction && !IsNodeType(this.scanner)) { opnd = ParseMethod(null); } break; } Debug.Assert(opnd != null, "IsPrimaryExpr() was true. We should recognize this lex."); return opnd; } private AstNode ParseMethod(AstNode qyInput) { List<AstNode> argList = new List<AstNode>(); string name = this.scanner.Name; string prefix = this.scanner.Prefix; PassToken(XPathScanner.LexKind.Name); PassToken(XPathScanner.LexKind.LParens); if (this.scanner.Kind != XPathScanner.LexKind.RParens) { do { argList.Add(ParseExpresion(qyInput)); if (this.scanner.Kind == XPathScanner.LexKind.RParens) { break; } PassToken(XPathScanner.LexKind.Comma); } while (true); } PassToken(XPathScanner.LexKind.RParens); if (prefix.Length == 0) { ParamInfo pi; if (functionTable.TryGetValue(name, out pi)) { int argCount = argList.Count; if (argCount < pi.Minargs) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, this.scanner.SourceText); } if (pi.FType == Function.FunctionType.FuncConcat) { for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if (arg.ReturnType != XPathResultType.String) { arg = new Function(Function.FunctionType.FuncString, arg); } argList[i] = arg; } } else { if (pi.Maxargs < argCount) { throw XPathException.Create(SR.Xp_InvalidNumArgs, name, this.scanner.SourceText); } if (pi.ArgTypes.Length < argCount) { argCount = pi.ArgTypes.Length; // argument we have the type specified (can be < pi.Minargs) } for (int i = 0; i < argCount; i++) { AstNode arg = (AstNode)argList[i]; if ( pi.ArgTypes[i] != XPathResultType.Any && pi.ArgTypes[i] != arg.ReturnType ) { switch (pi.ArgTypes[i]) { case XPathResultType.NodeSet: if (!(arg is Variable) && !(arg is Function && arg.ReturnType == XPathResultType.Any)) { throw XPathException.Create(SR.Xp_InvalidArgumentType, name, this.scanner.SourceText); } break; case XPathResultType.String: arg = new Function(Function.FunctionType.FuncString, arg); break; case XPathResultType.Number: arg = new Function(Function.FunctionType.FuncNumber, arg); break; case XPathResultType.Boolean: arg = new Function(Function.FunctionType.FuncBoolean, arg); break; } argList[i] = arg; } } } return new Function(pi.FType, argList); } } return new Function(prefix, name, argList); } // --------------- Pattern Parsing ---------------------- //>> Pattern ::= ( Pattern '|' )? LocationPathPattern private AstNode ParsePattern() { AstNode opnd = ParseLocationPathPattern(); do { if (this.scanner.Kind != XPathScanner.LexKind.Union) { return opnd; } NextLex(); opnd = new Operator(Operator.Op.UNION, opnd, ParseLocationPathPattern()); } while (true); } //>> LocationPathPattern ::= '/' | RelativePathPattern | '//' RelativePathPattern | '/' RelativePathPattern //>> | IdKeyPattern (('/' | '//') RelativePathPattern)? private AstNode ParseLocationPathPattern() { AstNode opnd = null; switch (this.scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); opnd = new Root(); if (this.scanner.Kind == XPathScanner.LexKind.Eof || this.scanner.Kind == XPathScanner.LexKind.Union) { return opnd; } break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, new Root()); break; case XPathScanner.LexKind.Name: if (this.scanner.CanBeFunction) { opnd = ParseIdKeyPattern(); if (opnd != null) { switch (this.scanner.Kind) { case XPathScanner.LexKind.Slash: NextLex(); break; case XPathScanner.LexKind.SlashSlash: NextLex(); opnd = new Axis(Axis.AxisType.DescendantOrSelf, opnd); break; default: return opnd; } } } break; } return ParseRelativePathPattern(opnd); } //>> IdKeyPattern ::= 'id' '(' Literal ')' | 'key' '(' Literal ',' Literal ')' private AstNode ParseIdKeyPattern() { Debug.Assert(this.scanner.CanBeFunction); List<AstNode> argList = new List<AstNode>(); if (this.scanner.Prefix.Length == 0) { if (this.scanner.Name == "id") { ParamInfo pi = (ParamInfo)functionTable["id"]; NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function(pi.FType, argList); } if (this.scanner.Name == "key") { NextLex(); PassToken(XPathScanner.LexKind.LParens); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.Comma); CheckToken(XPathScanner.LexKind.String); argList.Add(new Operand(this.scanner.StringValue)); NextLex(); PassToken(XPathScanner.LexKind.RParens); return new Function("", "key", argList); } } return null; } //>> PathOp ::= '/' | '//' //>> RelativePathPattern ::= ( RelativePathPattern PathOp )? StepPattern private AstNode ParseRelativePathPattern(AstNode qyInput) { AstNode opnd = ParseStepPattern(qyInput); if (XPathScanner.LexKind.SlashSlash == this.scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(new Axis(Axis.AxisType.DescendantOrSelf, opnd)); } else if (XPathScanner.LexKind.Slash == this.scanner.Kind) { NextLex(); opnd = ParseRelativePathPattern(opnd); } return opnd; } //>> StepPattern ::= ChildOrAttributeAxisSpecifier NodeTest Predicate* //>> ChildOrAttributeAxisSpecifier ::= @ ? | ('child' | 'attribute') '::' private AstNode ParseStepPattern(AstNode qyInput) { AstNode opnd; Axis.AxisType axisType = Axis.AxisType.Child; switch (this.scanner.Kind) { case XPathScanner.LexKind.At: //>> '@' axisType = Axis.AxisType.Attribute; NextLex(); break; case XPathScanner.LexKind.Axe: //>> AxisName '::' axisType = GetAxis(); if (axisType != Axis.AxisType.Child && axisType != Axis.AxisType.Attribute) { throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText); } NextLex(); break; } XPathNodeType nodeType = ( axisType == Axis.AxisType.Attribute ? XPathNodeType.Attribute : /* default: */ XPathNodeType.Element ); opnd = ParseNodeTest(qyInput, axisType, nodeType); while (XPathScanner.LexKind.LBracket == this.scanner.Kind) { opnd = new Filter(opnd, ParsePredicate(opnd)); } return opnd; } // --------------- Helper methods ---------------------- void CheckToken(XPathScanner.LexKind t) { if (this.scanner.Kind != t) { throw XPathException.Create(SR.Xp_InvalidToken, this.scanner.SourceText); } } void PassToken(XPathScanner.LexKind t) { CheckToken(t); NextLex(); } void NextLex() { this.scanner.NextLex(); } private bool TestOp(string op) { return ( this.scanner.Kind == XPathScanner.LexKind.Name && this.scanner.Prefix.Length == 0 && this.scanner.Name.Equals(op) ); } void CheckNodeSet(XPathResultType t) { if (t != XPathResultType.NodeSet && t != XPathResultType.Any) { throw XPathException.Create(SR.Xp_NodeSetExpected, this.scanner.SourceText); } } // ---------------------------------------------------------------- static readonly XPathResultType[] temparray1 = { }; static readonly XPathResultType[] temparray2 = { XPathResultType.NodeSet }; static readonly XPathResultType[] temparray3 = { XPathResultType.Any }; static readonly XPathResultType[] temparray4 = { XPathResultType.String }; static readonly XPathResultType[] temparray5 = { XPathResultType.String, XPathResultType.String }; static readonly XPathResultType[] temparray6 = { XPathResultType.String, XPathResultType.Number, XPathResultType.Number }; static readonly XPathResultType[] temparray7 = { XPathResultType.String, XPathResultType.String, XPathResultType.String }; static readonly XPathResultType[] temparray8 = { XPathResultType.Boolean }; static readonly XPathResultType[] temparray9 = { XPathResultType.Number }; private class ParamInfo { private Function.FunctionType ftype; private int minargs; private int maxargs; private XPathResultType[] argTypes; public Function.FunctionType FType { get { return this.ftype; } } public int Minargs { get { return this.minargs; } } public int Maxargs { get { return this.maxargs; } } public XPathResultType[] ArgTypes { get { return this.argTypes; } } internal ParamInfo(Function.FunctionType ftype, int minargs, int maxargs, XPathResultType[] argTypes) { this.ftype = ftype; this.minargs = minargs; this.maxargs = maxargs; this.argTypes = argTypes; } } //ParamInfo private static Dictionary<string, ParamInfo> functionTable = CreateFunctionTable(); private static Dictionary<string, ParamInfo> CreateFunctionTable() { Dictionary<string, ParamInfo> table = new Dictionary<string, ParamInfo>(36); table.Add("last", new ParamInfo(Function.FunctionType.FuncLast, 0, 0, temparray1)); table.Add("position", new ParamInfo(Function.FunctionType.FuncPosition, 0, 0, temparray1)); table.Add("name", new ParamInfo(Function.FunctionType.FuncName, 0, 1, temparray2)); table.Add("namespace-uri", new ParamInfo(Function.FunctionType.FuncNameSpaceUri, 0, 1, temparray2)); table.Add("local-name", new ParamInfo(Function.FunctionType.FuncLocalName, 0, 1, temparray2)); table.Add("count", new ParamInfo(Function.FunctionType.FuncCount, 1, 1, temparray2)); table.Add("id", new ParamInfo(Function.FunctionType.FuncID, 1, 1, temparray3)); table.Add("string", new ParamInfo(Function.FunctionType.FuncString, 0, 1, temparray3)); table.Add("concat", new ParamInfo(Function.FunctionType.FuncConcat, 2, 100, temparray4)); table.Add("starts-with", new ParamInfo(Function.FunctionType.FuncStartsWith, 2, 2, temparray5)); table.Add("contains", new ParamInfo(Function.FunctionType.FuncContains, 2, 2, temparray5)); table.Add("substring-before", new ParamInfo(Function.FunctionType.FuncSubstringBefore, 2, 2, temparray5)); table.Add("substring-after", new ParamInfo(Function.FunctionType.FuncSubstringAfter, 2, 2, temparray5)); table.Add("substring", new ParamInfo(Function.FunctionType.FuncSubstring, 2, 3, temparray6)); table.Add("string-length", new ParamInfo(Function.FunctionType.FuncStringLength, 0, 1, temparray4)); table.Add("normalize-space", new ParamInfo(Function.FunctionType.FuncNormalize, 0, 1, temparray4)); table.Add("translate", new ParamInfo(Function.FunctionType.FuncTranslate, 3, 3, temparray7)); table.Add("boolean", new ParamInfo(Function.FunctionType.FuncBoolean, 1, 1, temparray3)); table.Add("not", new ParamInfo(Function.FunctionType.FuncNot, 1, 1, temparray8)); table.Add("true", new ParamInfo(Function.FunctionType.FuncTrue, 0, 0, temparray8)); table.Add("false", new ParamInfo(Function.FunctionType.FuncFalse, 0, 0, temparray8)); table.Add("lang", new ParamInfo(Function.FunctionType.FuncLang, 1, 1, temparray4)); table.Add("number", new ParamInfo(Function.FunctionType.FuncNumber, 0, 1, temparray3)); table.Add("sum", new ParamInfo(Function.FunctionType.FuncSum, 1, 1, temparray2)); table.Add("floor", new ParamInfo(Function.FunctionType.FuncFloor, 1, 1, temparray9)); table.Add("ceiling", new ParamInfo(Function.FunctionType.FuncCeiling, 1, 1, temparray9)); table.Add("round", new ParamInfo(Function.FunctionType.FuncRound, 1, 1, temparray9)); return table; } private static Dictionary<string, Axis.AxisType> AxesTable = CreateAxesTable(); private static Dictionary<string, Axis.AxisType> CreateAxesTable() { Dictionary<string, Axis.AxisType> table = new Dictionary<string, Axis.AxisType>(13); table.Add("ancestor", Axis.AxisType.Ancestor); table.Add("ancestor-or-self", Axis.AxisType.AncestorOrSelf); table.Add("attribute", Axis.AxisType.Attribute); table.Add("child", Axis.AxisType.Child); table.Add("descendant", Axis.AxisType.Descendant); table.Add("descendant-or-self", Axis.AxisType.DescendantOrSelf); table.Add("following", Axis.AxisType.Following); table.Add("following-sibling", Axis.AxisType.FollowingSibling); table.Add("namespace", Axis.AxisType.Namespace); table.Add("parent", Axis.AxisType.Parent); table.Add("preceding", Axis.AxisType.Preceding); table.Add("preceding-sibling", Axis.AxisType.PrecedingSibling); table.Add("self", Axis.AxisType.Self); return table; } private Axis.AxisType GetAxis() { Debug.Assert(scanner.Kind == XPathScanner.LexKind.Axe); Axis.AxisType axis; if (!AxesTable.TryGetValue(scanner.Name, out axis)) { throw XPathException.Create(SR.Xp_InvalidToken, scanner.SourceText); } return axis; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Text.RegularExpressions; #pragma warning disable 1591 #pragma warning disable 3001 namespace MbUnit.Framework { /// <summary> /// String Assertion class /// </summary> [Obsolete("Use Assert instead.")] public static class OldStringAssert { /// <summary> /// Asserts that two strings are equal, ignoring the case /// </summary> /// <param name="s1"> /// Expected string. /// </param> /// <param name="s2"> /// Actual string. /// </param> public static void AreEqualIgnoreCase(string s1, string s2) { if (s1==null || s2==null) Assert.AreEqual(s1,s2); else Assert.AreEqual(s1.ToLower(), s2.ToLower()); } /// <summary> /// Asserts that the string is non null and empty /// </summary> /// <param name="s"> /// String to test. /// </param> public static void IsEmpty(String s) { Assert.IsNotNull(s,"String is null"); Assert.AreEqual(0,s.Length, "String count is not 0"); } /// <summary> /// Asserts that the string is non null and non empty /// </summary> /// <param name="s"> /// String to test. /// </param> public static void IsNonEmpty(String s) { Assert.IsNotNull(s,"String is null"); Assert.IsTrue(s.Length!=0, "String count is 0"); } /// <summary> /// Asserts the regular expression reg makes a full match on s /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="reg"> /// Regular expression. /// </param> public static void FullMatch(String s, string reg) { Regex regex = new Regex(reg); FullMatch(s,regex); } /// <summary> /// Asserts the regular expression regex makes a full match on ///<paramref name="s"/>. /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="regex"> /// Regular expression. /// </param> public static void FullMatch(String s, Regex regex) { Assert.IsNotNull(regex); Match m = regex.Match(s); Assert.IsTrue(m.Success, "Match is not successful"); Assert.AreEqual(s.Length, m.Length, "Not a full match"); } /// <summary> /// Asserts the regular expression reg makes a match on s /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="reg"> /// Regular expression. /// </param> public static void Like(String s, string reg) { Regex regex = new Regex(reg); Like(s,regex); } /// <summary> /// Asserts the regular expression regex makes a match on s /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="regex"> /// A <see cref="Regex"/> instance. /// </param> public static void Like(String s, Regex regex) { Assert.IsNotNull(regex); Match m = regex.Match(s); Assert.IsTrue(m.Success, "Match is not successful"); } /// <summary> /// Asserts the regular expression reg makes a match on s /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="reg"> /// Regular expression. /// </param> public static void NotLike(String s, string reg) { Regex regex = new Regex(reg); NotLike(s,regex); } /// <summary> /// Asserts the regular expression regex makes a match on s /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="regex"> /// A <see cref="Regex"/> instance. /// </param> public static void NotLike(String s, Regex regex) { Assert.IsNotNull(regex); Match m = regex.Match(s); Assert.IsFalse(m.Success, "Match was found successful"); } /// <summary> /// Asserts the string does not contain c /// </summary> /// <param name="s"> /// String to test. /// </param> /// <param name="anyOf"> /// Variable list of characeters. /// </param> public static void DoesNotContain(String s, params char[] anyOf) { if (s==null) return; Assert.AreEqual(-1, s.IndexOfAny(anyOf), "{0} contains at {1}", s,s.IndexOfAny(anyOf)); } public static void StartsWith(String s, string pattern) { Assert.IsTrue(s.StartsWith(pattern), "String [[{0}]] does not start with [[{1}]]", s, pattern); } public static void EndsWith(String s, string pattern) { Assert.IsTrue(s.EndsWith(pattern), "String [[{0}]] does not end with [[{1}]]", s, pattern); } public static void Contains(String s, string contain) { Assert.IsTrue(s.IndexOf(contain) >= 0, "String [[{0}]] does not contain [[{1}]]", s, contain); } } }
#region Copyright /*Copyright (C) 2015 Wosad 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. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Wosad.WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; #if !NET_3_5 using System.Collections.ObjectModel; using System.Collections.Specialized; #endif using System.Linq; using System.Linq.Expressions; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Clauses.StreamedData; using Remotion.Linq.Parsing; #if NET_3_5 using Remotion.Linq.Collections; #endif using Remotion.Linq.Parsing.Structure; using Remotion.Linq.Utilities; using Remotion.Utilities; namespace Remotion.Linq { /// <summary> /// Provides an abstraction of an expression tree created for a LINQ query. <see cref="QueryModel"/> instances are passed to LINQ providers based /// on re-linq via <see cref="IQueryExecutor"/>, but you can also use <see cref="QueryParser"/> to parse an expression tree by hand or construct /// a <see cref="QueryModel"/> manually via its constructor. /// </summary> /// <remarks> /// The different parts of the query are mapped to clauses, see <see cref="MainFromClause"/>, <see cref="BodyClauses"/>, and /// <see cref="SelectClause"/>. The simplest way to process all the clauses belonging to a <see cref="QueryModel"/> is by implementing /// <see cref="IQueryModelVisitor"/> (or deriving from <see cref="QueryModelVisitorBase"/>) and calling <see cref="Accept"/>. /// </remarks> public sealed class QueryModel { private sealed class CloningExpressionVisitor : RelinqExpressionVisitor { private readonly QuerySourceMapping _querySourceMapping; public CloningExpressionVisitor (QuerySourceMapping querySourceMapping) { _querySourceMapping = querySourceMapping; } protected internal override Expression VisitQuerySourceReference (QuerySourceReferenceExpression expression) { if (_querySourceMapping.ContainsMapping (expression.ReferencedQuerySource)) return _querySourceMapping.GetExpression (expression.ReferencedQuerySource); return expression; } protected internal override Expression VisitSubQuery (SubQueryExpression expression) { var clonedQueryModel = expression.QueryModel.Clone (_querySourceMapping); return new SubQueryExpression (clonedQueryModel); } #if NET_3_5 protected override Expression VisitRelinqUnknownNonExtension (Expression expression) { //ignore return expression; } #endif } private readonly UniqueIdentifierGenerator _uniqueIdentifierGenerator; private MainFromClause _mainFromClause; private SelectClause _selectClause; /// <summary> /// Initializes a new instance of <see cref="QueryModel"/> /// </summary> /// <param name="mainFromClause">The <see cref="Clauses.MainFromClause"/> of the query. This is the starting point of the query, generating items /// that are filtered and projected by the query.</param> /// <param name="selectClause">The <see cref="SelectClause"/> of the query. This is the end point of /// the query, it defines what is actually returned for each of the items coming from the <see cref="MainFromClause"/> and passing the /// <see cref="BodyClauses"/>. After it, only the <see cref="ResultOperators"/> modify the result of the query.</param> public QueryModel (MainFromClause mainFromClause, SelectClause selectClause) { ArgumentUtility.CheckNotNull ("mainFromClause", mainFromClause); ArgumentUtility.CheckNotNull ("selectClause", selectClause); _uniqueIdentifierGenerator = new UniqueIdentifierGenerator(); MainFromClause = mainFromClause; SelectClause = selectClause; BodyClauses = new ObservableCollection<IBodyClause>(); BodyClauses.CollectionChanged += BodyClauses_CollectionChanged; ResultOperators = new ObservableCollection<ResultOperatorBase>(); ResultOperators.CollectionChanged += ResultOperators_CollectionChanged; } public Type ResultTypeOverride { get; set; } public Type GetResultType () { return GetOutputDataInfo ().DataType; } /// <summary> /// Gets an <see cref="IStreamedDataInfo"/> object describing the data streaming out of this <see cref="QueryModel"/>. If a query ends with /// the <see cref="SelectClause"/>, this corresponds to <see cref="Clauses.SelectClause.GetOutputDataInfo"/>. If a query has /// <see cref="QueryModel.ResultOperators"/>, the data is further modified by those operators. /// </summary> /// <returns>Gets a <see cref="IStreamedDataInfo"/> object describing the data streaming out of this <see cref="QueryModel"/>.</returns> /// <remarks> /// The data streamed from a <see cref="QueryModel"/> is often of type <see cref="IQueryable{T}"/> instantiated /// with a specific item type, unless the /// query ends with a <see cref="ResultOperatorBase"/>. For example, if the query ends with a <see cref="CountResultOperator"/>, the /// result type will be <see cref="int"/>. /// </remarks> public IStreamedDataInfo GetOutputDataInfo () { var outputDataInfo = ResultOperators .Aggregate ((IStreamedDataInfo) SelectClause.GetOutputDataInfo (), (current, resultOperator) => resultOperator.GetOutputDataInfo (current)); if (ResultTypeOverride != null) return outputDataInfo.AdjustDataType (ResultTypeOverride); else return outputDataInfo; } /// <summary> /// Gets or sets the query's <see cref="Clauses.MainFromClause"/>. This is the starting point of the query, generating items that are processed by /// the <see cref="BodyClauses"/> and projected or grouped by the <see cref="SelectClause"/>. /// </summary> public MainFromClause MainFromClause { get { return _mainFromClause; } set { ArgumentUtility.CheckNotNull ("value", value); _mainFromClause = value; _uniqueIdentifierGenerator.AddKnownIdentifier (value.ItemName); } } /// <summary> /// Gets or sets the query's select clause. This is the end point of the query, it defines what is actually returned for each of the /// items coming from the <see cref="MainFromClause"/> and passing the <see cref="BodyClauses"/>. After it, only the <see cref="ResultOperators"/> /// modify the result of the query. /// </summary> public SelectClause SelectClause { get { return _selectClause; } set { ArgumentUtility.CheckNotNull ("value", value); _selectClause = value; } } /// <summary> /// Gets a collection representing the query's body clauses. Body clauses take the items generated by the <see cref="MainFromClause"/>, /// filtering (<see cref="WhereClause"/>), ordering (<see cref="OrderByClause"/>), augmenting (<see cref="AdditionalFromClause"/>), or otherwise /// processing them before they are passed to the <see cref="SelectClause"/>. /// </summary> public ObservableCollection<IBodyClause> BodyClauses { get; private set; } /// <summary> /// Gets the result operators attached to this <see cref="SelectClause"/>. Result operators modify the query's result set, aggregating, /// filtering, or otherwise processing the result before it is returned. /// </summary> public ObservableCollection<ResultOperatorBase> ResultOperators { get; private set; } /// <summary> /// Gets the <see cref="UniqueIdentifierGenerator"/> which is used by the <see cref="QueryModel"/>. /// </summary> /// <returns></returns> public UniqueIdentifierGenerator GetUniqueIdentfierGenerator () { return _uniqueIdentifierGenerator; } private void ResultOperators_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e) { ArgumentUtility.CheckNotNull ("e", e); ArgumentUtility.CheckItemsNotNullAndType ("e.NewItems", e.NewItems, typeof (ResultOperatorBase)); } /// <summary> /// Accepts an implementation of <see cref="IQueryModelVisitor"/> or <see cref="QueryModelVisitorBase"/>, as defined by the Visitor pattern. /// </summary> public void Accept (IQueryModelVisitor visitor) { ArgumentUtility.CheckNotNull ("visitor", visitor); visitor.VisitQueryModel (this); } /// <summary> /// Returns a <see cref="System.String"/> representation of this <see cref="QueryModel"/>. /// </summary> public override string ToString () { string mainQueryString; if (IsIdentityQuery ()) { mainQueryString = MainFromClause.FromExpression.BuildString(); } else { mainQueryString = MainFromClause + BodyClauses.Aggregate ("", (s, b) => s + " " + b) + " " + SelectClause; } return ResultOperators.Aggregate (mainQueryString, (s, r) => s + " => " + r); } /// <summary> /// Clones this <see cref="QueryModel"/>, returning a new <see cref="QueryModel"/> equivalent to this instance, but with its clauses being /// clones of this instance's clauses. Any <see cref="QuerySourceReferenceExpression"/> in the cloned clauses that points back to another clause /// in this <see cref="QueryModel"/> (including its subqueries) is adjusted to point to the respective clones in the cloned /// <see cref="QueryModel"/>. Any subquery nested in the <see cref="QueryModel"/> is also cloned. /// </summary> public QueryModel Clone () { return Clone (new QuerySourceMapping()); } /// <summary> /// Clones this <see cref="QueryModel"/>, returning a new <see cref="QueryModel"/> equivalent to this instance, but with its clauses being /// clones of this instance's clauses. Any <see cref="QuerySourceReferenceExpression"/> in the cloned clauses that points back to another clause /// in this <see cref="QueryModel"/> (including its subqueries) is adjusted to point to the respective clones in the cloned /// <see cref="QueryModel"/>. Any subquery nested in the <see cref="QueryModel"/> is also cloned. /// </summary> /// <param name="querySourceMapping">The <see cref="QuerySourceMapping"/> defining how to adjust instances of /// <see cref="QuerySourceReferenceExpression"/> in the cloned <see cref="QueryModel"/>. If there is a <see cref="QuerySourceReferenceExpression"/> /// that points out of the <see cref="QueryModel"/> being cloned, specify its replacement via this parameter. At the end of the cloning process, /// this object maps all the clauses in this original <see cref="QueryModel"/> to the clones created in the process. /// </param> public QueryModel Clone (QuerySourceMapping querySourceMapping) { ArgumentUtility.CheckNotNull ("querySourceMapping", querySourceMapping); var cloneContext = new CloneContext (querySourceMapping); var queryModelBuilder = new QueryModelBuilder(); queryModelBuilder.AddClause (MainFromClause.Clone (cloneContext)); foreach (var bodyClause in BodyClauses) queryModelBuilder.AddClause (bodyClause.Clone (cloneContext)); queryModelBuilder.AddClause (SelectClause.Clone (cloneContext)); foreach (var resultOperator in ResultOperators) { var resultOperatorClone = resultOperator.Clone (cloneContext); queryModelBuilder.AddResultOperator (resultOperatorClone); } var clone = queryModelBuilder.Build (); var cloningExpressionVisitor = new CloningExpressionVisitor (cloneContext.QuerySourceMapping); clone.TransformExpressions (cloningExpressionVisitor.Visit); clone.ResultTypeOverride = ResultTypeOverride; return clone; } /// <summary> /// Transforms all the expressions in this <see cref="QueryModel"/>'s clauses via the given <paramref name="transformation"/> delegate. /// </summary> /// <param name="transformation">The transformation object. This delegate is called for each <see cref="Expression"/> within this /// <see cref="QueryModel"/>, and those expressions will be replaced with what the delegate returns.</param> public void TransformExpressions (Func<Expression, Expression> transformation) { ArgumentUtility.CheckNotNull ("transformation", transformation); MainFromClause.TransformExpressions (transformation); foreach (var bodyClause in BodyClauses) bodyClause.TransformExpressions (transformation); SelectClause.TransformExpressions (transformation); foreach (var resultOperator in ResultOperators) resultOperator.TransformExpressions (transformation); } /// <summary> /// Returns a new name with the given prefix. The name is different from that of any <see cref="FromClauseBase"/> added /// in the <see cref="QueryModel"/>. Note that clause names that are changed after the clause is added as well as names of other clauses /// than from clauses are not considered when determining "unique" names. Use names only for readability and debugging, not /// for uniquely identifying clauses. /// </summary> public string GetNewName (string prefix) { ArgumentUtility.CheckNotNullOrEmpty ("prefix", prefix); return _uniqueIdentifierGenerator.GetUniqueIdentifier (prefix); } private void BodyClauses_CollectionChanged (object sender, NotifyCollectionChangedEventArgs e) { ArgumentUtility.CheckNotNull ("e", e); ArgumentUtility.CheckItemsNotNullAndType ("e.NewItems", e.NewItems, typeof (IBodyClause)); if (e.NewItems != null) { foreach (var fromClause in e.NewItems.OfType<IFromClause>()) _uniqueIdentifierGenerator.AddKnownIdentifier (fromClause.ItemName); } } /// <summary> /// Executes this <see cref="QueryModel"/> via the given <see cref="IQueryExecutor"/>. By default, this indirectly calls /// <see cref="IQueryExecutor.ExecuteCollection{T}"/>, but this can be modified by the <see cref="ResultOperators"/>. /// </summary> /// <param name="executor">The <see cref="IQueryExecutor"/> to use for executing this query.</param> public IStreamedData Execute (IQueryExecutor executor) { ArgumentUtility.CheckNotNull ("executor", executor); var dataInfo = GetOutputDataInfo(); return dataInfo.ExecuteQueryModel (this, executor); } /// <summary> /// Determines whether this <see cref="QueryModel"/> represents an identity query. An identity query is a query without any body clauses /// whose <see cref="SelectClause"/> selects exactly the items produced by its <see cref="MainFromClause"/>. An identity query can have /// <see cref="ResultOperators"/>. /// </summary> /// <returns> /// <see langword="true" /> if this <see cref="QueryModel"/> represents an identity query; otherwise, <see langword="false" />. /// </returns> /// <example> /// An example for an identity query is the subquery in that is produced for the <see cref="Clauses.SelectClause.Selector"/> in the following /// query: /// <code> /// from order in ... /// select order.OrderItems.Count() /// </code> /// In this query, the <see cref="Clauses.SelectClause.Selector"/> will become a <see cref="SubQueryExpression"/> because /// <see cref="Enumerable.Count{TSource}(System.Collections.Generic.IEnumerable{TSource})"/> is treated as a query operator. The /// <see cref="QueryModel"/> in that <see cref="SubQueryExpression"/> has no <see cref="BodyClauses"/> and a trivial <see cref="SelectClause"/>, /// so its <see cref="IsIdentityQuery"/> method returns <see langword="true" />. The outer <see cref="QueryModel"/>, on the other hand, does not /// have a trivial <see cref="SelectClause"/>, so its <see cref="IsIdentityQuery"/> method returns <see langword="false" />. /// </example> public bool IsIdentityQuery () { return BodyClauses.Count == 0 && SelectClause.Selector is QuerySourceReferenceExpression && ((QuerySourceReferenceExpression) SelectClause.Selector).ReferencedQuerySource == MainFromClause; } /// <summary> /// Creates a new <see cref="QueryModel"/> that has this <see cref="QueryModel"/> as a sub-query in its <see cref="MainFromClause"/>. /// </summary> /// <param name="itemName">The name of the new <see cref="QueryModel"/>'s <see cref="FromClauseBase.ItemName"/>.</param> /// <returns>A new <see cref="QueryModel"/> whose <see cref="MainFromClause"/>'s <see cref="FromClauseBase.FromExpression"/> is a /// <see cref="SubQueryExpression"/> that holds this <see cref="QueryModel"/> instance.</returns> public QueryModel ConvertToSubQuery (string itemName) { ArgumentUtility.CheckNotNullOrEmpty ("itemName", itemName); var outputDataInfo = GetOutputDataInfo() as StreamedSequenceInfo; if (outputDataInfo == null) { var message = string.Format ( "The query must return a sequence of items, but it selects a single object of type '{0}'.", GetOutputDataInfo ().DataType); throw new InvalidOperationException (message); } // from x in (sourceItemQuery) // select x var mainFromClause = new MainFromClause ( itemName, outputDataInfo.ResultItemType, new SubQueryExpression (this)); var selectClause = new SelectClause (new QuerySourceReferenceExpression (mainFromClause)); return new QueryModel (mainFromClause, selectClause); } } }
namespace XmlUnit { using System; using System.Collections; using System.IO; using System.Xml; using System.Xml.Schema; public class XmlDiff { private const string XMLNS_PREFIX = "xmlns"; private readonly XmlInput controlInput; private readonly XmlInput testInput; private readonly DiffConfiguration _diffConfiguration; private DiffResult _diffResult; public XmlDiff(XmlInput control, XmlInput test, DiffConfiguration diffConfiguration) { _diffConfiguration = diffConfiguration; controlInput = control; testInput = test; } public XmlDiff(XmlInput control, XmlInput test) : this(control, test, new DiffConfiguration()) { } public XmlDiff(TextReader control, TextReader test) : this(new XmlInput(control), new XmlInput(test)) { } public XmlDiff(string control, string test) : this(new XmlInput(control), new XmlInput(test)) { } private XmlReader CreateXmlReader(XmlInput forInput) { XmlReader xmlReader = forInput.CreateXmlReader(); if (xmlReader is XmlTextReader) { ((XmlTextReader) xmlReader ).WhitespaceHandling = _diffConfiguration.WhitespaceHandling; } if (_diffConfiguration.UseValidatingParser) { XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); return validatingReader; } return xmlReader; } public DiffResult Compare() { if (_diffResult == null) { _diffResult = new DiffResult(); XmlReader controlReader, testReader; controlReader = testReader = null; try { controlReader = CreateXmlReader(controlInput); testReader = CreateXmlReader(testInput); if (!controlInput.Equals(testInput)) { Compare(_diffResult, controlReader, testReader); } } finally { try { if (testReader != null) { testReader.Close(); } } finally { if (controlReader != null) { controlReader.Close(); } } } } return _diffResult; } private void Compare(DiffResult result, XmlReader controlReader, XmlReader testReader) { try { ReaderWithState control = new ReaderWithState(controlReader); ReaderWithState test = new ReaderWithState(testReader); do { control.Read(); test.Read(); Compare(result, control, test); } while (control.HasRead && test.HasRead) ; } catch (FlowControlException e) { Console.Out.WriteLine(e.Message); } } private void Compare(DiffResult result, ReaderWithState control, ReaderWithState test) { if (control.HasRead) { if (test.HasRead) { CompareNodes(result, control, test); CheckEmptyOrAtEndElement(result, control, test); } else { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } } private void CompareNodes(DiffResult result, ReaderWithState control, ReaderWithState test) { XmlNodeType controlNodeType = control.Reader.NodeType; XmlNodeType testNodeType = test.Reader.NodeType; if (!controlNodeType.Equals(testNodeType)) { CheckNodeTypes(controlNodeType, testNodeType, result, control, test); } else if (controlNodeType == XmlNodeType.Element) { CompareElements(result, control, test); } else if (controlNodeType == XmlNodeType.Text) { CompareText(result, control, test); } } private void CheckNodeTypes(XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result, ReaderWithState control, ReaderWithState test) { ReaderWithState readerToAdvance = null; if (controlNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = control; } else if (testNodeType.Equals(XmlNodeType.XmlDeclaration)) { readerToAdvance = test; } if (readerToAdvance != null) { DifferenceFound(DifferenceType.HAS_XML_DECLARATION_PREFIX_ID, controlNodeType, testNodeType, result); readerToAdvance.Read(); CompareNodes(result, control, test); } else { DifferenceFound(DifferenceType.NODE_TYPE_ID, controlNodeType, testNodeType, result); } } private void CompareElements(DiffResult result, ReaderWithState control, ReaderWithState test) { string controlTagName = control.Reader.Name; string testTagName = test.Reader.Name; if (!String.Equals(controlTagName, testTagName)) { DifferenceFound(DifferenceType.ELEMENT_TAG_NAME_ID, result); } else { XmlAttribute[] controlAttributes = GetNonSpecialAttributes(control); XmlAttribute[] testAttributes = GetNonSpecialAttributes(test); if (controlAttributes.Length != testAttributes.Length) { DifferenceFound(DifferenceType.ELEMENT_NUM_ATTRIBUTES_ID, result); } CompareAttributes(result, controlAttributes, testAttributes); } } private void CompareAttributes(DiffResult result, XmlAttribute[] controlAttributes, XmlAttribute[] testAttributes) { ArrayList unmatchedTestAttributes = new ArrayList(); unmatchedTestAttributes.AddRange(testAttributes); for (int i=0; i < controlAttributes.Length; ++i) { bool controlIsInNs = IsNamespaced(controlAttributes[i]); string controlAttrName = GetUnNamespacedNodeName(controlAttributes[i]); XmlAttribute testAttr = null; if (!controlIsInNs) { testAttr = FindAttributeByName(testAttributes, controlAttrName); } else { testAttr = FindAttributeByNameAndNs(testAttributes, controlAttrName, controlAttributes[i] .NamespaceURI); } if (testAttr != null) { unmatchedTestAttributes.Remove(testAttr); if (!_diffConfiguration.IgnoreAttributeOrder && testAttr != testAttributes[i]) { DifferenceFound(DifferenceType.ATTR_SEQUENCE_ID, result); } if (controlAttributes[i].Value != testAttr.Value) { DifferenceFound(DifferenceType.ATTR_VALUE_ID, result); } } else { DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID, result); } } foreach (XmlAttribute a in unmatchedTestAttributes) { DifferenceFound(DifferenceType.ATTR_NAME_NOT_FOUND_ID, result); } } private void CompareText(DiffResult result, ReaderWithState control, ReaderWithState test) { string controlText = control.Reader.Value; string testText = test.Reader.Value; if (!String.Equals(controlText, testText)) { DifferenceFound(DifferenceType.TEXT_VALUE_ID, result); } } private void DifferenceFound(DifferenceType differenceType, DiffResult result) { DifferenceFound(new Difference(differenceType), result); } private void DifferenceFound(Difference difference, DiffResult result) { result.DifferenceFound(this, difference); if (!ContinueComparison(difference)) { throw new FlowControlException(difference); } } private void DifferenceFound(DifferenceType differenceType, XmlNodeType controlNodeType, XmlNodeType testNodeType, DiffResult result) { DifferenceFound(new Difference(differenceType, controlNodeType, testNodeType), result); } private bool ContinueComparison(Difference afterDifference) { return !afterDifference.MajorDifference; } private void CheckEmptyOrAtEndElement(DiffResult result, ReaderWithState control, ReaderWithState test) { if (control.LastElementWasEmpty) { if (!test.LastElementWasEmpty) { CheckEndElement(test, result); } } else { if (test.LastElementWasEmpty) { CheckEndElement(control, result); } } } private XmlAttribute[] GetNonSpecialAttributes(ReaderWithState r) { ArrayList l = new ArrayList(); int length = r.Reader.AttributeCount; if (length > 0) { XmlDocument doc = new XmlDocument(); r.Reader.MoveToFirstAttribute(); for (int i = 0; i < length; i++) { XmlAttribute a = doc.CreateAttribute(r.Reader.Name, r.Reader.NamespaceURI); if (!IsXMLNSAttribute(a)) { a.Value = r.Reader.Value; l.Add(a); } r.Reader.MoveToNextAttribute(); } } return (XmlAttribute[]) l.ToArray(typeof(XmlAttribute)); } private bool IsXMLNSAttribute(XmlAttribute attribute) { return XMLNS_PREFIX == attribute.Prefix || XMLNS_PREFIX == attribute.Name; } private XmlAttribute FindAttributeByName(XmlAttribute[] attrs, string name) { foreach (XmlAttribute a in attrs) { if (GetUnNamespacedNodeName(a) == name) { return a; } } return null; } private XmlAttribute FindAttributeByNameAndNs(XmlAttribute[] attrs, string name, string nsUri) { foreach (XmlAttribute a in attrs) { if (GetUnNamespacedNodeName(a) == name && a.NamespaceURI == nsUri) { return a; } } return null; } private string GetUnNamespacedNodeName(XmlNode aNode) { return GetUnNamespacedNodeName(aNode, IsNamespaced(aNode)); } private string GetUnNamespacedNodeName(XmlNode aNode, bool isNamespacedNode) { if (isNamespacedNode) { return aNode.LocalName; } return aNode.Name; } private bool IsNamespaced(XmlNode aNode) { string ns = aNode.NamespaceURI; return ns != null && ns.Length > 0; } private void CheckEndElement(ReaderWithState reader, DiffResult result) { bool readResult = reader.Read(); if (!readResult || reader.Reader.NodeType != XmlNodeType.EndElement) { DifferenceFound(DifferenceType.CHILD_NODELIST_LENGTH_ID, result); } } public string OptionalDescription { get { return _diffConfiguration.Description; } } private class FlowControlException : ApplicationException { public FlowControlException(Difference cause) : base(cause.ToString()) { } } private class ReaderWithState { internal ReaderWithState(XmlReader reader) { Reader = reader; HasRead = false; LastElementWasEmpty = false; } internal readonly XmlReader Reader; internal bool HasRead; internal bool LastElementWasEmpty; internal bool Read() { HasRead = Reader.Read(); if (HasRead) { switch (Reader.NodeType) { case XmlNodeType.Element: LastElementWasEmpty = Reader.IsEmptyElement; break; case XmlNodeType.EndElement: LastElementWasEmpty = false; break; default: // don't care break; } } return HasRead; } internal string State { get { return string.Format("Name {0}, NodeType {1}, IsEmpty {2}," + " HasRead {3}, LastWasEmpty {4}", Reader.Name, Reader.NodeType, Reader.IsEmptyElement, HasRead, LastElementWasEmpty); } } } } }
// 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 gcbv = Google.Cloud.BinaryAuthorization.V1; using sys = System; namespace Google.Cloud.BinaryAuthorization.V1 { /// <summary>Resource name for the <c>Policy</c> resource.</summary> public sealed partial class PolicyName : gax::IResourceName, sys::IEquatable<PolicyName> { /// <summary>The possible contents of <see cref="PolicyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/policy</c>.</summary> Project = 1, /// <summary>A resource name with pattern <c>locations/{location}/policy</c>.</summary> Location = 2, } private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}/policy"); private static gax::PathTemplate s_location = new gax::PathTemplate("locations/{location}/policy"); /// <summary>Creates a <see cref="PolicyName"/> 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="PolicyName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static PolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary>Creates a <see cref="PolicyName"/> with the pattern <c>projects/{project}/policy</c>.</summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns> public static PolicyName FromProject(string projectId) => new PolicyName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))); /// <summary>Creates a <see cref="PolicyName"/> with the pattern <c>locations/{location}/policy</c>.</summary> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PolicyName"/> constructed from the provided ids.</returns> public static PolicyName FromLocation(string locationId) => new PolicyName(ResourceNameType.Location, locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern /// <c>projects/{project}/policy</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyName"/> with pattern <c>projects/{project}/policy</c>. /// </returns> public static string Format(string projectId) => FormatProject(projectId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern /// <c>projects/{project}/policy</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyName"/> with pattern <c>projects/{project}/policy</c>. /// </returns> public static string FormatProject(string projectId) => s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PolicyName"/> with pattern /// <c>locations/{location}/policy</c>. /// </summary> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PolicyName"/> with pattern <c>locations/{location}/policy</c>. /// </returns> public static string FormatLocation(string locationId) => s_location.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId))); /// <summary>Parses the given resource name string into a new <see cref="PolicyName"/> 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}/policy</c></description></item> /// <item><description><c>locations/{location}/policy</c></description></item> /// </list> /// </remarks> /// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PolicyName"/> if successful.</returns> public static PolicyName Parse(string policyName) => Parse(policyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PolicyName"/> 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}/policy</c></description></item> /// <item><description><c>locations/{location}/policy</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyName">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="PolicyName"/> if successful.</returns> public static PolicyName Parse(string policyName, bool allowUnparsed) => TryParse(policyName, allowUnparsed, out PolicyName 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="PolicyName"/> 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}/policy</c></description></item> /// <item><description><c>locations/{location}/policy</c></description></item> /// </list> /// </remarks> /// <param name="policyName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PolicyName"/>, 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 policyName, out PolicyName result) => TryParse(policyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PolicyName"/> 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}/policy</c></description></item> /// <item><description><c>locations/{location}/policy</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="policyName">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="PolicyName"/>, 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 policyName, bool allowUnparsed, out PolicyName result) { gax::GaxPreconditions.CheckNotNull(policyName, nameof(policyName)); gax::TemplatedResourceName resourceName; if (s_project.TryParseName(policyName, out resourceName)) { result = FromProject(resourceName[0]); return true; } if (s_location.TryParseName(policyName, out resourceName)) { result = FromLocation(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(policyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="PolicyName"/> class from the component parts of pattern /// <c>projects/{project}/policy</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> public PolicyName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId))) { } /// <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. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { 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.Project: return s_project.Expand(ProjectId); case ResourceNameType.Location: return s_location.Expand(LocationId); 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 PolicyName); /// <inheritdoc/> public bool Equals(PolicyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PolicyName a, PolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PolicyName a, PolicyName b) => !(a == b); } /// <summary>Resource name for the <c>Attestor</c> resource.</summary> public sealed partial class AttestorName : gax::IResourceName, sys::IEquatable<AttestorName> { /// <summary>The possible contents of <see cref="AttestorName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/attestors/{attestor}</c>.</summary> ProjectAttestor = 1, } private static gax::PathTemplate s_projectAttestor = new gax::PathTemplate("projects/{project}/attestors/{attestor}"); /// <summary>Creates a <see cref="AttestorName"/> 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="AttestorName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static AttestorName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AttestorName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AttestorName"/> with the pattern <c>projects/{project}/attestors/{attestor}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AttestorName"/> constructed from the provided ids.</returns> public static AttestorName FromProjectAttestor(string projectId, string attestorId) => new AttestorName(ResourceNameType.ProjectAttestor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), attestorId: gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AttestorName"/> with pattern /// <c>projects/{project}/attestors/{attestor}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AttestorName"/> with pattern /// <c>projects/{project}/attestors/{attestor}</c>. /// </returns> public static string Format(string projectId, string attestorId) => FormatProjectAttestor(projectId, attestorId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AttestorName"/> with pattern /// <c>projects/{project}/attestors/{attestor}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AttestorName"/> with pattern /// <c>projects/{project}/attestors/{attestor}</c>. /// </returns> public static string FormatProjectAttestor(string projectId, string attestorId) => s_projectAttestor.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId))); /// <summary>Parses the given resource name string into a new <see cref="AttestorName"/> 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}/attestors/{attestor}</c></description></item> /// </list> /// </remarks> /// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AttestorName"/> if successful.</returns> public static AttestorName Parse(string attestorName) => Parse(attestorName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AttestorName"/> 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}/attestors/{attestor}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="attestorName">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="AttestorName"/> if successful.</returns> public static AttestorName Parse(string attestorName, bool allowUnparsed) => TryParse(attestorName, allowUnparsed, out AttestorName 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="AttestorName"/> 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}/attestors/{attestor}</c></description></item> /// </list> /// </remarks> /// <param name="attestorName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AttestorName"/>, 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 attestorName, out AttestorName result) => TryParse(attestorName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AttestorName"/> 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}/attestors/{attestor}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="attestorName">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="AttestorName"/>, 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 attestorName, bool allowUnparsed, out AttestorName result) { gax::GaxPreconditions.CheckNotNull(attestorName, nameof(attestorName)); gax::TemplatedResourceName resourceName; if (s_projectAttestor.TryParseName(attestorName, out resourceName)) { result = FromProjectAttestor(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(attestorName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AttestorName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string attestorId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; AttestorId = attestorId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="AttestorName"/> class from the component parts of pattern /// <c>projects/{project}/attestors/{attestor}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="attestorId">The <c>Attestor</c> ID. Must not be <c>null</c> or empty.</param> public AttestorName(string projectId, string attestorId) : this(ResourceNameType.ProjectAttestor, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), attestorId: gax::GaxPreconditions.CheckNotNullOrEmpty(attestorId, nameof(attestorId))) { } /// <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>Attestor</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AttestorId { 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>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.ProjectAttestor: return s_projectAttestor.Expand(ProjectId, AttestorId); 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 AttestorName); /// <inheritdoc/> public bool Equals(AttestorName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AttestorName a, AttestorName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AttestorName a, AttestorName b) => !(a == b); } public partial class Policy { /// <summary> /// <see cref="gcbv::PolicyName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbv::PolicyName PolicyName { get => string.IsNullOrEmpty(Name) ? null : gcbv::PolicyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Attestor { /// <summary> /// <see cref="gcbv::AttestorName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbv::AttestorName AttestorName { get => string.IsNullOrEmpty(Name) ? null : gcbv::AttestorName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using UnityEngine; using System.Collections; [AddComponentMenu("DudeWorld/Dude Controller")] public class DudeController : MonoBehaviour { public int humanPlayer; public bool cardinalMovement; public string aimMethod = "mouse"; public Transform animated; private Vector3 forward = Vector3.forward; private Dude dude; private SwordzDude swordz; private bool itemUsed = false; private Camera cam; private Vector3 axisX = new Vector3( 0.5f, 0.0f, 0.5f); private Vector3 axisY = new Vector3(-0.5f, 0.0f, 0.5f); private Vector3 moveVec; private bool disabled = false; public void Start() { dude = GetComponent(typeof(Dude)) as Dude; swordz = GetComponent(typeof(SwordzDude)) as SwordzDude; cam = Camera.main; if( aimMethod == "mouse" ) Screen.showCursor = true; // automatically set up move axes to match the camera SetMovementAxes(cam.transform.right * 0.5f, cam.transform.forward * 0.5f); } public void SetMovementAxes(Vector3 x, Vector3 y) { axisX = x; axisY = y; } public void SetMovementDirection(Vector3 newForward) { Vector3 cameraLook = newForward - transform.position; var right = Vector3.Cross(Vector3.up, cameraLook); SetMovementAxes(right.normalized * 0.5f, cameraLook.normalized * 0.5f); } public Vector3 GetCurrentMoveVec() { var movex = Input.GetAxis("Horizontal_"+humanPlayer); var movey = Input.GetAxis("Vertical_"+humanPlayer); // clamp to maximum /* if( movex != 0.0f ) movex = Mathf.Sign(movex) * 1.0f; if( movey != 0.0f ) movey = Mathf.Sign(movey) * 1.0f; */ var finalMove = Vector3.zero; if(movex != 0.0f || movey != 0.0f) { finalMove = (movex * axisX) + (movey * axisY); if(finalMove.sqrMagnitude < 1.0f) finalMove = finalMove.normalized; } return finalMove; } public void FixedUpdate() //function Update() { if(disabled) return; if(cardinalMovement) { var finalMove = GetCurrentMoveVec(); if(finalMove != Vector3.zero) { moveVec = finalMove; if(swordz != null) { if(swordz.status.blocking) finalMove *= 0.6f; if(!swordz.status.dodging) { //animated.animation.Blend("bjorn_walk"); } } /* movex = cam.transform.right.x * movex; movey = cam.transform.up.y * movey; var move_up = transform.position - cam.transform.position; move_up.y = 0; move_up = move_up.normalized; var move_right = cam.transform.right; var finalMove = (move_right * movex) + (move_up * movey); */ if(aimMethod == "hold_direction") { if(swordz != null && !swordz.status.attacking && !swordz.status.attackingRecovery) { if(Input.GetButtonDown("Attack_"+humanPlayer) || Input.GetButtonDown("Dodge_"+humanPlayer) || Input.GetButtonDown("Block_"+humanPlayer) || swordz.status.dodging) { dude.RawMovement(finalMove, true, true); } else if(Input.GetButton("Attack_"+humanPlayer) || Input.GetButton("Block_"+humanPlayer) || swordz.status.dodging) { dude.RawMovement(finalMove, false, true); } else if(!Input.GetButtonUp("Attack_"+humanPlayer)) { dude.RawMovement(finalMove, true, false); } } } else if(aimMethod == "mouse") { dude.RawMovement(finalMove, false); } else { dude.RawMovement(finalMove, true); } } else { // when not moving, //animated.animation.Stop("bjorn_walk"); // if pressing an action button, snap the look if(Input.GetButtonDown("Attack_"+humanPlayer) || Input.GetButtonDown("Dodge_"+humanPlayer) || Input.GetButtonDown("Block_"+humanPlayer)) { dude.Look();//moveVec, false); } // otherwise, continue to rotate into the direction the player last pointed to else if(!Input.GetButton("Attack_"+humanPlayer) && !Input.GetButton("Block_"+humanPlayer) && !Input.GetButtonUp("Attack_"+humanPlayer)) { //dude.Look(moveVec, true); dude.Look();//moveVec, false); } } } else dude.Movement(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); if(aimMethod == "mouse") { LookAtMouse(); } } public void LookAtMouse() { transform.LookAt(GetMousePoint()); } public Vector3 GetMousePoint() { // shoot ray where the mouse is // see if the dude can see the collision point // var cam = Camera.main; RaycastHit hit; var camRay = cam.ScreenPointToRay(Input.mousePosition); Debug.DrawRay(camRay.origin, camRay.direction); if( Physics.Raycast(camRay, out hit) ) { var lookpoint = hit.point; // ensure the player is looking at something equal to a certain y-level //lookpoint.y = transform.position.y; // when aiming at a dude, just aim // otherwise, aim slightly above (such as with terrain) var hitDude = hit.collider.GetComponent(typeof(Dude)) as Dude; if(hitDude == null) { lookpoint.y = transform.position.y;//+= 0.5; } Debug.DrawLine(transform.position, lookpoint); return lookpoint; //cubepoint = new Vector3(Mathf.Round(lookpoint.x), Mathf.Floor(lookpoint.y)-1, Mathf.Round(lookpoint.z)); //selectorCube.position = cubepoint; } // intersect the ray with the camera's far look plane, I guess return cam.ScreenToWorldPoint(Input.mousePosition); } public Vector3 GetMoveVec() { return moveVec; } public void OnEnable() { disabled = false; } public void OnDisable() { disabled = true; } }
#define TRACE #region using declarations using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Windows.Forms; #endregion namespace DigitallyImported.Client.Diagnostics { /// <summary> /// Summary description for DebugConsole. /// </summary> public class DebugConsoleWrapper : Form { /// <summary> /// Required designer variable. /// </summary> private readonly Container _components = null; /// <summary> /// /// </summary> public StringBuilder Buffer = new StringBuilder(); private Button _btnClear; private Button _btnSave; private CheckBox _checkScroll; private CheckBox _checkTop; private ColumnHeader _col1; private ColumnHeader _col2; private ColumnHeader _col3; private ListViewItem.ListViewSubItem _currentMsgItem; private int _eventCounter; private ListView _outputView; private Panel _panel2; private SaveFileDialog _saveFileDlg; /// <summary> /// </summary> public DebugConsoleWrapper() { InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (_components != null) { _components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// </summary> public void CreateEventRow() { DateTime d = DateTime.Now; // create a ListView item/subitems : [event nb] - [time] - [empty string] string msg1 = (++_eventCounter).ToString(CultureInfo.InvariantCulture); string msg2 = d.ToLongTimeString(); var elem = new ListViewItem(msg1); elem.SubItems.Add(msg2); elem.SubItems.Add(""); // this.OutputView.Items.Add(elem); if (_outputView.InvokeRequired) _outputView.Invoke((Action) (() => _outputView.Items.Add(elem))); else _outputView.Items.Add(elem); // we save the message item for incoming text updates _currentMsgItem = elem.SubItems[2]; } /// <summary> /// </summary> public void UpdateCurrentRow( /*bool CreateRowNextTime*/) { if (_currentMsgItem == null) CreateEventRow(); if (_currentMsgItem != null) { _currentMsgItem.Text = Buffer.ToString(); // if null, a new row will be created next time this function is called if (true) _currentMsgItem = null; } // this is the autoscroll, move to the last element available in the ListView if (_checkScroll.CheckState == CheckState.Checked) { _outputView.EnsureVisible(_outputView.Items.Count - 1); } } private void BtnSave_Click(object sender, EventArgs e) { _saveFileDlg.Filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*"; _saveFileDlg.FileName = "log.txt"; _saveFileDlg.ShowDialog(); var fileInfo = new FileInfo(_saveFileDlg.FileName); // create a new textfile and export all lines StreamWriter s = fileInfo.CreateText(); for (int i = 0; i < _outputView.Items.Count; i++) { var sb = new StringBuilder(); sb.Append(_outputView.Items[i].SubItems[0].Text); sb.Append("\t"); sb.Append(_outputView.Items[i].SubItems[1].Text); sb.Append("\t"); sb.Append(_outputView.Items[i].SubItems[2].Text); s.WriteLine(sb.ToString()); } s.Close(); } private void BtnClear_Click(object sender, EventArgs e) { _eventCounter = 0; _outputView.Items.Clear(); _currentMsgItem = null; Buffer = new StringBuilder(); } private void CheckTop_CheckedChanged(object sender, EventArgs e) { TopMost = _checkTop.CheckState == CheckState.Checked; } private void CheckScroll_CheckedChanged(object sender, EventArgs e) { if (_checkScroll.CheckState == CheckState.Checked) _outputView.EnsureVisible(_outputView.Items.Count - 1); } #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._btnSave = new System.Windows.Forms.Button(); this._btnClear = new System.Windows.Forms.Button(); this._saveFileDlg = new System.Windows.Forms.SaveFileDialog(); this._checkScroll = new System.Windows.Forms.CheckBox(); this._outputView = new System.Windows.Forms.ListView(); this._col1 = new System.Windows.Forms.ColumnHeader(); this._col2 = new System.Windows.Forms.ColumnHeader(); this._col3 = new System.Windows.Forms.ColumnHeader(); this._checkTop = new System.Windows.Forms.CheckBox(); this._panel2 = new System.Windows.Forms.Panel(); this._panel2.SuspendLayout(); this.SuspendLayout(); // // BtnSave // this._btnSave.Location = new System.Drawing.Point(8, 16); this._btnSave.Name = "_btnSave"; this._btnSave.Size = new System.Drawing.Size(64, 24); this._btnSave.TabIndex = 8; this._btnSave.Text = "Save"; this._btnSave.Click += new System.EventHandler(this.BtnSave_Click); // // BtnClear // this._btnClear.Location = new System.Drawing.Point(80, 16); this._btnClear.Name = "_btnClear"; this._btnClear.Size = new System.Drawing.Size(64, 24); this._btnClear.TabIndex = 8; this._btnClear.Text = "Clear"; this._btnClear.Click += new System.EventHandler(this.BtnClear_Click); // // CheckScroll // this._checkScroll.Checked = true; this._checkScroll.CheckState = System.Windows.Forms.CheckState.Checked; this._checkScroll.Location = new System.Drawing.Point(152, 16); this._checkScroll.Name = "_checkScroll"; this._checkScroll.Size = new System.Drawing.Size(80, 16); this._checkScroll.TabIndex = 8; this._checkScroll.Text = "autoscroll"; this._checkScroll.CheckedChanged += new System.EventHandler(this.CheckScroll_CheckedChanged); // // OutputView // this._outputView.AutoArrange = false; this._outputView.BackColor = System.Drawing.Color.RoyalBlue; this._outputView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this._col1, this._col2, this._col3 }); this._outputView.Dock = System.Windows.Forms.DockStyle.Fill; this._outputView.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (0))); this._outputView.ForeColor = System.Drawing.Color.Yellow; this._outputView.Location = new System.Drawing.Point(0, 0); this._outputView.Name = "_outputView"; this._outputView.Size = new System.Drawing.Size(760, 286); this._outputView.TabIndex = 7; this._outputView.UseCompatibleStateImageBehavior = false; this._outputView.View = System.Windows.Forms.View.Details; // // Col1 // this._col1.Text = "#"; this._col1.Width = 30; // // Col2 // this._col2.Text = "Time"; this._col2.Width = 101; // // Col3 // this._col3.Text = "Message"; this._col3.Width = 619; // // CheckTop // this._checkTop.Location = new System.Drawing.Point(240, 16); this._checkTop.Name = "_checkTop"; this._checkTop.Size = new System.Drawing.Size(96, 16); this._checkTop.TabIndex = 8; this._checkTop.Text = "always on top"; this._checkTop.CheckedChanged += new System.EventHandler(this.CheckTop_CheckedChanged); // // panel2 // this._panel2.Controls.Add(this._btnSave); this._panel2.Controls.Add(this._btnClear); this._panel2.Controls.Add(this._checkScroll); this._panel2.Controls.Add(this._checkTop); this._panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this._panel2.Location = new System.Drawing.Point(0, 286); this._panel2.Name = "_panel2"; this._panel2.Size = new System.Drawing.Size(760, 48); this._panel2.TabIndex = 8; // // DebugConsoleWrapper // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(760, 334); this.Controls.Add(this._outputView); this.Controls.Add(this._panel2); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; this.MinimumSize = new System.Drawing.Size(390, 160); this.Name = "DebugConsoleWrapper"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "Debug Console"; this._panel2.ResumeLayout(false); this.ResumeLayout(false); } #endregion } // DebugConsole Singleton internal sealed class DebugConsole : TraceListener { public static readonly DebugConsole Instance = new DebugConsole(); private readonly DebugConsoleWrapper _debugForm = new DebugConsoleWrapper(); // if this parameter is set to true, a call to WriteLine will always create a new row // (if false, it may be appended to the current buffer created with some Write calls) private bool _useCrWl = true; private DebugConsole() { _debugForm.Show(); } public void Init(bool useDebugOutput, bool useCrForWriteLine) { var dtl = new DefaultTraceListener(); if (useDebugOutput) { Debug.Listeners.Add(this); Debug.Listeners.Add(dtl); } else { Trace.Listeners.Add(this); Trace.Listeners.Add(dtl); } _useCrWl = useCrForWriteLine; } public override void Write(string message) { _debugForm.Buffer.Append(message); if (_debugForm.InvokeRequired && !_debugForm.Disposing) _debugForm.Invoke((Action) (() => _debugForm.UpdateCurrentRow())); else _debugForm.UpdateCurrentRow(); // DebugForm.BeginInvoke(Action(delegate() { Console.WriteLine("Simple Anonymous Method Called"); })); } public override void WriteLine(string message) { if (_useCrWl) { _debugForm.CreateEventRow(); _debugForm.Buffer = new StringBuilder(); } _debugForm.Buffer.Append(message); if (_debugForm.InvokeRequired && !_debugForm.Disposing) _debugForm.Invoke((Action) (() => _debugForm.UpdateCurrentRow())); else _debugForm.UpdateCurrentRow(); _debugForm.Buffer = new StringBuilder(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace LinkRelations.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); } } } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Party Consent ///<para>SObject Name: PartyConsent</para> ///<para>Custom Object: False</para> ///</summary> public class SfPartyConsent : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "PartyConsent"; } } ///<summary> /// PartyConsent ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Owner ID /// <para>Name: OwnerId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "ownerId")] public string OwnerId { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Name /// <para>Name: Name</para> /// <para>SF Type: string</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Individual ID /// <para>Name: PartyId</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "partyId")] public string PartyId { get; set; } ///<summary> /// ReferenceTo: Individual /// <para>RelationshipName: Party</para> ///</summary> [JsonProperty(PropertyName = "party")] [Updateable(false), Createable(false)] public SfIndividual Party { get; set; } ///<summary> /// Action /// <para>Name: Action</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "action")] public string Action { get; set; } ///<summary> /// Privacy Consent Status /// <para>Name: PrivacyConsentStatus</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "privacyConsentStatus")] public string PrivacyConsentStatus { get; set; } ///<summary> /// Consent Captured Date Time /// <para>Name: CaptureDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "captureDate")] public DateTimeOffset? CaptureDate { get; set; } ///<summary> /// Consent Captured Contact Point Type /// <para>Name: CaptureContactPointType</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "captureContactPointType")] public string CaptureContactPointType { get; set; } ///<summary> /// Consent Captured Source /// <para>Name: CaptureSource</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "captureSource")] public string CaptureSource { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class LambdaModuloNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableFloat(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableLong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableShort(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableUInt(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableULong(values[i], values[j], useInterpreter); } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void LambdaModuloNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private enum ResultType { Success, DivideByZero, Overflow } #region Verify decimal? private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { bool divideByZero; decimal? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a % b; } ParameterExpression p0 = Expression.Parameter(typeof(decimal?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(decimal?), "p1"); // verify with parameters supplied Expression<Func<decimal?>> e1 = Expression.Lambda<Func<decimal?>>( Expression.Invoke( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<decimal?, decimal?, Func<decimal?>>> e2 = Expression.Lambda<Func<decimal?, decimal?, Func<decimal?>>>( Expression.Lambda<Func<decimal?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<decimal?, decimal?, Func<decimal?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<decimal?, decimal?, decimal?>>> e3 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?, decimal?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<decimal?, decimal?, decimal?>>> e4 = Expression.Lambda<Func<Func<decimal?, decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?, decimal?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<decimal?, decimal?, decimal?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<decimal?, Func<decimal?, decimal?>>> e5 = Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<decimal?, Func<decimal?, decimal?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<decimal?, decimal?>>> e6 = Expression.Lambda<Func<Func<decimal?, decimal?>>>( Expression.Invoke( Expression.Lambda<Func<decimal?, Func<decimal?, decimal?>>>( Expression.Lambda<Func<decimal?, decimal?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(decimal?)) }), Enumerable.Empty<ParameterExpression>()); Func<decimal?, decimal?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify double? private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter) { double? expected = a % b; ParameterExpression p0 = Expression.Parameter(typeof(double?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(double?), "p1"); // verify with parameters supplied Expression<Func<double?>> e1 = Expression.Lambda<Func<double?>>( Expression.Invoke( Expression.Lambda<Func<double?, double?, double?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<double?, double?, Func<double?>>> e2 = Expression.Lambda<Func<double?, double?, Func<double?>>>( Expression.Lambda<Func<double?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<double?, double?, Func<double?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<double?, double?, double?>>> e3 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<double?, double?, double?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<double?, double?, double?>>> e4 = Expression.Lambda<Func<Func<double?, double?, double?>>>( Expression.Lambda<Func<double?, double?, double?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<double?, double?, double?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<double?, Func<double?, double?>>> e5 = Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<double?, Func<double?, double?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<double?, double?>>> e6 = Expression.Lambda<Func<Func<double?, double?>>>( Expression.Invoke( Expression.Lambda<Func<double?, Func<double?, double?>>>( Expression.Lambda<Func<double?, double?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(double?)) }), Enumerable.Empty<ParameterExpression>()); Func<double?, double?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify float? private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter) { float? expected = a % b; ParameterExpression p0 = Expression.Parameter(typeof(float?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(float?), "p1"); // verify with parameters supplied Expression<Func<float?>> e1 = Expression.Lambda<Func<float?>>( Expression.Invoke( Expression.Lambda<Func<float?, float?, float?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?> f1 = e1.Compile(useInterpreter); Assert.Equal(expected, f1()); // verify with values passed to make parameters Expression<Func<float?, float?, Func<float?>>> e2 = Expression.Lambda<Func<float?, float?, Func<float?>>>( Expression.Lambda<Func<float?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<float?, float?, Func<float?>> f2 = e2.Compile(useInterpreter); Assert.Equal(expected, f2(a, b)()); // verify with values directly passed Expression<Func<Func<float?, float?, float?>>> e3 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<float?, float?, float?> f3 = e3.Compile(useInterpreter)(); Assert.Equal(expected, f3(a, b)); // verify as a function generator Expression<Func<Func<float?, float?, float?>>> e4 = Expression.Lambda<Func<Func<float?, float?, float?>>>( Expression.Lambda<Func<float?, float?, float?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<float?, float?, float?>> f4 = e4.Compile(useInterpreter); Assert.Equal(expected, f4()(a, b)); // verify with currying Expression<Func<float?, Func<float?, float?>>> e5 = Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<float?, Func<float?, float?>> f5 = e5.Compile(useInterpreter); Assert.Equal(expected, f5(a)(b)); // verify with one parameter Expression<Func<Func<float?, float?>>> e6 = Expression.Lambda<Func<Func<float?, float?>>>( Expression.Invoke( Expression.Lambda<Func<float?, Func<float?, float?>>>( Expression.Lambda<Func<float?, float?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(float?)) }), Enumerable.Empty<ParameterExpression>()); Func<float?, float?> f6 = e6.Compile(useInterpreter)(); Assert.Equal(expected, f6(b)); } #endregion #region Verify int? private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter) { ResultType outcome; int? expected = null; if (a.HasValue && b == 0) { outcome = ResultType.DivideByZero; } else if (a == int.MinValue && b == -1) { outcome = ResultType.Overflow; } else { expected = a % b; outcome = ResultType.Success; } ParameterExpression p0 = Expression.Parameter(typeof(int?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(int?), "p1"); // verify with parameters supplied Expression<Func<int?>> e1 = Expression.Lambda<Func<int?>>( Expression.Invoke( Expression.Lambda<Func<int?, int?, int?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?> f1 = e1.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f1()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f1()); break; default: Assert.Equal(expected, f1()); break; } // verify with values passed to make parameters Expression<Func<int?, int?, Func<int?>>> e2 = Expression.Lambda<Func<int?, int?, Func<int?>>>( Expression.Lambda<Func<int?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<int?, int?, Func<int?>> f2 = e2.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f2(a, b)()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f2(a, b)()); break; default: Assert.Equal(expected, f2(a, b)()); break; } // verify with values directly passed Expression<Func<Func<int?, int?, int?>>> e3 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<int?, int?, int?> f3 = e3.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f3(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f3(a, b)); break; default: Assert.Equal(expected, f3(a, b)); break; } // verify as a function generator Expression<Func<Func<int?, int?, int?>>> e4 = Expression.Lambda<Func<Func<int?, int?, int?>>>( Expression.Lambda<Func<int?, int?, int?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<int?, int?, int?>> f4 = e4.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f4()(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f4()(a, b)); break; default: Assert.Equal(expected, f4()(a, b)); break; } // verify with currying Expression<Func<int?, Func<int?, int?>>> e5 = Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<int?, Func<int?, int?>> f5 = e5.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f5(a)(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f5(a)(b)); break; default: Assert.Equal(expected, f5(a)(b)); break; } // verify with one parameter Expression<Func<Func<int?, int?>>> e6 = Expression.Lambda<Func<Func<int?, int?>>>( Expression.Invoke( Expression.Lambda<Func<int?, Func<int?, int?>>>( Expression.Lambda<Func<int?, int?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(int?)) }), Enumerable.Empty<ParameterExpression>()); Func<int?, int?> f6 = e6.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f6(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f6(b)); break; default: Assert.Equal(expected, f6(b)); break; } } #endregion #region Verify long? private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter) { ResultType outcome; long? expected = null; if (a.HasValue && b == 0) { outcome = ResultType.DivideByZero; } else if (a == long.MinValue && b == -1) { outcome = ResultType.Overflow; } else { expected = a % b; outcome = ResultType.Success; } ParameterExpression p0 = Expression.Parameter(typeof(long?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(long?), "p1"); // verify with parameters supplied Expression<Func<long?>> e1 = Expression.Lambda<Func<long?>>( Expression.Invoke( Expression.Lambda<Func<long?, long?, long?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?> f1 = e1.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f1()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f1()); break; default: Assert.Equal(expected, f1()); break; } // verify with values passed to make parameters Expression<Func<long?, long?, Func<long?>>> e2 = Expression.Lambda<Func<long?, long?, Func<long?>>>( Expression.Lambda<Func<long?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<long?, long?, Func<long?>> f2 = e2.Compile(useInterpreter); long? f2Result = default(long?); Exception f2Ex = null; try { f2Result = f2(a, b)(); } catch (Exception ex) { f2Ex = ex; } // verify with values directly passed Expression<Func<Func<long?, long?, long?>>> e3 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<long?, long?, long?> f3 = e3.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f2(a, b)()); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f2(a, b)()); break; default: Assert.Equal(expected, f2(a, b)()); break; } // verify as a function generator Expression<Func<Func<long?, long?, long?>>> e4 = Expression.Lambda<Func<Func<long?, long?, long?>>>( Expression.Lambda<Func<long?, long?, long?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<long?, long?, long?>> f4 = e4.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f3(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f3(a, b)); break; default: Assert.Equal(expected, f3(a, b)); break; } // verify with currying Expression<Func<long?, Func<long?, long?>>> e5 = Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<long?, Func<long?, long?>> f5 = e5.Compile(useInterpreter); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f4()(a, b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f4()(a, b)); break; default: Assert.Equal(expected, f4()(a, b)); break; } // verify with one parameter Expression<Func<Func<long?, long?>>> e6 = Expression.Lambda<Func<Func<long?, long?>>>( Expression.Invoke( Expression.Lambda<Func<long?, Func<long?, long?>>>( Expression.Lambda<Func<long?, long?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(long?)) }), Enumerable.Empty<ParameterExpression>()); Func<long?, long?> f6 = e6.Compile(useInterpreter)(); switch (outcome) { case ResultType.DivideByZero: Assert.Throws<DivideByZeroException>(() => f5(a)(b)); break; case ResultType.Overflow: Assert.Throws<OverflowException>(() => f5(a)(b)); break; default: Assert.Equal(expected, f5(a)(b)); break; } } #endregion #region Verify short? private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter) { bool divideByZero; short? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = (short?)(a % b); } ParameterExpression p0 = Expression.Parameter(typeof(short?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(short?), "p1"); // verify with parameters supplied Expression<Func<short?>> e1 = Expression.Lambda<Func<short?>>( Expression.Invoke( Expression.Lambda<Func<short?, short?, short?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<short?, short?, Func<short?>>> e2 = Expression.Lambda<Func<short?, short?, Func<short?>>>( Expression.Lambda<Func<short?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<short?, short?, Func<short?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<short?, short?, short?>>> e3 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<short?, short?, short?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<short?, short?, short?>>> e4 = Expression.Lambda<Func<Func<short?, short?, short?>>>( Expression.Lambda<Func<short?, short?, short?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<short?, short?, short?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<short?, Func<short?, short?>>> e5 = Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<short?, Func<short?, short?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<short?, short?>>> e6 = Expression.Lambda<Func<Func<short?, short?>>>( Expression.Invoke( Expression.Lambda<Func<short?, Func<short?, short?>>>( Expression.Lambda<Func<short?, short?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(short?)) }), Enumerable.Empty<ParameterExpression>()); Func<short?, short?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify uint? private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter) { bool divideByZero; uint? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a % b; } ParameterExpression p0 = Expression.Parameter(typeof(uint?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(uint?), "p1"); // verify with parameters supplied Expression<Func<uint?>> e1 = Expression.Lambda<Func<uint?>>( Expression.Invoke( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<uint?, uint?, Func<uint?>>> e2 = Expression.Lambda<Func<uint?, uint?, Func<uint?>>>( Expression.Lambda<Func<uint?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<uint?, uint?, Func<uint?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<uint?, uint?, uint?>>> e3 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?, uint?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<uint?, uint?, uint?>>> e4 = Expression.Lambda<Func<Func<uint?, uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?, uint?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<uint?, uint?, uint?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<uint?, Func<uint?, uint?>>> e5 = Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<uint?, Func<uint?, uint?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<uint?, uint?>>> e6 = Expression.Lambda<Func<Func<uint?, uint?>>>( Expression.Invoke( Expression.Lambda<Func<uint?, Func<uint?, uint?>>>( Expression.Lambda<Func<uint?, uint?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(uint?)) }), Enumerable.Empty<ParameterExpression>()); Func<uint?, uint?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify ulong? private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter) { bool divideByZero; ulong? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = a % b; } ParameterExpression p0 = Expression.Parameter(typeof(ulong?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ulong?), "p1"); // verify with parameters supplied Expression<Func<ulong?>> e1 = Expression.Lambda<Func<ulong?>>( Expression.Invoke( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<ulong?, ulong?, Func<ulong?>>> e2 = Expression.Lambda<Func<ulong?, ulong?, Func<ulong?>>>( Expression.Lambda<Func<ulong?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ulong?, ulong?, Func<ulong?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<ulong?, ulong?, ulong?>>> e3 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?, ulong?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<ulong?, ulong?, ulong?>>> e4 = Expression.Lambda<Func<Func<ulong?, ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?, ulong?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ulong?, ulong?, ulong?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<ulong?, Func<ulong?, ulong?>>> e5 = Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ulong?, Func<ulong?, ulong?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<ulong?, ulong?>>> e6 = Expression.Lambda<Func<Func<ulong?, ulong?>>>( Expression.Invoke( Expression.Lambda<Func<ulong?, Func<ulong?, ulong?>>>( Expression.Lambda<Func<ulong?, ulong?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ulong?)) }), Enumerable.Empty<ParameterExpression>()); Func<ulong?, ulong?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #region Verify ushort? private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter) { bool divideByZero; ushort? expected; if (a.HasValue && b == 0) { divideByZero = true; expected = null; } else { divideByZero = false; expected = (ushort?)(a % b); } ParameterExpression p0 = Expression.Parameter(typeof(ushort?), "p0"); ParameterExpression p1 = Expression.Parameter(typeof(ushort?), "p1"); // verify with parameters supplied Expression<Func<ushort?>> e1 = Expression.Lambda<Func<ushort?>>( Expression.Invoke( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), new Expression[] { Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f1 = e1.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f1()); } else { Assert.Equal(expected, f1()); } // verify with values passed to make parameters Expression<Func<ushort?, ushort?, Func<ushort?>>> e2 = Expression.Lambda<Func<ushort?, ushort?, Func<ushort?>>>( Expression.Lambda<Func<ushort?>>( Expression.Modulo(p0, p1), Enumerable.Empty<ParameterExpression>()), new ParameterExpression[] { p0, p1 }); Func<ushort?, ushort?, Func<ushort?>> f2 = e2.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f2(a, b)()); } else { Assert.Equal(expected, f2(a, b)()); } // verify with values directly passed Expression<Func<Func<ushort?, ushort?, ushort?>>> e3 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()), Enumerable.Empty<Expression>()), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?, ushort?> f3 = e3.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f3(a, b)); } else { Assert.Equal(expected, f3(a, b)); } // verify as a function generator Expression<Func<Func<ushort?, ushort?, ushort?>>> e4 = Expression.Lambda<Func<Func<ushort?, ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?, ushort?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p0, p1 }), Enumerable.Empty<ParameterExpression>()); Func<Func<ushort?, ushort?, ushort?>> f4 = e4.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f4()(a, b)); } else { Assert.Equal(expected, f4()(a, b)); } // verify with currying Expression<Func<ushort?, Func<ushort?, ushort?>>> e5 = Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }); Func<ushort?, Func<ushort?, ushort?>> f5 = e5.Compile(useInterpreter); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f5(a)(b)); } else { Assert.Equal(expected, f5(a)(b)); } // verify with one parameter Expression<Func<Func<ushort?, ushort?>>> e6 = Expression.Lambda<Func<Func<ushort?, ushort?>>>( Expression.Invoke( Expression.Lambda<Func<ushort?, Func<ushort?, ushort?>>>( Expression.Lambda<Func<ushort?, ushort?>>( Expression.Modulo(p0, p1), new ParameterExpression[] { p1 }), new ParameterExpression[] { p0 }), new Expression[] { Expression.Constant(a, typeof(ushort?)) }), Enumerable.Empty<ParameterExpression>()); Func<ushort?, ushort?> f6 = e6.Compile(useInterpreter)(); if (divideByZero) { Assert.Throws<DivideByZeroException>(() => f6(b)); } else { Assert.Equal(expected, f6(b)); } } #endregion #endregion } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="Cab.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Compression { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Management; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>AddFile</i> (<b>Required: </b>NewFile, CabFile, CabExePath, ExtractExePath, NewFileDestination)</para> /// <para><i>Create</i> (<b>Required: </b>PathToCab or FilesToCab, CabFile, ExePath. <b>Optional: </b>PreservePaths, StripPrefixes, Recursive)</para> /// <para><i>Extract</i> (<b>Required: </b>CabFile, ExtractExePath, ExtractTo <b>Optional:</b> ExtractFile)</para> /// <para><b>Compatible with:</b></para> /// <para>Microsoft (R) Cabinet Tool (cabarc.exe) - Version 5.2.3790.0</para> /// <para>Microsoft (R) CAB File Extract Utility (extrac32.exe)- Version 5.2.3790.0</para> /// <para><b>Remote Execution Support:</b> No</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <ItemGroup> /// <!-- Create a collection of files to CAB --> /// <Files Include="C:\ddd\**\*"/> /// </ItemGroup> /// <!-- Create the CAB using the File collection and preserve the paths whilst stripping a prefix --> /// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Create" FilesToCab="@(Files)" CabExePath="D:\BuildTools\CabArc.Exe" CabFile="C:\newcabbyitem.cab" PreservePaths="true" StripPrefixes="ddd\"/> /// <!-- Create the same CAB but this time based on the Path. Note that Recursive is required --> /// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Create" PathToCab="C:\ddd" CabExePath="D:\BuildTools\CabArc.Exe" CabFile="C:\newcabbypath.cab" PreservePaths="true" StripPrefixes="ddd\" Recursive="true"/> /// <!-- Add a file to the CAB --> /// <MSBuild.ExtensionPack.Compression.Cab TaskAction="AddFile" NewFile="c:\New Text Document.txt" CabExePath="D:\BuildTools\CabArc.Exe" ExtractExePath="D:\BuildTools\Extrac32.EXE" CabFile="C:\newcabbyitem.cab" NewFileDestination="\Any Path"/> /// <!-- Extract a CAB--> /// <MSBuild.ExtensionPack.Compression.Cab TaskAction="Extract" ExtractTo="c:\a111" ExtractExePath="D:\BuildTools\Extrac32.EXE" CabFile="C:\newcabbyitem.cab"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class Cab : BaseTask { /// <summary> /// Sets the path to extract to /// </summary> public ITaskItem ExtractTo { get; set; } /// <summary> /// Sets the CAB file. Required. /// </summary> [Required] public ITaskItem CabFile { get; set; } /// <summary> /// Sets the path to cab /// </summary> public ITaskItem PathToCab { get; set; } /// <summary> /// Sets whether to add files and folders recursively if PathToCab is specified. /// </summary> public bool Recursive { get; set; } /// <summary> /// Sets the files to cab /// </summary> public ITaskItem[] FilesToCab { get; set; } /// <summary> /// Sets the path to CabArc.Exe /// </summary> public ITaskItem CabExePath { get; set; } /// <summary> /// Sets the path to extrac32.exe /// </summary> public ITaskItem ExtractExePath { get; set; } /// <summary> /// Sets the files to extract. Default is /E, which is all. /// </summary> public string ExtractFile { get; set; } = "/E"; /// <summary> /// Sets a value indicating whether [preserve paths] /// </summary> public bool PreservePaths { get; set; } /// <summary> /// Sets the prefixes to strip. Delimit with ';' /// </summary> public string StripPrefixes { get; set; } /// <summary> /// Sets the new file to add to the Cab File /// </summary> public ITaskItem NewFile { get; set; } /// <summary> /// Sets the path to add the file to /// </summary> public string NewFileDestination { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } // Resolve TaskAction switch (this.TaskAction) { case "Create": this.Create(); break; case "Extract": this.Extract(); break; case "AddFile": this.AddFile(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } /// <summary> /// Adds the file. /// </summary> private void AddFile() { // Validation if (!this.ValidateExtract()) { return; } if (!System.IO.File.Exists(this.NewFile.GetMetadata("FullPath"))) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "New File not found: {0}", this.NewFile.GetMetadata("FullPath"))); return; } FileInfo f = new FileInfo(this.NewFile.GetMetadata("FullPath")); this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Adding File: {0} to Cab: {1}", this.NewFile.GetMetadata("FullPath"), this.CabFile.GetMetadata("FullPath"))); string tempFolderName = System.Guid.NewGuid() + "\\"; DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(Path.GetTempPath(), tempFolderName)); Directory.CreateDirectory(dirInfo.FullName); if (dirInfo.Exists) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Created: {0}", dirInfo.FullName)); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Failed to create temp folder: {0}", dirInfo.FullName)); return; } // configure the process we need to run using (Process cabProcess = new Process()) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Extracting Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.ExtractExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = true; cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/Y /L ""{0}"" ""{1}"" ""{2}""", dirInfo.FullName, this.CabFile.GetMetadata("FullPath"), "/E"); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.ExtractExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); cabProcess.Start(); cabProcess.WaitForExit(); } Directory.CreateDirectory(dirInfo.FullName + "\\" + this.NewFileDestination); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Copying new File: {0} to {1}", this.NewFile, dirInfo.FullName + "\\" + this.NewFileDestination + "\\" + f.Name)); System.IO.File.Copy(this.NewFile.GetMetadata("FullPath"), dirInfo.FullName + this.NewFileDestination + @"\" + f.Name, true); using (Process cabProcess = new Process()) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Creating Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.CabExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = false; cabProcess.StartInfo.RedirectStandardOutput = true; StringBuilder options = new StringBuilder(); options.Append("-r -p"); options.AppendFormat(CultureInfo.CurrentCulture, " -P \"{0}\"\\", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1).Replace(@"C:\", string.Empty)); cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"{0} N ""{1}"" ""{2}""", options, this.CabFile.GetMetadata("FullPath"), "\"" + dirInfo.FullName + "*.*\"" + " "); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.CabExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); // start the process cabProcess.Start(); // Read any messages from CABARC...and log them string output = cabProcess.StandardOutput.ReadToEnd(); cabProcess.WaitForExit(); if (output.Contains("Completed successfully")) { this.LogTaskMessage(output); } else { this.Log.LogError(output); } } string dirObject = string.Format(CultureInfo.CurrentCulture, "win32_Directory.Name='{0}'", dirInfo.FullName.Remove(dirInfo.FullName.Length - 1)); using (ManagementObject mdir = new ManagementObject(dirObject)) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Deleting Temp Folder: {0}", dirObject)); mdir.Get(); ManagementBaseObject outParams = mdir.InvokeMethod("Delete", null, null); // ReturnValue should be 0, else failure if (outParams != null) { if (Convert.ToInt32(outParams.Properties["ReturnValue"].Value, CultureInfo.CurrentCulture) != 0) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Directory deletion error: ReturnValue: {0}", outParams.Properties["ReturnValue"].Value)); } } else { this.Log.LogError("The ManagementObject call to invoke Delete returned null."); } } } /// <summary> /// Extracts this instance. /// </summary> private void Extract() { // Validation if (this.ValidateExtract() == false) { return; } if (this.ExtractTo == null) { this.Log.LogError("ExtractTo required."); return; } // configure the process we need to run using (Process cabProcess = new Process()) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Extracting Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.ExtractExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = true; cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"/Y /L ""{0}"" ""{1}"" ""{2}""", this.ExtractTo.GetMetadata("FullPath"), this.CabFile.GetMetadata("FullPath"), this.ExtractFile); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.ExtractExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); cabProcess.Start(); cabProcess.WaitForExit(); } } /// <summary> /// Validates the extract. /// </summary> /// <returns>bool</returns> private bool ValidateExtract() { // Validation if (System.IO.File.Exists(this.CabFile.GetMetadata("FullPath")) == false) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "CAB file not found: {0}", this.CabFile.GetMetadata("FullPath"))); return false; } if (this.ExtractExePath == null) { if (System.IO.File.Exists(Environment.SystemDirectory + "extrac32.exe")) { this.ExtractExePath = new TaskItem(); this.ExtractExePath.SetMetadata("FullPath", Environment.SystemDirectory + "extrac32.exe"); } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.ExtractExePath.GetMetadata("FullPath"))); return false; } } else { if (System.IO.File.Exists(this.ExtractExePath.GetMetadata("FullPath")) == false) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.ExtractExePath.GetMetadata("FullPath"))); return false; } } return true; } /// <summary> /// Creates this instance. /// </summary> private void Create() { // Validation if (System.IO.File.Exists(this.CabExePath.GetMetadata("FullPath")) == false) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Executable not found: {0}", this.CabExePath.GetMetadata("FullPath"))); return; } using (Process cabProcess = new Process()) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Cab: {0}", this.CabFile.GetMetadata("FullPath"))); cabProcess.StartInfo.FileName = this.CabExePath.GetMetadata("FullPath"); cabProcess.StartInfo.UseShellExecute = false; cabProcess.StartInfo.RedirectStandardOutput = true; StringBuilder options = new StringBuilder(); if (this.PreservePaths) { options.Append("-p"); } if (this.PathToCab != null && this.Recursive) { options.Append(" -r "); } // Could be more than one prefix to strip... if (string.IsNullOrEmpty(this.StripPrefixes) == false) { string[] prefixes = this.StripPrefixes.Split(';'); foreach (string prefix in prefixes) { options.AppendFormat(CultureInfo.CurrentCulture, " -P {0}", prefix); } } string files = string.Empty; if ((this.FilesToCab == null || this.FilesToCab.Length == 0) && this.PathToCab == null) { this.Log.LogError("FilesToCab or PathToCab must be supplied"); return; } if (this.PathToCab != null) { files = this.PathToCab.GetMetadata("FullPath"); if (!files.EndsWith(@"\*", StringComparison.OrdinalIgnoreCase)) { files += @"\*"; } } else { files = this.FilesToCab.Aggregate(files, (current, file) => current + ("\"" + file.ItemSpec + "\"" + " ")); } cabProcess.StartInfo.Arguments = string.Format(CultureInfo.CurrentCulture, @"{0} N ""{1}"" ""{2}""", options, this.CabFile.GetMetadata("FullPath"), files); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Calling {0} with {1}", this.CabExePath.GetMetadata("FullPath"), cabProcess.StartInfo.Arguments)); // start the process cabProcess.Start(); // Read any messages from CABARC...and log them string output = cabProcess.StandardOutput.ReadToEnd(); cabProcess.WaitForExit(); if (output.Contains("Completed successfully")) { this.LogTaskMessage(MessageImportance.Low, output); } else { this.Log.LogError(output); } } } } }
using Discord.Audio; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; namespace Discord.Rest { /// <summary> /// Represents a REST-based group-message channel. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class RestGroupChannel : RestChannel, IGroupChannel, IRestPrivateChannel, IRestMessageChannel, IRestAudioChannel { private string _iconId; private ImmutableDictionary<ulong, RestGroupUser> _users; /// <inheritdoc /> public string Name { get; private set; } public IReadOnlyCollection<RestGroupUser> Users => _users.ToReadOnlyCollection(); public IReadOnlyCollection<RestGroupUser> Recipients => _users.Select(x => x.Value).Where(x => x.Id != Discord.CurrentUser.Id).ToReadOnlyCollection(() => _users.Count - 1); internal RestGroupChannel(BaseDiscordClient discord, ulong id) : base(discord, id) { } internal new static RestGroupChannel Create(BaseDiscordClient discord, Model model) { var entity = new RestGroupChannel(discord, model.Id); entity.Update(model); return entity; } internal override void Update(Model model) { if (model.Name.IsSpecified) Name = model.Name.Value; if (model.Icon.IsSpecified) _iconId = model.Icon.Value; if (model.Recipients.IsSpecified) UpdateUsers(model.Recipients.Value); } internal void UpdateUsers(API.User[] models) { var users = ImmutableDictionary.CreateBuilder<ulong, RestGroupUser>(); for (int i = 0; i < models.Length; i++) users[models[i].Id] = RestGroupUser.Create(Discord, models[i]); _users = users.ToImmutable(); } /// <inheritdoc /> public override async Task UpdateAsync(RequestOptions options = null) { var model = await Discord.ApiClient.GetChannelAsync(Id, options).ConfigureAwait(false); Update(model); } /// <inheritdoc /> public Task LeaveAsync(RequestOptions options = null) => ChannelHelper.DeleteAsync(this, Discord, options); public RestUser GetUser(ulong id) { if (_users.TryGetValue(id, out RestGroupUser user)) return user; return null; } /// <inheritdoc /> public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null) => ChannelHelper.GetMessageAsync(this, Discord, id, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options); /// <inheritdoc /> public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options); /// <inheritdoc /> public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options); /// <inheritdoc /> /// <exception cref="ArgumentException"> /// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more /// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="filePath" /> is <c>null</c>. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. For example, on /// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 /// characters. /// </exception> /// <exception cref="DirectoryNotFoundException"> /// The specified path is invalid, (for example, it is on an unmapped drive). /// </exception> /// <exception cref="UnauthorizedAccessException"> /// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission. /// </exception> /// <exception cref="FileNotFoundException"> /// The file specified in <paramref name="filePath" /> was not found. /// </exception> /// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception> /// <exception cref="IOException">An I/O error occurred while opening the file.</exception> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null) => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler); /// <inheritdoc /> public Task TriggerTypingAsync(RequestOptions options = null) => ChannelHelper.TriggerTypingAsync(this, Discord, options); /// <inheritdoc /> public IDisposable EnterTypingState(RequestOptions options = null) => ChannelHelper.EnterTypingState(this, Discord, options); public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, Group)"; //ISocketPrivateChannel IReadOnlyCollection<RestUser> IRestPrivateChannel.Recipients => Recipients; //IPrivateChannel IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients; //IMessageChannel async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetMessageAsync(id, options).ConfigureAwait(false); else return null; } IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(fromMessageId, dir, limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return GetMessagesAsync(fromMessage, dir, limit, options); else return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>(); } async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference) => await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false); async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference) => await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false); //IAudioChannel /// <inheritdoc /> /// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception> Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); } Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); } //IChannel Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IUser>(GetUser(id)); IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable(); } }
// <copyright file="Ilutp.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2010 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Single.Solvers { /// <summary> /// This class performs an Incomplete LU factorization with drop tolerance /// and partial pivoting. The drop tolerance indicates which additional entries /// will be dropped from the factorized LU matrices. /// </summary> /// <remarks> /// The ILUTP-Mem algorithm was taken from: <br/> /// ILUTP_Mem: a Space-Efficient Incomplete LU Preconditioner /// <br/> /// Tzu-Yi Chen, Department of Mathematics and Computer Science, <br/> /// Pomona College, Claremont CA 91711, USA <br/> /// Published in: <br/> /// Lecture Notes in Computer Science <br/> /// Volume 3046 / 2004 <br/> /// pp. 20 - 28 <br/> /// Algorithm is described in Section 2, page 22 /// </remarks> public sealed class ILUTPPreconditioner : IPreconditioner<float> { /// <summary> /// The default fill level. /// </summary> public const double DefaultFillLevel = 200.0; /// <summary> /// The default drop tolerance. /// </summary> public const double DefaultDropTolerance = 0.0001; /// <summary> /// The decomposed upper triangular matrix. /// </summary> SparseMatrix _upper; /// <summary> /// The decomposed lower triangular matrix. /// </summary> SparseMatrix _lower; /// <summary> /// The array containing the pivot values. /// </summary> int[] _pivots; /// <summary> /// The fill level. /// </summary> double _fillLevel = DefaultFillLevel; /// <summary> /// The drop tolerance. /// </summary> double _dropTolerance = DefaultDropTolerance; /// <summary> /// The pivot tolerance. /// </summary> double _pivotTolerance; /// <summary> /// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the default settings. /// </summary> public ILUTPPreconditioner() { } /// <summary> /// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the specified settings. /// </summary> /// <param name="fillLevel"> /// The amount of fill that is allowed in the matrix. The value is a fraction of /// the number of non-zero entries in the original matrix. Values should be positive. /// </param> /// <param name="dropTolerance"> /// The absolute drop tolerance which indicates below what absolute value an entry /// will be dropped from the matrix. A drop tolerance of 0.0 means that no values /// will be dropped. Values should always be positive. /// </param> /// <param name="pivotTolerance"> /// The pivot tolerance which indicates at what level pivoting will take place. A /// value of 0.0 means that no pivoting will take place. /// </param> public ILUTPPreconditioner(double fillLevel, double dropTolerance, double pivotTolerance) { if (fillLevel < 0) { throw new ArgumentOutOfRangeException("fillLevel"); } if (dropTolerance < 0) { throw new ArgumentOutOfRangeException("dropTolerance"); } if (pivotTolerance < 0) { throw new ArgumentOutOfRangeException("pivotTolerance"); } _fillLevel = fillLevel; _dropTolerance = dropTolerance; _pivotTolerance = pivotTolerance; } /// <summary> /// Gets or sets the amount of fill that is allowed in the matrix. The /// value is a fraction of the number of non-zero entries in the original /// matrix. The standard value is 200. /// </summary> /// <remarks> /// <para> /// Values should always be positive and can be higher than 1.0. A value lower /// than 1.0 means that the eventual preconditioner matrix will have fewer /// non-zero entries as the original matrix. A value higher than 1.0 means that /// the eventual preconditioner can have more non-zero values than the original /// matrix. /// </para> /// <para> /// Note that any changes to the <b>FillLevel</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double FillLevel { get { return _fillLevel; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _fillLevel = value; } } /// <summary> /// Gets or sets the absolute drop tolerance which indicates below what absolute value /// an entry will be dropped from the matrix. The standard value is 0.0001. /// </summary> /// <remarks> /// <para> /// The values should always be positive and can be larger than 1.0. A low value will /// keep more small numbers in the preconditioner matrix. A high value will remove /// more small numbers from the preconditioner matrix. /// </para> /// <para> /// Note that any changes to the <b>DropTolerance</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double DropTolerance { get { return _dropTolerance; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _dropTolerance = value; } } /// <summary> /// Gets or sets the pivot tolerance which indicates at what level pivoting will /// take place. The standard value is 0.0 which means pivoting will never take place. /// </summary> /// <remarks> /// <para> /// The pivot tolerance is used to calculate if pivoting is necessary. Pivoting /// will take place if any of the values in a row is bigger than the /// diagonal value of that row divided by the pivot tolerance, i.e. pivoting /// will take place if <b>row(i,j) > row(i,i) / PivotTolerance</b> for /// any <b>j</b> that is not equal to <b>i</b>. /// </para> /// <para> /// Note that any changes to the <b>PivotTolerance</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double PivotTolerance { get { return _pivotTolerance; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _pivotTolerance = value; } } /// <summary> /// Returns the upper triagonal matrix that was created during the LU decomposition. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>A new matrix containing the upper triagonal elements.</returns> internal Matrix<float> UpperTriangle() { return _upper.Clone(); } /// <summary> /// Returns the lower triagonal matrix that was created during the LU decomposition. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>A new matrix containing the lower triagonal elements.</returns> internal Matrix<float> LowerTriangle() { return _lower.Clone(); } /// <summary> /// Returns the pivot array. This array is not needed for normal use because /// the preconditioner will return the solution vector values in the proper order. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>The pivot array.</returns> internal int[] Pivots() { var result = new int[_pivots.Length]; for (var i = 0; i < _pivots.Length; i++) { result[i] = _pivots[i]; } return result; } /// <summary> /// Initializes the preconditioner and loads the internal data structures. /// </summary> /// <param name="matrix"> /// The <see cref="Matrix"/> upon which this preconditioner is based. Note that the /// method takes a general matrix type. However internally the data is stored /// as a sparse matrix. Therefore it is not recommended to pass a dense matrix. /// </param> /// <exception cref="ArgumentNullException"> If <paramref name="matrix"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> public void Initialize(Matrix<float> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resource.ArgumentMatrixSquare, "matrix"); } var sparseMatrix = (matrix is SparseMatrix) ? matrix as SparseMatrix : SparseMatrix.OfMatrix(matrix); // The creation of the preconditioner follows the following algorithm. // spaceLeft = lfilNnz * nnz(A) // for i = 1, .. , n // { // w = a(i,*) // for j = 1, .. , i - 1 // { // if (w(j) != 0) // { // w(j) = w(j) / a(j,j) // if (w(j) < dropTol) // { // w(j) = 0; // } // if (w(j) != 0) // { // w = w - w(j) * U(j,*) // } // } // } // // for j = i, .. ,n // { // if w(j) <= dropTol * ||A(i,*)|| // { // w(j) = 0 // } // } // // spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row // lfil = spaceRow / 2 // space for this row of L // l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements // // lfil = spaceRow - nnz(L(i,:)) // space for this row of U // u(i,j) = w(j) for j = i, .. , n // only the largest lfil - 1 elements // w = 0 // // if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary // { // pivot by swapping the max and the diagonal entries // Update L, U // Update P // } // spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:)) // } // Create the lower triangular matrix _lower = new SparseMatrix(sparseMatrix.RowCount); // Create the upper triangular matrix and copy the values _upper = new SparseMatrix(sparseMatrix.RowCount); // Create the pivot array _pivots = new int[sparseMatrix.RowCount]; for (var i = 0; i < _pivots.Length; i++) { _pivots[i] = i; } var workVector = new DenseVector(sparseMatrix.RowCount); var rowVector = new DenseVector(sparseMatrix.ColumnCount); var indexSorting = new int[sparseMatrix.RowCount]; // spaceLeft = lfilNnz * nnz(A) var spaceLeft = (int) _fillLevel*sparseMatrix.NonZerosCount; // for i = 1, .. , n for (var i = 0; i < sparseMatrix.RowCount; i++) { // w = a(i,*) sparseMatrix.Row(i, workVector); // pivot the row PivotRow(workVector); var vectorNorm = workVector.InfinityNorm(); // for j = 1, .. , i - 1) for (var j = 0; j < i; j++) { // if (w(j) != 0) // { // w(j) = w(j) / a(j,j) // if (w(j) < dropTol) // { // w(j) = 0; // } // if (w(j) != 0) // { // w = w - w(j) * U(j,*) // } if (workVector[j] != 0.0) { // Calculate the multiplication factors that go into the L matrix workVector[j] = workVector[j]/_upper[j, j]; if (Math.Abs(workVector[j]) < _dropTolerance) { workVector[j] = 0.0f; } // Calculate the addition factor if (workVector[j] != 0.0) { // vector update all in one go _upper.Row(j, rowVector); // zero out columnVector[k] because we don't need that // one anymore for k = 0 to k = j for (var k = 0; k <= j; k++) { rowVector[k] = 0.0f; } rowVector.Multiply(workVector[j], rowVector); workVector.Subtract(rowVector, workVector); } } } // for j = i, .. ,n for (var j = i; j < sparseMatrix.RowCount; j++) { // if w(j) <= dropTol * ||A(i,*)|| // { // w(j) = 0 // } if (Math.Abs(workVector[j]) <= _dropTolerance*vectorNorm) { workVector[j] = 0.0f; } } // spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row var spaceRow = spaceLeft/(sparseMatrix.RowCount - i + 1); // lfil = spaceRow / 2 // space for this row of L var fillLevel = spaceRow/2; FindLargestItems(0, i - 1, indexSorting, workVector); // l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements var lowerNonZeroCount = 0; var count = 0; for (var j = 0; j < i; j++) { if ((count > fillLevel) || (indexSorting[j] == -1)) { break; } _lower[i, indexSorting[j]] = workVector[indexSorting[j]]; count += 1; lowerNonZeroCount += 1; } FindLargestItems(i + 1, sparseMatrix.RowCount - 1, indexSorting, workVector); // lfil = spaceRow - nnz(L(i,:)) // space for this row of U fillLevel = spaceRow - lowerNonZeroCount; // u(i,j) = w(j) for j = i + 1, .. , n // only the largest lfil - 1 elements var upperNonZeroCount = 0; count = 0; for (var j = 0; j < sparseMatrix.RowCount - i; j++) { if ((count > fillLevel - 1) || (indexSorting[j] == -1)) { break; } _upper[i, indexSorting[j]] = workVector[indexSorting[j]]; count += 1; upperNonZeroCount += 1; } // Simply copy the diagonal element. Next step is to see if we pivot _upper[i, i] = workVector[i]; // if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary // { // pivot by swapping the max and the diagonal entries // Update L, U // Update P // } // Check if we really need to pivot. If (i+1) >=(mCoefficientMatrix.Rows -1) then // we are working on the last row. That means that there is only one number // And pivoting is useless. Also the indexSorting array will only contain // -1 values. if ((i + 1) < (sparseMatrix.RowCount - 1)) { if (Math.Abs(workVector[i]) < _pivotTolerance*Math.Abs(workVector[indexSorting[0]])) { // swap columns of u (which holds the values of A in the // sections that haven't been partitioned yet. SwapColumns(_upper, i, indexSorting[0]); // Update P var temp = _pivots[i]; _pivots[i] = _pivots[indexSorting[0]]; _pivots[indexSorting[0]] = temp; } } // spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:)) spaceLeft -= lowerNonZeroCount + upperNonZeroCount; } for (var i = 0; i < _lower.RowCount; i++) { _lower[i, i] = 1.0f; } } /// <summary> /// Pivot elements in the <paramref name="row"/> according to internal pivot array /// </summary> /// <param name="row">Row <see cref="Vector"/> to pivot in</param> void PivotRow(Vector<float> row) { var knownPivots = new Dictionary<int, int>(); // pivot the row for (var i = 0; i < row.Count; i++) { if ((_pivots[i] != i) && (!PivotMapFound(knownPivots, i))) { // store the pivots in the hashtable knownPivots.Add(_pivots[i], i); var t = row[i]; row[i] = row[_pivots[i]]; row[_pivots[i]] = t; } } } /// <summary> /// Was pivoting already performed /// </summary> /// <param name="knownPivots">Pivots already done</param> /// <param name="currentItem">Current item to pivot</param> /// <returns><c>true</c> if performed, otherwise <c>false</c></returns> bool PivotMapFound(Dictionary<int, int> knownPivots, int currentItem) { if (knownPivots.ContainsKey(_pivots[currentItem])) { if (knownPivots[_pivots[currentItem]].Equals(currentItem)) { return true; } } if (knownPivots.ContainsKey(currentItem)) { if (knownPivots[currentItem].Equals(_pivots[currentItem])) { return true; } } return false; } /// <summary> /// Swap columns in the <see cref="Matrix"/> /// </summary> /// <param name="matrix">Source <see cref="Matrix"/>.</param> /// <param name="firstColumn">First column index to swap</param> /// <param name="secondColumn">Second column index to swap</param> static void SwapColumns(Matrix<float> matrix, int firstColumn, int secondColumn) { for (var i = 0; i < matrix.RowCount; i++) { var temp = matrix[i, firstColumn]; matrix[i, firstColumn] = matrix[i, secondColumn]; matrix[i, secondColumn] = temp; } } /// <summary> /// Sort vector descending, not changing vector but placing sorted indicies to <paramref name="sortedIndices"/> /// </summary> /// <param name="lowerBound">Start sort form</param> /// <param name="upperBound">Sort till upper bound</param> /// <param name="sortedIndices">Array with sorted vector indicies</param> /// <param name="values">Source <see cref="Vector"/></param> static void FindLargestItems(int lowerBound, int upperBound, int[] sortedIndices, Vector<float> values) { // Copy the indices for the values into the array for (var i = 0; i < upperBound + 1 - lowerBound; i++) { sortedIndices[i] = lowerBound + i; } for (var i = upperBound + 1 - lowerBound; i < sortedIndices.Length; i++) { sortedIndices[i] = -1; } // Sort the first set of items. // Sorting starts at index 0 because the index array // starts at zero // and ends at index upperBound - lowerBound ILUTPElementSorter.SortDoubleIndicesDecreasing(0, upperBound - lowerBound, sortedIndices, values); } /// <summary> /// Approximates the solution to the matrix equation <b>Ax = b</b>. /// </summary> /// <param name="rhs">The right hand side vector.</param> /// <param name="lhs">The left hand side vector. Also known as the result vector.</param> public void Approximate(Vector<float> rhs, Vector<float> lhs) { if (_upper == null) { throw new ArgumentException(Resource.ArgumentMatrixDoesNotExist); } if ((lhs.Count != rhs.Count) || (lhs.Count != _upper.RowCount)) { throw new ArgumentException(Resource.ArgumentVectorsSameLength, "rhs"); } // Solve equation here // Pivot(vector, result); // Solve L*Y = B(piv,:) var rowValues = new DenseVector(_lower.RowCount); for (var i = 0; i < _lower.RowCount; i++) { _lower.Row(i, rowValues); var sum = 0.0f; for (var j = 0; j < i; j++) { sum += rowValues[j]*lhs[j]; } lhs[i] = rhs[i] - sum; } // Solve U*X = Y; for (var i = _upper.RowCount - 1; i > -1; i--) { _upper.Row(i, rowValues); var sum = 0.0f; for (var j = _upper.RowCount - 1; j > i; j--) { sum += rowValues[j]*lhs[j]; } lhs[i] = 1/rowValues[i]*(lhs[i] - sum); } // We have a column pivot so we only need to pivot the // end result not the incoming right hand side vector var temp = lhs.Clone(); Pivot(temp, lhs); } /// <summary> /// Pivot elements in <see cref="Vector"/> according to internal pivot array /// </summary> /// <param name="vector">Source <see cref="Vector"/>.</param> /// <param name="result">Result <see cref="Vector"/> after pivoting.</param> void Pivot(Vector<float> vector, Vector<float> result) { for (var i = 0; i < _pivots.Length; i++) { result[i] = vector[_pivots[i]]; } } } /// <summary> /// An element sort algorithm for the <see cref="ILUTPPreconditioner"/> class. /// </summary> /// <remarks> /// This sort algorithm is used to sort the columns in a sparse matrix based on /// the value of the element on the diagonal of the matrix. /// </remarks> internal static class ILUTPElementSorter { /// <summary> /// Sorts the elements of the <paramref name="values"/> vector in decreasing /// fashion. The vector itself is not affected. /// </summary> /// <param name="lowerBound">The starting index.</param> /// <param name="upperBound">The stopping index.</param> /// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param> /// <param name="values">The <see cref="Vector"/> that contains the values that need to be sorted.</param> public static void SortDoubleIndicesDecreasing(int lowerBound, int upperBound, int[] sortedIndices, Vector<float> values) { // Move all the indices that we're interested in to the beginning of the // array. Ignore the rest of the indices. if (lowerBound > 0) { for (var i = 0; i < (upperBound - lowerBound + 1); i++) { Exchange(sortedIndices, i, i + lowerBound); } upperBound -= lowerBound; lowerBound = 0; } HeapSortDoublesIndices(lowerBound, upperBound, sortedIndices, values); } /// <summary> /// Sorts the elements of the <paramref name="values"/> vector in decreasing /// fashion using heap sort algorithm. The vector itself is not affected. /// </summary> /// <param name="lowerBound">The starting index.</param> /// <param name="upperBound">The stopping index.</param> /// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param> /// <param name="values">The <see cref="Vector"/> that contains the values that need to be sorted.</param> private static void HeapSortDoublesIndices(int lowerBound, int upperBound, int[] sortedIndices, Vector<float> values) { var start = ((upperBound - lowerBound + 1) / 2) - 1 + lowerBound; var end = (upperBound - lowerBound + 1) - 1 + lowerBound; BuildDoubleIndexHeap(start, upperBound - lowerBound + 1, sortedIndices, values); while (end >= lowerBound) { Exchange(sortedIndices, end, lowerBound); SiftDoubleIndices(sortedIndices, values, lowerBound, end); end -= 1; } } /// <summary> /// Build heap for double indicies /// </summary> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> /// <param name="sortedIndices">Indicies of <paramref name="values"/></param> /// <param name="values">Target <see cref="Vector"/></param> private static void BuildDoubleIndexHeap(int start, int count, int[] sortedIndices, Vector<float> values) { while (start >= 0) { SiftDoubleIndices(sortedIndices, values, start, count); start -= 1; } } /// <summary> /// Sift double indicies /// </summary> /// <param name="sortedIndices">Indicies of <paramref name="values"/></param> /// <param name="values">Target <see cref="Vector"/></param> /// <param name="begin">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void SiftDoubleIndices(int[] sortedIndices, Vector<float> values, int begin, int count) { var root = begin; while (root * 2 < count) { var child = root * 2; if ((child < count - 1) && (values[sortedIndices[child]] > values[sortedIndices[child + 1]])) { child += 1; } if (values[sortedIndices[root]] <= values[sortedIndices[child]]) { return; } Exchange(sortedIndices, root, child); root = child; } } /// <summary> /// Sorts the given integers in a decreasing fashion. /// </summary> /// <param name="values">The values.</param> public static void SortIntegersDecreasing(int[] values) { HeapSortIntegers(values, values.Length); } /// <summary> /// Sort the given integers in a decreasing fashion using heapsort algorithm /// </summary> /// <param name="values">Array of values to sort</param> /// <param name="count">Length of <paramref name="values"/></param> private static void HeapSortIntegers(int[] values, int count) { var start = (count / 2) - 1; var end = count - 1; BuildHeap(values, start, count); while (end >= 0) { Exchange(values, end, 0); Sift(values, 0, end); end -= 1; } } /// <summary> /// Build heap /// </summary> /// <param name="values">Target values array</param> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void BuildHeap(int[] values, int start, int count) { while (start >= 0) { Sift(values, start, count); start -= 1; } } /// <summary> /// Sift values /// </summary> /// <param name="values">Target value array</param> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void Sift(int[] values, int start, int count) { var root = start; while (root * 2 < count) { var child = root * 2; if ((child < count - 1) && (values[child] > values[child + 1])) { child += 1; } if (values[root] > values[child]) { Exchange(values, root, child); root = child; } else { return; } } } /// <summary> /// Exchange values in array /// </summary> /// <param name="values">Target values array</param> /// <param name="first">First value to exchange</param> /// <param name="second">Second value to exchange</param> private static void Exchange(int[] values, int first, int second) { var t = values[first]; values[first] = values[second]; values[second] = t; } } }
// // System.Security.Cryptography.X509Certificate2 class // // Author: // Sebastien Pouliot <[email protected]> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2006 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. // #if SECURITY_DEP #if MONO_SECURITY_ALIAS extern alias MonoSecurity; using MonoSecurity::Mono.Security; using MonoSecurity::Mono.Security.Cryptography; using MX = MonoSecurity::Mono.Security.X509; #else using Mono.Security; using Mono.Security.Cryptography; using MX = Mono.Security.X509; #endif #endif using System.IO; using System.Text; using System.Collections; using System.Runtime.Serialization; namespace System.Security.Cryptography.X509Certificates { [Serializable] public class X509Certificate2Mono : X509CertificateMono { #if !SECURITY_DEP // Used in Mono.Security HttpsClientStream public X509Certificate2Mono(byte[] rawData) { } #endif #if SECURITY_DEP new internal X509Certificate2Impl Impl { get { var impl2 = base.Impl as X509Certificate2Impl; X509Helper2.ThrowIfContextInvalid (impl2); return impl2; } } string friendlyName = string.Empty; // constructors public X509Certificate2 () { } public X509Certificate2 (byte[] rawData) { Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (byte[] rawData, string password) { Import (rawData, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (byte[] rawData, SecureString password) { Import (rawData, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { Import (rawData, password, keyStorageFlags); } public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { Import (rawData, password, keyStorageFlags); } public X509Certificate2 (string fileName) { Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, string password) { Import (fileName, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, SecureString password) { Import (fileName, password, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags) { Import (fileName, password, keyStorageFlags); } public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { Import (fileName, password, keyStorageFlags); } public X509Certificate2 (IntPtr handle) : base (handle) { throw new NotImplementedException (); } public X509Certificate2 (X509Certificate certificate) : base (X509Helper2.Import (certificate)) { } protected X509Certificate2 (SerializationInfo info, StreamingContext context) : base (info, context) { } internal X509Certificate2 (X509Certificate2Impl impl) : base (impl) { } // properties public bool Archived { get { return Impl.Archived; } set { Impl.Archived = true; } } public X509ExtensionCollection Extensions { get { return Impl.Extensions; } } public string FriendlyName { get { ThrowIfContextInvalid (); return friendlyName; } set { ThrowIfContextInvalid (); friendlyName = value; } } public bool HasPrivateKey { get { return Impl.HasPrivateKey; } } public X500DistinguishedName IssuerName { get { return Impl.IssuerName; } } public DateTime NotAfter { get { return Impl.GetValidUntil ().ToLocalTime (); } } public DateTime NotBefore { get { return Impl.GetValidFrom ().ToLocalTime (); } } public AsymmetricAlgorithm PrivateKey { get { return Impl.PrivateKey; } set { Impl.PrivateKey = value; } } public PublicKey PublicKey { get { return Impl.PublicKey; } } public byte[] RawData { get { return GetRawCertData (); } } public string SerialNumber { get { return GetSerialNumberString (); } } public Oid SignatureAlgorithm { get { return Impl.SignatureAlgorithm; } } public X500DistinguishedName SubjectName { get { return Impl.SubjectName; } } public string Thumbprint { get { return GetCertHashString (); } } public int Version { get { return Impl.Version; } } // methods [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")] public string GetNameInfo (X509NameType nameType, bool forIssuer) { return Impl.GetNameInfo (nameType, forIssuer); } public override void Import (byte[] rawData) { Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); } [MonoTODO ("missing KeyStorageFlags support")] public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { var impl = X509Helper2.Import (rawData, password, keyStorageFlags); ImportHandle (impl); } [MonoTODO ("SecureString is incomplete")] public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { Import (rawData, (string) null, keyStorageFlags); } public override void Import (string fileName) { byte[] rawData = File.ReadAllBytes (fileName); Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet); } [MonoTODO ("missing KeyStorageFlags support")] public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) { byte[] rawData = File.ReadAllBytes (fileName); Import (rawData, password, keyStorageFlags); } [MonoTODO ("SecureString is incomplete")] public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { byte[] rawData = File.ReadAllBytes (fileName); Import (rawData, (string)null, keyStorageFlags); } [MonoTODO ("X509ContentType.SerializedCert is not supported")] public override byte[] Export (X509ContentType contentType, string password) { return Impl.Export (contentType, password); } public override void Reset () { friendlyName = string.Empty; base.Reset (); } public override string ToString () { if (!IsValid) return "System.Security.Cryptography.X509Certificates.X509Certificate2"; return base.ToString (true); } public override string ToString (bool verbose) { if (!IsValid) return "System.Security.Cryptography.X509Certificates.X509Certificate2"; // the non-verbose X509Certificate2 == verbose X509Certificate if (!verbose) return base.ToString (true); string nl = Environment.NewLine; StringBuilder sb = new StringBuilder (); sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version); sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject); sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer); sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber); sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore); sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter); sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint); sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName, SignatureAlgorithm.Value); AsymmetricAlgorithm key = PublicKey.Key; sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl); if (key is RSA) sb.Append ("RSA"); else if (key is DSA) sb.Append ("DSA"); else sb.Append (key.ToString ()); sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize); AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData); sb.AppendFormat ("{0} Parameters: ", nl); AppendBuffer (sb, PublicKey.EncodedParameters.RawData); sb.Append (nl); return sb.ToString (); } private static void AppendBuffer (StringBuilder sb, byte[] buffer) { if (buffer == null) return; for (int i=0; i < buffer.Length; i++) { sb.Append (buffer [i].ToString ("x2")); if (i < buffer.Length - 1) sb.Append (" "); } } [MonoTODO ("by default this depends on the incomplete X509Chain")] public bool Verify () { return Impl.Verify (this); } // static methods private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 }; [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")] public static X509ContentType GetCertContentType (byte[] rawData) { if ((rawData == null) || (rawData.Length == 0)) throw new ArgumentException ("rawData"); X509ContentType type = X509ContentType.Unknown; try { ASN1 data = new ASN1 (rawData); if (data.Tag != 0x30) { string msg = Locale.GetText ("Unable to decode certificate."); throw new CryptographicException (msg); } if (data.Count == 0) return type; if (data.Count == 3) { switch (data [0].Tag) { case 0x30: // SEQUENCE / SEQUENCE / BITSTRING if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03)) type = X509ContentType.Cert; break; case 0x02: // INTEGER / SEQUENCE / SEQUENCE if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30)) type = X509ContentType.Pkcs12; // note: Pfx == Pkcs12 break; } } // check for PKCS#7 (count unknown but greater than 0) // SEQUENCE / OID (signedData) if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData)) type = X509ContentType.Pkcs7; } catch (Exception e) { string msg = Locale.GetText ("Unable to decode certificate."); throw new CryptographicException (msg, e); } return type; } [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")] public static X509ContentType GetCertContentType (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (fileName.Length == 0) throw new ArgumentException ("fileName"); byte[] data = File.ReadAllBytes (fileName); return GetCertContentType (data); } // internal stuff because X509Certificate2 isn't complete enough // (maybe X509Certificate3 will be better?) [MonoTODO ("See comment in X509Helper2.GetMonoCertificate().")] internal MX.X509Certificate MonoCertificate { get { return X509Helper2.GetMonoCertificate (this); } } #else // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS public AsymmetricAlgorithm PrivateKey { get { return null; } } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Text.RegularExpressions; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.Shared.FileSystem; using Microsoft.Build.Utilities; namespace Microsoft.Build.Tasks { /// <summary> /// This class defines an "Exec" MSBuild task, which simply invokes the specified process with the specified arguments, waits /// for it to complete, and then returns True if the process completed successfully, and False if an error occurred. /// </summary> // UNDONE: ToolTask has a "UseCommandProcessor" flag that duplicates much of the code in this class. Remove the duplication. public class Exec : ToolTaskExtension { #region Constructors /// <summary> /// Default constructor. /// </summary> public Exec() { Command = string.Empty; // Console-based output uses the current system OEM code page by default. Note that we should not use Console.OutputEncoding // here since processes we run don't really have much to do with our console window (and also Console.OutputEncoding // doesn't return the OEM code page if the running application that hosts MSBuild is not a console application). // If the cmd file contains non-ANSI characters encoding may change. _standardOutputEncoding = EncodingUtilities.CurrentSystemOemEncoding; _standardErrorEncoding = EncodingUtilities.CurrentSystemOemEncoding; } #endregion #region Fields // Are the encodings for StdErr and StdOut streams valid private bool _encodingParametersValid = true; private string _workingDirectory; private ITaskItem[] _outputs; internal bool workingDirectoryIsUNC; // internal for unit testing private string _batchFile; private string _customErrorRegex; private string _customWarningRegex; private readonly List<ITaskItem> _nonEmptyOutput = new List<ITaskItem>(); private Encoding _standardErrorEncoding; private Encoding _standardOutputEncoding; private string _command; #endregion #region Properties [Required] public string Command { get => _command; set { _command = value; if (NativeMethodsShared.IsUnixLike) { _command = _command.Replace("\r\n", "\n"); } } } public string WorkingDirectory { get; set; } public bool IgnoreExitCode { get; set; } /// <summary> /// Enable the pipe of the standard out to an item (StandardOutput). /// </summary> /// <Remarks> /// Even thought this is called a pipe, it is in fact a Tee. Use StandardOutputImportance to adjust the visibility of the stdout. /// </Remarks> public bool ConsoleToMSBuild { get; set; } /// <summary> /// Users can supply a regular expression that we should /// use to spot error lines in the tool output. This is /// useful for tools that produce unusually formatted output /// </summary> public string CustomErrorRegularExpression { get => _customErrorRegex; set => _customErrorRegex = value; } /// <summary> /// Users can supply a regular expression that we should /// use to spot warning lines in the tool output. This is /// useful for tools that produce unusually formatted output /// </summary> public string CustomWarningRegularExpression { get => _customWarningRegex; set => _customWarningRegex = value; } /// <summary> /// Whether to use pick out lines in the output that match /// the standard error/warning format, and log them as errors/warnings. /// Defaults to false. /// </summary> public bool IgnoreStandardErrorWarningFormat { get; set; } /// <summary> /// Property specifying the encoding of the captured task standard output stream /// </summary> protected override Encoding StandardOutputEncoding => _standardOutputEncoding; /// <summary> /// Property specifying the encoding of the captured task standard error stream /// </summary> protected override Encoding StandardErrorEncoding => _standardErrorEncoding; /// <summary> /// Whether or not to use UTF8 encoding for the cmd file and console window. /// Values: Always, Never, Detect /// If set to Detect, the current code page will be used unless it cannot represent /// the Command string. In that case, UTF-8 is used. /// </summary> public string UseUtf8Encoding { get; set; } /// <summary> /// Project visible property specifying the encoding of the captured task standard output stream /// </summary> [Output] public string StdOutEncoding { get => StandardOutputEncoding.EncodingName; set { try { _standardOutputEncoding = Encoding.GetEncoding(value); } catch (ArgumentException) { Log.LogErrorWithCodeFromResources("General.InvalidValue", "StdOutEncoding", "Exec"); _encodingParametersValid = false; } } } /// <summary> /// Project visible property specifying the encoding of the captured task standard error stream /// </summary> [Output] public string StdErrEncoding { get => StandardErrorEncoding.EncodingName; set { try { _standardErrorEncoding = Encoding.GetEncoding(value); } catch (ArgumentException) { Log.LogErrorWithCodeFromResources("General.InvalidValue", "StdErrEncoding", "Exec"); _encodingParametersValid = false; } } } [Output] public ITaskItem[] Outputs { get => _outputs ?? Array.Empty<ITaskItem>(); set => _outputs = value; } /// <summary> /// Returns the output as an Item. Whitespace are trimmed. /// ConsoleOutput is enabled when ConsoleToMSBuild is true. This avoids holding lines in memory /// if they aren't used. ConsoleOutput is a combination of stdout and stderr. /// </summary> [Output] public ITaskItem[] ConsoleOutput => !ConsoleToMSBuild ? Array.Empty<ITaskItem>(): _nonEmptyOutput.ToArray(); #endregion #region Methods /// <summary> /// Write out a temporary batch file with the user-specified command in it. /// </summary> private void CreateTemporaryBatchFile() { var encoding = EncodingUtilities.BatchFileEncoding(Command + WorkingDirectory, UseUtf8Encoding); // Temporary file with the extension .Exec.bat _batchFile = FileUtilities.GetTemporaryFile(".exec.cmd"); // UNICODE Batch files are not allowed as of WinXP. We can't use normal ANSI code pages either, // since console-related apps use OEM code pages "for historical reasons". Sigh. // We need to get the current OEM code page which will be the same language as the current ANSI code page, // just the OEM version. // See http://www.microsoft.com/globaldev/getWR/steps/wrg_codepage.mspx for a discussion of ANSI vs OEM // Note: 8/12/15 - Switched to use UTF8 on OS newer than 6.1 (Windows 7) // Note: 1/12/16 - Only use UTF8 when we detect we need to or the user specifies 'Always' using (StreamWriter sw = FileUtilities.OpenWrite(_batchFile, false, encoding)) { if (!NativeMethodsShared.IsUnixLike) { // In some wierd setups, users may have set an env var actually called "errorlevel" // this would cause our "exit %errorlevel%" to return false. // This is because the actual errorlevel value is not an environment variable, but some commands, // such as "exit %errorlevel%" will use the environment variable with that name if it exists, instead // of the actual errorlevel value. So we must temporarily reset errorlevel locally first. sw.WriteLine("setlocal"); // One more wrinkle. // "set foo=" has odd behavior: it sets errorlevel to 1 if there was no environment variable named // "foo" defined. // This has the effect of making "set errorlevel=" set an errorlevel of 1 if an environment // variable named "errorlevel" didn't already exist! // To avoid this problem, set errorlevel locally to a dummy value first. sw.WriteLine("set errorlevel=dummy"); sw.WriteLine("set errorlevel="); // We may need to change the code page and console encoding. if (encoding.CodePage != EncodingUtilities.CurrentSystemOemEncoding.CodePage) { // Output to nul so we don't change output and logs. sw.WriteLine($@"%SystemRoot%\System32\chcp.com {encoding.CodePage}>nul"); // Ensure that the console encoding is correct. _standardOutputEncoding = encoding; _standardErrorEncoding = encoding; } // if the working directory is a UNC path, bracket the exec command with pushd and popd, because pushd // automatically maps the network path to a drive letter, and then popd disconnects it. // This is required because Cmd.exe does not support UNC names as the current directory: // https://support.microsoft.com/en-us/kb/156276 if (workingDirectoryIsUNC) { sw.WriteLine("pushd " + _workingDirectory); } } else { // Use sh rather than bash, as not all 'nix systems necessarily have Bash installed sw.WriteLine("#!/bin/sh"); } if (NativeMethodsShared.IsUnixLike && NativeMethodsShared.IsMono) { // Extract the command we are going to run. Note that the command name may // be preceded by whitespace var m = Regex.Match(Command, @"^\s*((?:(?:(?<!\\)[^\0 !$`&*()+])|(?:(?<=\\)[^\0]))+)(.*)"); if (m.Success && m.Groups.Count > 1 && m.Groups[1].Captures.Count > 0) { string exe = m.Groups[1].Captures[0].ToString(); string commandLine = (m.Groups.Count > 2 && m.Groups[2].Captures.Count > 0) ? m.Groups[2].Captures[0].Value : ""; // If we are trying to run a .exe file, prepend mono as the file may // not be runnable if (exe.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || exe.EndsWith(".exe\"", StringComparison.OrdinalIgnoreCase) || exe.EndsWith(".exe'", StringComparison.OrdinalIgnoreCase)) { Command = "mono " + FileUtilities.FixFilePath(exe) + commandLine; } } } sw.WriteLine(Command); if (!NativeMethodsShared.IsUnixLike) { if (workingDirectoryIsUNC) { sw.WriteLine("popd"); } // NOTES: // 1) there's a bug in the Process class where the exit code is not returned properly i.e. if the command // fails with exit code 9009, Process.ExitCode returns 1 -- the statement below forces it to return the // correct exit code // 2) also because of another (or perhaps the same) bug in the Process class, when we use pushd/popd for a // UNC path, even if the command fails, the exit code comes back as 0 (seemingly reflecting the success // of popd) -- the statement below fixes that too // 3) the above described behaviour is most likely bugs in the Process class because batch files in a // console window do not hide or change the exit code a.k.a. errorlevel, esp. since the popd command is // a no-fail command, and it never changes the previous errorlevel sw.WriteLine("exit %errorlevel%"); } } } #endregion #region Overridden methods /// <summary> /// Executes cmd.exe and waits for it to complete /// </summary> /// <remarks> /// Overridden to clean up the batch file afterwards. /// </remarks> /// <returns>Upon completion of the process, returns True if successful, False if not.</returns> protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { try { return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands); } finally { DeleteTempFile(_batchFile); } } /// <summary> /// Allows tool to handle the return code. /// This method will only be called with non-zero exitCode set to true. /// </summary> /// <remarks> /// Overridden to make sure we display the command we put in the batch file, not the cmd.exe command /// used to run the batch file. /// </remarks> protected override bool HandleTaskExecutionErrors() { if (IgnoreExitCode) { // Don't log when EchoOff and IgnoreExitCode. if (!EchoOff) { Log.LogMessageFromResources(MessageImportance.Normal, "Exec.CommandFailedNoErrorCode", Command, ExitCode); } return true; } // Don't emit expanded form of Command when EchoOff is set. string commandForLog = EchoOff ? "..." : Command; if (ExitCode == NativeMethods.SE_ERR_ACCESSDENIED) { Log.LogErrorWithCodeFromResources("Exec.CommandFailedAccessDenied", commandForLog, ExitCode); } else { Log.LogErrorWithCodeFromResources("Exec.CommandFailed", commandForLog, ExitCode); } return false; } /// <summary> /// Logs the tool name and the path from where it is being run. /// </summary> /// <remarks> /// Overridden to avoid logging the path to "cmd.exe", which is not interesting. /// </remarks> protected override void LogPathToTool(string toolName, string pathToTool) { // Do nothing } /// <summary> /// Logs the command to be executed. /// </summary> /// <remarks> /// Overridden to log the batch file command instead of the cmd.exe command. /// </remarks> /// <param name="message"></param> protected override void LogToolCommand(string message) { //Dont print the command line if Echo is Off. if (!EchoOff) { base.LogToolCommand(Command); } } /// <summary> /// Calls a method on the TaskLoggingHelper to parse a single line of text to /// see if there are any errors or warnings in canonical format. /// </summary> /// <remarks> /// Overridden to handle any custom regular expressions supplied. /// </remarks> protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance) { if (OutputMatchesRegex(singleLine, ref _customErrorRegex)) { Log.LogError(singleLine); } else if (OutputMatchesRegex(singleLine, ref _customWarningRegex)) { Log.LogWarning(singleLine); } else if (IgnoreStandardErrorWarningFormat) { // Not detecting regular format errors and warnings, and it didn't // match any regexes either -- log as a regular message Log.LogMessage(messageImportance, singleLine, null); } else { // This is the normal code path: match standard format errors and warnings Log.LogMessageFromText(singleLine, messageImportance); } if (ConsoleToMSBuild) { string trimmedTextLine = singleLine.Trim(); if (trimmedTextLine.Length > 0) { // The lines read may be unescaped, so we need to escape them // before passing them to the TaskItem. _nonEmptyOutput.Add(new TaskItem(EscapingUtilities.Escape(trimmedTextLine))); } } } /// <summary> /// Returns true if the string is matched by the regular expression. /// If the regular expression is invalid, logs an error, then clears it out to /// prevent more errors. /// </summary> private bool OutputMatchesRegex(string singleLine, ref string regularExpression) { if (regularExpression == null) { return false; } bool match = false; try { match = Regex.IsMatch(singleLine, regularExpression); } catch (ArgumentException ex) { Log.LogErrorWithCodeFromResources("Exec.InvalidRegex", regularExpression, ex.Message); // Clear out the regex so there won't be any more errors; let the tool continue, // then it will fail because of the error we just logged regularExpression = null; } return match; } /// <summary> /// Validate the task arguments, log any warnings/errors /// </summary> /// <returns>true if arguments are corrent enough to continue processing, false otherwise</returns> protected override bool ValidateParameters() { // If either of the encoding parameters passed to the task were // invalid, then we should report that fact back to tooltask if (!_encodingParametersValid) { return false; } // Make sure that at least the Command property was set if (Command.Trim().Length == 0) { Log.LogErrorWithCodeFromResources("Exec.MissingCommandError"); return false; } // determine what the working directory for the exec command is going to be -- if the user specified a working // directory use that, otherwise it's the current directory _workingDirectory = !string.IsNullOrEmpty(WorkingDirectory) ? WorkingDirectory : Directory.GetCurrentDirectory(); // check if the working directory we're going to use for the exec command is a UNC path workingDirectoryIsUNC = FileUtilitiesRegex.StartsWithUncPattern(_workingDirectory); // if the working directory is a UNC path, and all drive letters are mapped, bail out, because the pushd command // will not be able to auto-map to the UNC path if (workingDirectoryIsUNC && NativeMethods.AllDrivesMapped()) { Log.LogErrorWithCodeFromResources("Exec.AllDriveLettersMappedError", _workingDirectory); return false; } return true; } /// <summary> /// Accessor for ValidateParameters purely for unit-test use /// </summary> /// <returns></returns> internal bool ValidateParametersAccessor() { return ValidateParameters(); } /// <summary> /// Determining the path to cmd.exe /// </summary> /// <returns>path to cmd.exe</returns> protected override string GenerateFullPathToTool() { return CommandProcessorPath.Value; } private static readonly Lazy<string> CommandProcessorPath = new Lazy<string>(() => { // Get the fully qualified path to cmd.exe if (NativeMethodsShared.IsWindows) { var systemCmd = ToolLocationHelper.GetPathToSystemFile("cmd.exe"); #if WORKAROUND_COREFX_19110 // Work around https://github.com/Microsoft/msbuild/issues/2273 and // https://github.com/dotnet/corefx/issues/19110, which result in // a bad path being returned above on Nano Server SKUs of Windows. if (!FileSystems.Default.FileExists(systemCmd)) { return Environment.GetEnvironmentVariable("ComSpec"); } #endif return systemCmd; } else { return "sh"; } }); /// <summary> /// Gets the working directory to use for the process. Should return null if ToolTask should use the /// current directory. /// May throw an IOException if the directory to be used is somehow invalid. /// </summary> /// <returns>working directory</returns> protected override string GetWorkingDirectory() { // If the working directory is UNC, we're going to use "pushd" in the batch file to set it. // If it's invalid, pushd won't fail: it will just go ahead and use the system folder. // So verify it's valid here. if (!FileSystems.Default.DirectoryExists(_workingDirectory)) { throw new DirectoryNotFoundException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Exec.InvalidWorkingDirectory", _workingDirectory)); } if (workingDirectoryIsUNC) { // if the working directory for the exec command is UNC, set the process working directory to the system path // so that it doesn't display this silly error message: // '\\<server>\<share>' // CMD.EXE was started with the above path as the current directory. // UNC paths are not supported. Defaulting to Windows directory. return ToolLocationHelper.PathToSystem; } else { return _workingDirectory; } } /// <summary> /// Accessor for GetWorkingDirectory purely for unit-test use /// </summary> /// <returns></returns> internal string GetWorkingDirectoryAccessor() { return GetWorkingDirectory(); } /// <summary> /// Adds the arguments for cmd.exe /// </summary> /// <param name="commandLine">command line builder class to add arguments to</param> protected internal override void AddCommandLineCommands(CommandLineBuilderExtension commandLine) { // Create the batch file now, // so we have the file name for the cmd.exe command line CreateTemporaryBatchFile(); string batchFileForCommandLine = _batchFile; // Unix consoles cannot have their encodings changed in place (like chcp on windows). // Instead, unix scripts receive encoding information via environment variables before invocation. // In consequence, encoding setup has to be performed outside the script, not inside it. if (NativeMethodsShared.IsUnixLike) { commandLine.AppendSwitch("-c"); commandLine.AppendTextUnquoted(" \""); commandLine.AppendTextUnquoted("export LANG=en_US.UTF-8; export LC_ALL=en_US.UTF-8; . "); commandLine.AppendFileNameIfNotNull(batchFileForCommandLine); commandLine.AppendTextUnquoted("\""); } else { if (NativeMethodsShared.IsWindows) { commandLine.AppendSwitch("/Q"); // echo off if(!Traits.Instance.EscapeHatches.UseAutoRunWhenLaunchingProcessUnderCmd) { commandLine.AppendSwitch("/D"); // do not load AutoRun configuration from the registry (perf) } commandLine.AppendSwitch("/C"); // run then terminate // If for some crazy reason the path has a & character and a space in it // then get the short path of the temp path, which should not have spaces in it // and then escape the & if (batchFileForCommandLine.Contains("&") && !batchFileForCommandLine.Contains("^&")) { batchFileForCommandLine = NativeMethodsShared.GetShortFilePath(batchFileForCommandLine); batchFileForCommandLine = batchFileForCommandLine.Replace("&", "^&"); } } commandLine.AppendFileNameIfNotNull(batchFileForCommandLine); } } #endregion #region Overridden properties /// <summary> /// The name of the tool to execute /// </summary> protected override string ToolName => NativeMethodsShared.IsWindows ? "cmd.exe" : "sh"; /// <summary> /// Importance with which to log ordinary messages in the /// standard error stream. /// </summary> protected override MessageImportance StandardErrorLoggingImportance => MessageImportance.High; /// <summary> /// Importance with which to log ordinary messages in the /// standard out stream. /// </summary> /// <remarks> /// Overridden to increase from the default "Low" up to "High". /// </remarks> protected override MessageImportance StandardOutputLoggingImportance => MessageImportance.High; #endregion } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using Zenject.ReflectionBaking.Mono.Cecil.Cil; using Zenject.ReflectionBaking.Mono.Collections.Generic; using RVA = System.UInt32; namespace Zenject.ReflectionBaking.Mono.Cecil { public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider { ushort attributes; ushort impl_attributes; internal volatile bool sem_attrs_ready; internal MethodSemanticsAttributes sem_attrs; Collection<CustomAttribute> custom_attributes; Collection<SecurityDeclaration> security_declarations; internal RVA rva; internal PInvokeInfo pinvoke; Collection<MethodReference> overrides; internal MethodBody body; public MethodAttributes Attributes { get { return (MethodAttributes) attributes; } set { attributes = (ushort) value; } } public MethodImplAttributes ImplAttributes { get { return (MethodImplAttributes) impl_attributes; } set { impl_attributes = (ushort) value; } } public MethodSemanticsAttributes SemanticsAttributes { get { if (sem_attrs_ready) return sem_attrs; if (HasImage) { ReadSemantics (); return sem_attrs; } sem_attrs = MethodSemanticsAttributes.None; sem_attrs_ready = true; return sem_attrs; } set { sem_attrs = value; } } internal void ReadSemantics () { if (sem_attrs_ready) return; var module = this.Module; if (module == null) return; if (!module.HasImage) return; module.Read (this, (method, reader) => reader.ReadAllSemantics (method)); } public bool HasSecurityDeclarations { get { if (security_declarations != null) return security_declarations.Count > 0; return this.GetHasSecurityDeclarations (Module); } } public Collection<SecurityDeclaration> SecurityDeclarations { get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public int RVA { get { return (int) rva; } } public bool HasBody { get { return (attributes & (ushort) MethodAttributes.Abstract) == 0 && (attributes & (ushort) MethodAttributes.PInvokeImpl) == 0 && (impl_attributes & (ushort) MethodImplAttributes.InternalCall) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Native) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Unmanaged) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Runtime) == 0; } } public MethodBody Body { get { MethodBody localBody = this.body; if (localBody != null) return localBody; if (!HasBody) return null; if (HasImage && rva != 0) return Module.Read (ref body, this, (method, reader) => reader.ReadMethodBody (method)); return body = new MethodBody (this); } set { var module = this.Module; if (module == null) { body = value; return; } // we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe lock (module.SyncRoot) { body = value; } } } public bool HasPInvokeInfo { get { if (pinvoke != null) return true; return IsPInvokeImpl; } } public PInvokeInfo PInvokeInfo { get { if (pinvoke != null) return pinvoke; if (HasImage && IsPInvokeImpl) return Module.Read (ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo (method)); return null; } set { IsPInvokeImpl = true; pinvoke = value; } } public bool HasOverrides { get { if (overrides != null) return overrides.Count > 0; return HasImage && Module.Read (this, (method, reader) => reader.HasOverrides (method)); } } public Collection<MethodReference> Overrides { get { if (overrides != null) return overrides; if (HasImage) return Module.Read (ref overrides, this, (method, reader) => reader.ReadOverrides (method)); return overrides = new Collection<MethodReference> (); } } public override bool HasGenericParameters { get { if (generic_parameters != null) return generic_parameters.Count > 0; return this.GetHasGenericParameters (Module); } } public override Collection<GenericParameter> GenericParameters { get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); } } #region MethodAttributes public bool IsCompilerControlled { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled, value); } } public bool IsPrivate { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private, value); } } public bool IsFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem, value); } } public bool IsAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly, value); } } public bool IsFamily { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family, value); } } public bool IsFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public, value); } } public bool IsStatic { get { return attributes.GetAttributes ((ushort) MethodAttributes.Static); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Static, value); } } public bool IsFinal { get { return attributes.GetAttributes ((ushort) MethodAttributes.Final); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Final, value); } } public bool IsVirtual { get { return attributes.GetAttributes ((ushort) MethodAttributes.Virtual); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Virtual, value); } } public bool IsHideBySig { get { return attributes.GetAttributes ((ushort) MethodAttributes.HideBySig); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HideBySig, value); } } public bool IsReuseSlot { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot, value); } } public bool IsNewSlot { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot, value); } } public bool IsCheckAccessOnOverride { get { return attributes.GetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((ushort) MethodAttributes.Abstract); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Abstract, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) MethodAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.SpecialName, value); } } public bool IsPInvokeImpl { get { return attributes.GetAttributes ((ushort) MethodAttributes.PInvokeImpl); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.PInvokeImpl, value); } } public bool IsUnmanagedExport { get { return attributes.GetAttributes ((ushort) MethodAttributes.UnmanagedExport); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.UnmanagedExport, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) MethodAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((ushort) MethodAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HasSecurity, value); } } #endregion #region MethodImplAttributes public bool IsIL { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL, value); } } public bool IsNative { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native, value); } } public bool IsRuntime { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime, value); } } public bool IsUnmanaged { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged, value); } } public bool IsManaged { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed, value); } } public bool IsForwardRef { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.ForwardRef); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.ForwardRef, value); } } public bool IsPreserveSig { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.PreserveSig); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.PreserveSig, value); } } public bool IsInternalCall { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.InternalCall); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.InternalCall, value); } } public bool IsSynchronized { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.Synchronized); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.Synchronized, value); } } public bool NoInlining { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoInlining); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoInlining, value); } } public bool NoOptimization { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoOptimization); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoOptimization, value); } } #endregion #region MethodSemanticsAttributes public bool IsSetter { get { return this.GetSemantics (MethodSemanticsAttributes.Setter); } set { this.SetSemantics (MethodSemanticsAttributes.Setter, value); } } public bool IsGetter { get { return this.GetSemantics (MethodSemanticsAttributes.Getter); } set { this.SetSemantics (MethodSemanticsAttributes.Getter, value); } } public bool IsOther { get { return this.GetSemantics (MethodSemanticsAttributes.Other); } set { this.SetSemantics (MethodSemanticsAttributes.Other, value); } } public bool IsAddOn { get { return this.GetSemantics (MethodSemanticsAttributes.AddOn); } set { this.SetSemantics (MethodSemanticsAttributes.AddOn, value); } } public bool IsRemoveOn { get { return this.GetSemantics (MethodSemanticsAttributes.RemoveOn); } set { this.SetSemantics (MethodSemanticsAttributes.RemoveOn, value); } } public bool IsFire { get { return this.GetSemantics (MethodSemanticsAttributes.Fire); } set { this.SetSemantics (MethodSemanticsAttributes.Fire, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public bool IsConstructor { get { return this.IsRuntimeSpecialName && this.IsSpecialName && (this.Name == ".cctor" || this.Name == ".ctor"); } } public override bool IsDefinition { get { return true; } } internal MethodDefinition () { this.token = new MetadataToken (TokenType.Method); } public MethodDefinition (string name, MethodAttributes attributes, TypeReference returnType) : base (name, returnType) { this.attributes = (ushort) attributes; this.HasThis = !this.IsStatic; this.token = new MetadataToken (TokenType.Method); } public override MethodDefinition Resolve () { return this; } } static partial class Mixin { public static ParameterDefinition GetParameter (this MethodBody self, int index) { var method = self.method; if (method.HasThis) { if (index == 0) return self.ThisParameter; index--; } var parameters = method.Parameters; if (index < 0 || index >= parameters.size) return null; return parameters [index]; } public static VariableDefinition GetVariable (this MethodBody self, int index) { var variables = self.Variables; if (index < 0 || index >= variables.size) return null; return variables [index]; } public static bool GetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics) { return (self.SemanticsAttributes & semantics) != 0; } public static void SetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics, bool value) { if (value) self.SemanticsAttributes |= semantics; else self.SemanticsAttributes &= ~semantics; } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace VRS.UI.Controls { /// <summary> /// /// </summary> public delegate void ButtonPressedEventHandler(object sender,System.EventArgs e); /// <summary> /// Button edit control(TextBox + Button). /// </summary> [DefaultEvent("ButtonPressed"),] public class WButtonEdit : WControlBase { protected WTextBoxBase m_pTextBox; private System.Windows.Forms.Timer timer1; private System.ComponentModel.IContainer components; public event ButtonPressedEventHandler ButtonPressed = null; public event ButtonPressedEventHandler EnterKeyPressed = null; public event ButtonPressedEventHandler PlusKeyPressed = null; public new event WValidate_EventHandler Validate = null; private int m_ButtonWidth = 18; private Icon m_ButtonIcon = null; private bool m_ReadOnly = false; private bool m_AcceptsPlussKey = true; private bool m_Modified = false; private int m_FlasCounter = 0; protected bool m_DrawGrayImgForReadOnly = true; protected bool m_DroppedDown = false; /// <summary> /// Default constructor. /// </summary> public WButtonEdit() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitForm call m_pTextBox.LostFocus += new System.EventHandler(this.m_pTextBox_OnLostFocus); m_pTextBox.GotFocus += new System.EventHandler(this.m_pTextBox_OnGotFocus); m_ButtonIcon = Core.LoadIcon("down.ico"); this.BackColor = Color.White; } #region function Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null){ components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.m_pTextBox = new VRS.UI.Controls.WTextBoxBase(); this.timer1 = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.m_pTextBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); this.SuspendLayout(); // // m_pTextBox // this.m_pTextBox.Anchor = (System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right); this.m_pTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.m_pTextBox.DecimalPlaces = 2; this.m_pTextBox.DecMaxValue = 999999999; this.m_pTextBox.DecMinValue = -999999999; this.m_pTextBox.Location = new System.Drawing.Point(3, 2); this.m_pTextBox.Mask = VRS.UI.Controls.WEditBox_Mask.Text; this.m_pTextBox.Name = "m_pTextBox"; this.m_pTextBox.Size = new System.Drawing.Size(86, 13); this.m_pTextBox.TabIndex = 0; this.m_pTextBox.Text = ""; this.m_pTextBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.m_pTextBox_KeyUp); this.m_pTextBox.TextChanged += new System.EventHandler(this.m_pTextBox_TextChanged); // // timer1 // this.timer1.Interval = 150; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // WButtonEdit // this.Controls.AddRange(new System.Windows.Forms.Control[] { this.m_pTextBox}); this.Name = "WButtonEdit"; this.Size = new System.Drawing.Size(118, 20); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.WButtonEdit_MouseMove); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.WButtonEdit_MouseDown); ((System.ComponentModel.ISupportInitialize)(this.m_pTextBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); this.ResumeLayout(false); } #endregion #region Events handling #region function WButtonEdit_MouseMove private void WButtonEdit_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { this.Invalidate(false); } #endregion #region function OnMouseUp protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) { base.OnMouseUp(e); if(e.Button == MouseButtons.Left && IsMouseInButtonRect()){ OnButtonPressed(); } } #endregion #region function WButtonEdit_MouseDown private void WButtonEdit_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if(IsMouseInButtonRect()){ this.Invalidate(false); } } #endregion #region function m_pTextBox_OnGotFocus private void m_pTextBox_OnGotFocus(object sender, System.EventArgs e) { this.BackColor = m_ViewStyle.EditFocusedColor; // this.OnValidate(); } #endregion #region function m_pTextBox_OnLostFocus private void m_pTextBox_OnLostFocus(object sender, System.EventArgs e) { if(!m_DroppedDown){ this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); } } #endregion #region function m_pTextBox_TextChanged private void m_pTextBox_TextChanged(object sender, System.EventArgs e) { base.OnTextChanged(new System.EventArgs()); } #endregion #region function m_pTextBox_KeyUp private void m_pTextBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { this.OnKeyUp(e); } #endregion #region function timer1_Tick private void timer1_Tick(object sender, System.EventArgs e) { if(m_pTextBox.BackColor == this.BackColor){ m_pTextBox.BackColor = m_ViewStyle.FlashColor; } else{ m_pTextBox.BackColor = this.BackColor; } m_FlasCounter++; if(m_FlasCounter > 8){ m_pTextBox.BackColor = this.BackColor; timer1.Enabled = false; } } #endregion #region function OnViewStyleChanged protected override void OnViewStyleChanged(ViewStyle_EventArgs e) { switch(e.PropertyName) { case "EditColor": this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); break; case "EditReadOnlyColor": this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); break; case "EditDisabledColor": this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); break; } this.Invalidate(false); } #endregion #endregion #region function DrawControl protected override void DrawControl(Graphics g,bool hot) { Rectangle rectButton = GetButtonRect(); //----- Draw border around control -------------------------// bool border_hot = hot; Painter.DrawBorder(g,m_ViewStyle,this.ClientRectangle,border_hot); //-----------------------------------------------------------// //----- Draw button ----------------------------------------------------// bool btn_hot = (IsMouseInButtonRect() && hot) || m_DroppedDown; bool btn_pressed = IsMouseInButtonRect() && Control.MouseButtons == MouseButtons.Left && hot; Painter.DrawButton(g,m_ViewStyle,rectButton,border_hot,btn_hot,btn_pressed); //----- End of button drawing ------------------------------------------// //---- Draw icon --------------------------------------------// if(m_ButtonIcon != null){ Rectangle rectI = new Rectangle(rectButton.Left+1,rectButton.Top,rectButton.Width-2,rectButton.Height-2); bool grayed = !this.Enabled || (this.ReadOnly && m_DrawGrayImgForReadOnly); Painter.DrawIcon(g,m_ButtonIcon,rectI,grayed,btn_pressed); } //-------------------------------------------------------------// } #endregion #region function ProcessDialogKey protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData) { System.Windows.Forms.Keys key = keyData; if(key == System.Windows.Forms.Keys.Enter){ this.OnEnterKeyPressed(); return true; } if(key == System.Windows.Forms.Keys.Add){ OnPlusKeyPressed(); return true; } return base.ProcessDialogKey(keyData); } #endregion #region override OnKeyUp /* protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e) { base.OnKeyUp(e); if(e.KeyData == System.Windows.Forms.Keys.Enter){ this.OnEnterKeyPressed(); e.Handled = true; } } */ #endregion #region function IsMouseInButtonRect protected bool IsMouseInButtonRect() { Rectangle rectButton = GetButtonRect(); Point mPos = Control.MousePosition; if(rectButton.Contains(this.PointToClient(mPos))){ return true; } else{ return false; } } #endregion #region fucntion GetButtonRect public Rectangle GetButtonRect() { Rectangle rectButton = new Rectangle(this.Width - m_ButtonWidth,1,m_ButtonWidth - 1,this.Height - 2); return rectButton; } #endregion #region override OnEndedInitialize public override void OnEndedInitialize() { this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); m_pTextBox.Width = this.Width - m_ButtonWidth - 7; } #endregion #region override OnEnabledChanged protected override void OnEnabledChanged(System.EventArgs e) { base.OnEnabledChanged(e); // m_pTextBox.Enabled = this.Enabled; this.BackColor = m_ViewStyle.GetEditColor(this.ReadOnly,this.Enabled); } #endregion #region Public Functions public void FlashControl() { if(!timer1.Enabled){ m_FlasCounter = 0; timer1.Enabled = true; } } #endregion #region Properties Implementation #region Color stuff /// <summary> /// /// </summary> public override Color ForeColor { get{ return base.ForeColor; } set{ base.ForeColor = value; m_pTextBox.ForeColor = value; } } /// <summary> /// /// </summary> public override Color BackColor { get{ return base.BackColor; } set{ base.BackColor = value; m_pTextBox.BackColor = value; Invalidate(false); } } #endregion /// <summary> /// /// </summary> public new Size Size { get{ return base.Size; } set{ if(value.Height > m_pTextBox.Height + 1){ base.Size = value; int yPos = (value.Height - m_pTextBox.Height) / 2; m_pTextBox.Top = yPos; } } } /// <summary> /// /// </summary> public int ButtonWidth { get{ return m_ButtonWidth; } set{ m_ButtonWidth = value; m_pTextBox.Width = this.Width - m_ButtonWidth - m_pTextBox.Left - 3; this.Invalidate(); } } /// <summary> /// /// </summary> public Icon ButtonIcon { get{ return m_ButtonIcon; } set{ m_ButtonIcon = value; } } /// <summary> /// True, if value is modified. /// </summary> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public bool IsModified { get{ return m_pTextBox.Modified; } set{ m_pTextBox.Modified = value; } } /// <summary> /// /// </summary> public bool AcceptsPlussKey { get{ return m_AcceptsPlussKey; } set{ m_AcceptsPlussKey = value; } } /// <summary> /// /// </summary> public bool ReadOnly { get{ return m_ReadOnly; } set{ m_ReadOnly = value; m_pTextBox.ReadOnly = value; if(value){ this.BackColor = m_ViewStyle.EditReadOnlyColor; } else{ if(this.ContainsFocus){ this.BackColor = m_ViewStyle.EditFocusedColor; } else{ this.BackColor = m_ViewStyle.EditColor; } } } } /// <summary> /// /// </summary> public int MaxLength { get{ return m_pTextBox.MaxLength; } set{ m_pTextBox.MaxLength = value; } } /// <summary> /// /// </summary> [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] public override string Text { get{ return m_pTextBox.Text; } set{ m_pTextBox.Text = value; } } [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public DateTime DateValue { get{ return m_pTextBox.DateValue; } set{ m_pTextBox.DateValue = value; } } public WEditBox_Mask Mask { get{ return m_pTextBox.Mask; } set{ m_pTextBox.Mask = value; } } #endregion #region Events Implementation #region function OnButtonPressed protected virtual void OnButtonPressed() { // Raises the ladu change event; System.EventArgs oArg = new System.EventArgs(); if(this.ButtonPressed != null && !this.ReadOnly && this.Enabled){ this.ButtonPressed(this, oArg); } } #endregion #region function OnEnterKeyPressed protected virtual void OnEnterKeyPressed() { // Raises the ladu change event; System.EventArgs oArg = new System.EventArgs(); if(this.EnterKeyPressed != null){ this.EnterKeyPressed(this, oArg); } } #endregion #region function OnPlusKeyPressed protected virtual void OnPlusKeyPressed() { System.EventArgs oArg = new System.EventArgs(); // Raise event if(this.PlusKeyPressed != null && !this.ReadOnly && this.Enabled){ this.PlusKeyPressed(this, oArg); } } #endregion #region function OnValidate protected virtual void OnValidate() { // Raises the Validate change event; WValidate_EventArgs oArg = new WValidate_EventArgs(this.Name,this.Text); if(this.Validate != null){ this.Validate(this, oArg); } //---- If validation failed ----// if(!oArg.IsValid){ if(oArg.FlashControl){ this.FlashControl(); } if(!oArg.AllowMoveFocus){ this.Focus(); } } //------------------------------// } #endregion #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* * ToolboxService.cs - used to add/remove/find/select toolbox items * * Authors: * Michael Hutchinson <[email protected]> * * Copyright (C) 2005 Michael Hutchinson * * This sourcecode is licenced under The MIT License: * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Drawing.Design; using System.Collections; using System.IO; using System.Xml; using System.Reflection; using System.ComponentModel; using System.Runtime.Serialization.Formatters.Binary; namespace AspNetEdit.Editor.ComponentModel { public class ToolboxService : IToolboxService { Hashtable categories = new Hashtable (); private string selectedCategory; private ToolboxItem selectedItem = null; public event EventHandler ToolboxChanged; protected void OnToolboxChanged () { ToolboxChanged (this, new EventArgs ()); } #region IToolboxService Members public void AddCreator (ToolboxItemCreatorCallback creator, string format, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public void AddCreator (ToolboxItemCreatorCallback creator, string format) { throw new NotImplementedException (); } public void AddLinkedToolboxItem (ToolboxItem toolboxItem, string category, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public void AddLinkedToolboxItem (ToolboxItem toolboxItem, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public void AddToolboxItem (ToolboxItem toolboxItem) { AddToolboxItem (toolboxItem, "General"); } public void AddToolboxItem (ToolboxItem toolboxItem, string category) { if (!categories.ContainsKey (category)) categories[category] = new ArrayList (); System.Diagnostics.Trace.WriteLine ("Adding ToolboxItem: " + toolboxItem.DisplayName + ", " + category); ((ArrayList) categories[category]).Add (toolboxItem); } public CategoryNameCollection CategoryNames { get { string[] cats = new string[categories.Keys.Count]; categories.Keys.CopyTo (cats, 0); return new CategoryNameCollection (cats); } } public ToolboxItem DeserializeToolboxItem(object serializedObject, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public ToolboxItem DeserializeToolboxItem (object serializedObject) { if ( !(serializedObject is byte[])) return null; MemoryStream ms = new MemoryStream( (byte[]) serializedObject); object obj = BF.Deserialize (ms); ms.Close (); if (! (obj is ToolboxItem)) return null; return (ToolboxItem) obj; } public ToolboxItem GetSelectedToolboxItem (System.ComponentModel.Design.IDesignerHost host) { IToolboxUser toolboxUser = (IToolboxUser) host.GetDesigner (host.RootComponent); if (toolboxUser.GetToolSupported (selectedItem)) return selectedItem; else return null; } public ToolboxItem GetSelectedToolboxItem () { return selectedItem; } public ToolboxItemCollection GetToolboxItems (string category, System.ComponentModel.Design.IDesignerHost host) { if (!categories.ContainsKey (category)) return null; ArrayList tools = new ArrayList (); foreach(ToolboxItem tool in ((ArrayList) categories[category])) if (((IToolboxUser) host.GetDesigner (host.RootComponent)).GetToolSupported (tool)) tools.Add (tool); return new ToolboxItemCollection ((ToolboxItem[]) tools.ToArray (typeof (ToolboxItem))); } public ToolboxItemCollection GetToolboxItems (string category) { if (!categories.ContainsKey (category)) return null; ArrayList tools = (ArrayList) categories[category]; return new ToolboxItemCollection ((ToolboxItem[]) tools.ToArray (typeof (ToolboxItem))); } public ToolboxItemCollection GetToolboxItems (System.ComponentModel.Design.IDesignerHost host) { ArrayList tools = new ArrayList(); IToolboxUser toolboxUser = (IToolboxUser) host.GetDesigner (host.RootComponent); foreach (ArrayList arr in categories.Values) foreach (ToolboxItem tool in arr) if (toolboxUser.GetToolSupported (tool)) tools.Add (tool); return new ToolboxItemCollection ((ToolboxItem[]) tools.ToArray (typeof (ToolboxItem))); } public ToolboxItemCollection GetToolboxItems () { ArrayList tools = new ArrayList (); foreach (ArrayList arr in categories.Values) tools.AddRange (arr); return new ToolboxItemCollection ((ToolboxItem[]) tools.ToArray (typeof (ToolboxItem))); } public bool IsSupported (object serializedObject, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public bool IsSupported (object serializedObject, System.Collections.ICollection filterAttributes) { throw new NotImplementedException (); } public bool IsToolboxItem (object serializedObject, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public bool IsToolboxItem (object serializedObject) { throw new NotImplementedException (); } public void Refresh () { throw new NotImplementedException (); } public void RemoveCreator (string format, System.ComponentModel.Design.IDesignerHost host) { throw new NotImplementedException (); } public void RemoveCreator (string format) { throw new NotImplementedException (); } public void RemoveToolboxItem (ToolboxItem toolboxItem, string category) { throw new NotImplementedException (); } public void RemoveToolboxItem (ToolboxItem toolboxItem) { throw new NotImplementedException (); } public string SelectedCategory { get {return selectedCategory;} set { if (categories.ContainsKey (value)) selectedCategory = value; } } public void SelectedToolboxItemUsed () { //throw new NotImplementedException (); } public object SerializeToolboxItem (ToolboxItem toolboxItem) { MemoryStream ms = new MemoryStream (); BF.Serialize (ms, toolboxItem); byte[] retval = ms.ToArray (); ms.Close (); return retval; } public bool SetCursor () { throw new NotImplementedException (); } public void SetSelectedToolboxItem (ToolboxItem toolboxItem) { this.selectedItem = toolboxItem; } #endregion #region Save/load routines public void Persist (Stream stream) { StreamWriter strw = new StreamWriter (stream); XmlTextWriter xw = new XmlTextWriter (strw); xw.WriteStartDocument (true); xw.WriteStartElement ("Toolbox"); foreach(string key in categories.Keys) { xw.WriteStartElement ("ToolboxCategory"); xw.WriteAttributeString ("name", key); foreach (ToolboxItem item in ((ArrayList)categories[key])) { xw.WriteStartElement ("ToolboxItem"); xw.WriteAttributeString ("DisplayName", item.DisplayName); //xw.WriteAttributeString ("AssemblyName", item.AssemblyName.ToString()); xw.WriteAttributeString ("TypeName", item.TypeName); byte[] serItem = (byte[]) SerializeToolboxItem(item); xw.WriteString (ToBinHexString(serItem)); xw.WriteEndElement (); } xw.WriteEndElement (); } xw.WriteEndElement (); xw.Close (); strw.Close (); } //temporary method until we get a UI and some form of persistence) public void PopulateFromAssembly (Assembly assembly) { Type[] types = assembly.GetTypes (); foreach (Type t in types) { if (t.IsAbstract || t.IsNotPublic) continue; if (t.GetConstructor (new Type[] {}) == null) continue; AttributeCollection atts = TypeDescriptor.GetAttributes (t); bool containsAtt = false; foreach (Attribute a in atts) if (a.GetType() == typeof (ToolboxItemAttribute)) containsAtt = true; if (!containsAtt) continue; ToolboxItemAttribute tba = (ToolboxItemAttribute) atts[typeof(ToolboxItemAttribute)]; if (tba.Equals (ToolboxItemAttribute.None)) continue; //FIXME: fix WebControlToolboxItem Type toolboxItemType = typeof (ToolboxItem);//(tba.ToolboxItemType == null) ? typeof (ToolboxItem) : tba.ToolboxItemType; string category = "General"; if (t.IsSubclassOf (typeof (System.Web.UI.WebControls.BaseValidator))) category = "Validation"; else if (t.Namespace == "System.Web.UI.HtmlControls" && t.IsSubclassOf (typeof (System.Web.UI.HtmlControls.HtmlControl))) category = "Html Elements"; else if (t.IsSubclassOf (typeof (System.Web.UI.WebControls.BaseDataList))) category = "Data Controls"; else if (t.IsSubclassOf (typeof (System.Web.UI.WebControls.WebControl))) category = "Web Controls"; AddToolboxItem ((ToolboxItem) Activator.CreateInstance (toolboxItemType, new object[] {t}), category); } OnToolboxChanged (); } #endregion private BinaryFormatter bf = null; private BinaryFormatter BF { get { if (bf == null) bf = new BinaryFormatter (); return bf; } } #region Borrowed from System.Xml.XmlConvert. If only the methods were public as documented... // Authors: Dwivedi, Ajay kumar ([email protected]), Gonzalo Paniagua Javier ([email protected]) // Alan Tam Siu Lung ([email protected]), Atsushi Enomoto ([email protected]) // License: MIT X11 (same as file) // Copyright: (C) 2002 Ximian, Inc (http://www.ximian.com // LAMESPEC: It has been documented as public, but is marked as internal. private string ToBinHexString (byte [] buffer) { StringWriter w = new StringWriter (); WriteBinHex (buffer, 0, buffer.Length, w); return w.ToString (); } internal static void WriteBinHex (byte [] buffer, int index, int count, TextWriter w) { if (buffer == null) throw new ArgumentNullException ("buffer"); if (index < 0) throw new ArgumentOutOfRangeException ("index", index, "index must be non negative integer."); if (count < 0) throw new ArgumentOutOfRangeException ("count", count, "count must be non negative integer."); if (buffer.Length < index + count) throw new ArgumentOutOfRangeException ("index and count must be smaller than the length of the buffer."); // Copied from XmlTextWriter.WriteBinHex () int end = index + count; for (int i = index; i < end; i++) { int val = buffer [i]; int high = val >> 4; int low = val & 15; if (high > 9) w.Write ((char) (high + 55)); else w.Write ((char) (high + 0x30)); if (low > 9) w.Write ((char) (low + 55)); else w.Write ((char) (low + 0x30)); } } // It is documented as public method, but in fact it is not. private byte [] FromBinHexString (string s) { char [] chars = s.ToCharArray (); byte [] bytes = new byte [chars.Length / 2 + chars.Length % 2]; FromBinHexString (chars, 0, chars.Length, bytes); return bytes; } private int FromBinHexString (char [] chars, int offset, int charLength, byte [] buffer) { int bufIndex = offset; for (int i = 0; i < charLength - 1; i += 2) { buffer [bufIndex] = (chars [i] > '9' ? (byte) (chars [i] - 'A' + 10) : (byte) (chars [i] - '0')); buffer [bufIndex] <<= 4; buffer [bufIndex] += chars [i + 1] > '9' ? (byte) (chars [i + 1] - 'A' + 10) : (byte) (chars [i + 1] - '0'); bufIndex++; } if (charLength %2 != 0) buffer [bufIndex++] = (byte) ((chars [charLength - 1] > '9' ? (byte) (chars [charLength - 1] - 'A' + 10) : (byte) (chars [charLength - 1] - '0')) << 4); return bufIndex - offset; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.AssetService { /// <summary> /// A de-duplicating asset service. /// </summary> public class XAssetService : XAssetServiceBase, IAssetService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected static XAssetService m_RootInstance; public XAssetService(IConfigSource config) : this(config, "AssetService") {} public XAssetService(IConfigSource config, string configName) : base(config, configName) { if (m_RootInstance == null) { m_RootInstance = this; if (m_AssetLoader != null) { IConfig assetConfig = config.Configs[configName]; if (assetConfig == null) throw new Exception("No AssetService configuration"); string loaderArgs = assetConfig.GetString("AssetLoaderArgs", String.Empty); bool assetLoaderEnabled = assetConfig.GetBoolean("AssetLoaderEnabled", true); if (assetLoaderEnabled && !HasChainedAssetService) { m_log.DebugFormat("[XASSET SERVICE]: Loading default asset set from {0}", loaderArgs); m_AssetLoader.ForEachDefaultXmlAsset( loaderArgs, a => { AssetBase existingAsset = Get(a.ID); // AssetMetadata existingMetadata = GetMetadata(a.ID); if (existingAsset == null || Util.SHA1Hash(existingAsset.Data) != Util.SHA1Hash(a.Data)) { // m_log.DebugFormat("[ASSET]: Storing {0} {1}", a.Name, a.ID); Store(a); } }); } m_log.Debug("[XASSET SERVICE]: Local asset service enabled"); } } } public virtual AssetBase Get(string id) { // m_log.DebugFormat("[ASSET SERVICE]: Get asset for {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) { m_log.WarnFormat("[XASSET SERVICE]: Could not parse requested asset id {0}", id); return null; } try { AssetBase asset = m_Database.GetAsset(assetID); if (asset != null) { return asset; } else if (HasChainedAssetService) { asset = m_ChainedAssetService.Get(id); if (asset != null) MigrateFromChainedService(asset); return asset; } return null; } catch (Exception e) { m_log.ErrorFormat("[XASSET SERVICE]: Exception getting asset {0} {1}", assetID, e); return null; } } public virtual AssetBase GetCached(string id) { return Get(id); } public virtual AssetMetadata GetMetadata(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Get asset metadata for {0}", id); AssetBase asset = Get(id); if (asset != null) return asset.Metadata; else return null; } public virtual byte[] GetData(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Get asset data for {0}", id); AssetBase asset = Get(id); if (asset != null) return asset.Data; else return null; } public virtual bool Get(string id, Object sender, AssetRetrieved handler) { //m_log.DebugFormat("[XASSET SERVICE]: Get asset async {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; AssetBase asset = Get(id); //m_log.DebugFormat("[XASSET SERVICE]: Got asset {0}", asset); handler(id, sender, asset); return true; } public virtual bool[] AssetsExist(string[] ids) { UUID[] uuid = Array.ConvertAll(ids, id => UUID.Parse(id)); return m_Database.AssetsExist(uuid); } public virtual string Store(AssetBase asset) { bool exists = m_Database.AssetsExist(new[] { asset.FullID })[0]; if (!exists) { // m_log.DebugFormat( // "[XASSET SERVICE]: Storing asset {0} {1}, bytes {2}", asset.Name, asset.FullID, asset.Data.Length); m_Database.StoreAsset(asset); } // else // { // m_log.DebugFormat( // "[XASSET SERVICE]: Not storing asset {0} {1}, bytes {2} as it already exists", asset.Name, asset.FullID, asset.Data.Length); // } return asset.ID; } public bool UpdateContent(string id, byte[] data) { return false; } public virtual bool Delete(string id) { // m_log.DebugFormat("[XASSET SERVICE]: Deleting asset {0}", id); UUID assetID; if (!UUID.TryParse(id, out assetID)) return false; if (HasChainedAssetService) m_ChainedAssetService.Delete(id); return m_Database.Delete(id); } private void MigrateFromChainedService(AssetBase asset) { Store(asset); m_ChainedAssetService.Delete(asset.ID); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using Microsoft.VisualStudio.PlatformUI; using Microsoft.Research.CodeAnalysis; using System.Diagnostics.Contracts; using System.Diagnostics; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI.OleComponentSupport; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Shell.Interop; //using RoslynToCCICodeModel; namespace Microsoft.Research.AskCodeContracts { /// <summary> /// Interaction logic for IsTrue.xaml /// </summary> public partial class IsTrue : Window, IOleComponent { public bool IsValid { private set; get; } public string Assertion { private set; get; } private readonly Func<string, IEnumerable<CodeAssumption>, ProofOutcome?> WorkerForQuery; private readonly Func<string> WorkerForInvariantQuery; private readonly Func<string, IEnumerable<SearchResult>> WorkerForSearchCallersMatchingPredicate; private readonly IWpfTextView wpfTextView; public IsTrue(IWpfTextView wpfTextView, Func<string, IEnumerable<CodeAssumption>, ProofOutcome?> WorkerForQuery, Func<string> WorkerForInvariantQuery, Func<string, IEnumerable<SearchResult>> WorkerForSearchCallersMatchingPredicate, string lastQuery = null) { Contract.Requires(WorkerForQuery != null); Contract.Requires(WorkerForInvariantQuery != null); Contract.Requires(WorkerForSearchCallersMatchingPredicate != null); InitializeComponent(); this.wpfTextView = wpfTextView; this.WorkerForQuery = WorkerForQuery; this.WorkerForInvariantQuery = WorkerForInvariantQuery; this.WorkerForSearchCallersMatchingPredicate = WorkerForSearchCallersMatchingPredicate; this.Assertion = lastQuery; this.IsValid = false; } #region Click handling private void AddAssumption_Click(object sender, RoutedEventArgs e) { var assumption = this.Assumption.Text; if (!string.IsNullOrWhiteSpace(assumption)) { var selectionStart = this.wpfTextView.Selection.Start.Position.Position; var selectionEnd = this.wpfTextView.Selection.End.Position.Position; if(selectionStart == selectionEnd) { var line = this.wpfTextView.Selection.Start.Position.GetContainingLine().LineNumber + 1; Trace.WriteLine(string.Format("Adding assumption {0} @ line {1}, position {2}", assumption, line, selectionStart)); this.Assumptions.Items.Add(new CodeAssumption(selectionStart, line, assumption)); this.Assumption.Text = String.Empty; // swallow the assumption } } } private void ClearAssumptions_Click(object sender, RoutedEventArgs e) { this.Assumptions.Items.Clear(); } private void IsTrueButton_Click(object sender, RoutedEventArgs e) { this.IsValid = true; this.Assertion = this.InputQuery.Text; this.AnswerText.Text = "Thinking..."; this.UpdateLineInTextMessages(); if (!String.IsNullOrEmpty(this.Assertion)) { var result = this.WorkerForQuery(this.Assertion, this.Assumptions.Items.AsEnumerable()); if (result.HasValue) { string text = null; switch (result.Value) { case ProofOutcome.Bottom: text = "No execution reaches this point"; break; case ProofOutcome.False: text = "No, it is false"; break; case ProofOutcome.Top: text = "I do not know. Sometimes may be true, sometimes may be false"; break; case ProofOutcome.True: text = "Yes, it is true"; break; } this.AnswerText.Text = text; } else { this.AnswerText.Text = "Something went wrong"; } } else { this.AnswerText.Text = String.Empty; } } private void GetInvariantButton_Click(object sender, RoutedEventArgs e) { this.InvariantText.Text = "Thinking..."; this.UpdateLineInTextMessages(); var result = this.WorkerForInvariantQuery(); if (result != null) { this.InvariantText.Text = result; } } private void requiresSearchBox_Click(object sender, RoutedEventArgs e) { Trace.WriteLine("Handling the find box"); // var myOutputWindow = VSIntegrationUtilities.OutputWindowManager.CreatePane(GuidList.guidClousotOutputPane, "Clousot find window"); // Clear the previous search this.searchResultsFalseListBox.Items.Clear(); this.searchResultsTopListBox.Items.Clear(); this.searchResultsTrueListBox.Items.Clear(); var query = this.requiresSearchConditionTextBox.Text; foreach (var r in this.WorkerForSearchCallersMatchingPredicate(query)) { switch (r.Outcome) { case ProofOutcome.Bottom: // do nothing; break; case ProofOutcome.False: this.searchResultsFalseListBox.Items.Add(r); break; case ProofOutcome.Top: this.searchResultsTopListBox.Items.Add(r); break; case ProofOutcome.True: this.searchResultsTrueListBox.Items.Add(r); break; default: // impossible; Contract.Assume(false); break; } } } #endregion #region Events protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Key == Key.Delete) { Trace.WriteLine("Hit Delete key"); if (this.Assumptions.IsKeyboardFocusWithin) { var selected = this.Assumptions.SelectedIndex; if (selected >= 0) { Trace.WriteLine(string.Format("Removing the assumption at position {0}", selected)); this.Assumptions.Items.RemoveAt(selected); } } } this.UpdateLineInTextMessages(); } #endregion #region Private private void UpdateLineInTextMessages() { var currLine = this.wpfTextView.Selection.Start.Position.GetContainingLine().LineNumber + 1; this.QueryText.Text = string.Format("Query @line {0} :", currLine); this.InvariantTextLabel.Text = string.Format("State @line {0} :", currLine); } #endregion #region Logic to make sure we do not lose arrows, backspace, etc. protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnGotKeyboardFocus(e); Trace.WriteLine("Get keyboard focus"); AdjustShellTracking(); e.Handled = true; } protected override void OnLostKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnLostKeyboardFocus(e); AdjustShellTracking(); Trace.WriteLine("Lost keyboard focus"); } public void AdjustShellTracking() { // See if our keyboard focus is within our self if (IsKeyboardFocusWithin) { // Then see if we should be tracking (only track on text boxes) if (Keyboard.FocusedElement is DependencyObject) { var obj = Keyboard.FocusedElement as DependencyObject; if (obj != null /*&& obj.FindParentOfType<TextBoxBase>() != null*/) { IsShellTrackingMe = true; } else { IsShellTrackingMe = false; } } else { IsShellTrackingMe = false; } } else { IsShellTrackingMe = false; } // Update our indicators that we are active. Our border and the caret will change if // we are tracking if (this.wpfTextView != null && this.wpfTextView.Caret != null) this.wpfTextView.Caret.IsHidden = IsShellTrackingMe; // If we have the keyboard focus, but we are not shell tracking, make sure // to set the keyboard focus back to the text editor. Otherwise // it looks like nobody has the focus if (this.wpfTextView != null && IsKeyboardFocusWithin && !IsShellTrackingMe) Keyboard.Focus(this.wpfTextView.VisualElement); } /// <summary> /// Indicates if this tip is the IOleComponent that is being tracked by the shell. This is necessary /// to ensure that keyboard input is sent entirely to the WPF window. Otherwise the PreTranslateMessage of /// the shell will send it to other windows. (Like backspace going to the editor window) /// </summary> public bool IsShellTrackingMe { get { return _isTracking; } set { if (_isTracking != value) { if (value) { // Register ourselves as a tracking component so we // get first crack at backspace/up/down/left/right/CTRL+A/CTRL+C // Sometimes this might not work because somebody else is already // the tracking target. _isTracking = VSIntegrationUtilities.OLE.StartTrackingComponent(this); } else { // Unregister ourselves as a command target VSIntegrationUtilities.OLE.StopTrackingComponent(this); // This always succeeds. Can't not unregister _isTracking = false; } } } } private bool _isTracking; #region implementation of IOleComponent public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) { // If we have keyboard focus, then allow more messages to be pumped if (IsKeyboardFocusWithin) return 1; return 0; } public int FDoIdle(uint grfidlef) { return 0; } public int FPreTranslateMessage(MSG[] pMsg) { // If we handle it, then tell the shell that (1 means we handled it) return VSIntegrationUtilities.OLE.HandleComponentMessage(pMsg[0]) ? 1 : 0; } public int FQueryTerminate(int fPromptUser) { return 1; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) { return 0; } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) { // F: LOOK AT THAT return IntPtr.Zero; } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnEnterState(uint uStateID, int fEnter) { } public void OnLoseActivation() { } public void Terminate() { } #endregion #endregion } public static class Extensions { public static IEnumerable<CodeAssumption> AsEnumerable(this ItemCollection collection) { if (collection != null) { foreach (var item in collection) { var assumption = item as CodeAssumption; if (assumption != null) { yield return assumption; } } } } } } namespace VSIntegrationUtilities { public static class OutputWindowManager { /// <summary> /// Create an output window /// </summary> static public IVsOutputWindowPane CreatePane(Guid guid, string title, bool visible = true, bool clearWithSolution = true) { var outputWindow = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; if (outputWindow != null) { IVsOutputWindowPane result; outputWindow.CreatePane(ref guid, title, Convert.ToInt32(visible), Convert.ToInt32(clearWithSolution)); outputWindow.GetPane(ref guid, out result); return result; } return null; } } public static class OLE { private static IOleComponent ActiveComponent { get; set; } public static bool HandleComponentMessage(Microsoft.VisualStudio.OLE.Interop.MSG msg) { // Swallow all keyboard input if ((msg.message >= VSIntegrationUtilities.NativeMethods.WM_KEYFIRST && msg.message <= VSIntegrationUtilities.NativeMethods.WM_KEYLAST) || (msg.message >= VSIntegrationUtilities.NativeMethods.WM_IME_FIRST && msg.message <= VSIntegrationUtilities.NativeMethods.WM_IME_LAST)) { /* // Special case when the Alt key is down if (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) { // Give the main window focus. This will allow it to handle // the ALT + <key> commands and bring up the menu. // // This works because we lose focus and revoke IOleComponent tracking status Utilities.NativeMethods.SetFocus(Shell.MainWindow.Handle); return false; } } */ // Otherwise it's our message. Don't let the shell translate it // into some goofy command. // Give WPF a chance to translate. System.Windows.Interop.MSG windowsMsg = NativeMethods.MSGFromOleMSG(ref msg); if (!System.Windows.Interop.ComponentDispatcher.RaiseThreadMessage(ref windowsMsg)) { VSIntegrationUtilities.NativeMethods.TranslateMessage(ref msg); VSIntegrationUtilities.NativeMethods.DispatchMessage(ref msg); } return true; } return false; } /// <summary> /// Exposing Service provider when the class to get the service is different than the interface /// that throws if the GetService call or cast to T fails /// </summary> /// <typeparam name="C">Service SID value. E.g. SVsShell</typeparam> /// <typeparam name="T">Interface to cast to. E.g. IVsShell</typeparam> /// <returns></returns> public static T GetRequiredService<C, T>() where T : class { T serviceInterface = (T)ServiceProvider.GlobalProvider.GetService(typeof(C).GUID); if (serviceInterface == null) { throw new InvalidOperationException(String.Format("GetService for {0} failed!", typeof(T))); } return serviceInterface; } private static IOleComponentManager OleComponentManager { get { return GetRequiredService<SOleComponentManager, IOleComponentManager>(); } } private static Dictionary<IOleComponent, uint> _registeredComponents = new Dictionary<IOleComponent, uint>(); private static uint RegisterComponent(IOleComponent me) { uint returnValue = 0; if (!_registeredComponents.TryGetValue(me, out returnValue)) { // treat us as a modal component that takes care of all input OLECRINFO info = new OLECRINFO(); info.cbSize = (uint)Marshal.SizeOf(info); info.grfcadvf = (uint)_OLECADVF.olecadvfModal; info.grfcrf = (uint)(_OLECRF.olecrfPreTranslateKeys | _OLECRF.olecrfPreTranslateAll | _OLECRF.olecrfNeedAllActiveNotifs | _OLECRF.olecrfExclusiveActivation); OLECRINFO[] array = new OLECRINFO[1]; array[0] = info; OleComponentManager.FRegisterComponent(me, array, out returnValue); _registeredComponents.Add(me, returnValue); } return returnValue; } public static bool StartTrackingComponent(IOleComponent me) { if (ActiveComponent != me) { // Make sure there isn't somebody already registered IOleComponent activeComponent; OleComponentManager.FGetActiveComponent( //(uint)FGetActiveComponentType.olegacTracking, // f: changed 1, out activeComponent, null, 0); if (activeComponent == null) { // Save ourselves as the currently active component (prevents reentrancy) ActiveComponent = me; // Tell the shell we are the active component OleComponentManager.FSetTrackingComponent(RegisterComponent(me), 1); return true; } else if (Marshal.IsComObject(activeComponent)) { Marshal.ReleaseComObject(activeComponent); } } return false; } public static bool StopTrackingComponent(IOleComponent me) { OleComponentManager.FSetTrackingComponent(RegisterComponent(me), 0); if (ActiveComponent == me) { ActiveComponent = null; } return true; } } public static class NativeMethods { public const int WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DELETEITEM = 0x002D, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_NCXBUTTONDOWN = 0x00AB, WM_NCXBUTTONUP = 0x00AC, WM_NCXBUTTONDBLCLK = 0x00AD, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_CTLCOLOR = 0x0019, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_COMPOSITION_FIRST = 0x010D, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_IME_COMPOSITION_LAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, WM_XBUTTONDBLCLK = 0x020D, WM_MOUSEWHEEL = 0x020A, WM_MOUSELAST = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_POWERBROADCAST = 0x0218, WM_DEVICECHANGE = 0x0219, WM_IME_FIRST = 0x0281, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_IME_LAST = 0x0291, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = unchecked((int)0x8000), WM_USER = 0x0400, WM_REFLECT = WM_USER + 0x1C00, WS_OVERLAPPED = 0x00000000, WPF_SETMINPOSITION = 0x0001, WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1), WM_THEMECHANGED = 0x31a; public static System.Windows.Interop.MSG MSGFromOleMSG(ref Microsoft.VisualStudio.OLE.Interop.MSG oleMsg) { System.Windows.Interop.MSG msg = new System.Windows.Interop.MSG(); msg.hwnd = oleMsg.hwnd; msg.message = (int)oleMsg.message; msg.wParam = oleMsg.wParam; msg.lParam = oleMsg.lParam; msg.time = (int)oleMsg.time; msg.pt_x = oleMsg.pt.x; msg.pt_y = oleMsg.pt.y; return msg; } [DllImport("user32.dll")] internal static extern bool TranslateMessage([In] ref MSG lpMsg); [DllImport("user32.dll")] internal static extern IntPtr DispatchMessage([In] ref MSG lpMsg); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Services; using NUnit.Framework; /// <summary> /// Services tests. /// </summary> public class ServicesTest { /** */ private const string SvcName = "Service1"; /** */ private const string CacheName = "cache1"; /** */ private const int AffKey = 25; /** */ protected IIgnite Grid1; /** */ protected IIgnite Grid2; /** */ protected IIgnite Grid3; /** */ protected IIgnite[] Grids; [TestFixtureTearDown] public void FixtureTearDown() { StopGrids(); } /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { StartGrids(); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { Services.CancelAll(); TestUtils.AssertHandleRegistryIsEmpty(1000, Grid1, Grid2, Grid3); } catch (Exception) { // Restart grids to cleanup StopGrids(); throw; } finally { if (TestContext.CurrentContext.Test.Name.StartsWith("TestEventTypes")) StopGrids(); // clean events for other tests } } /// <summary> /// Tests deployment. /// </summary> [Test] public void TestDeploy([Values(true, false)] bool binarizable) { var cfg = new ServiceConfiguration { Name = SvcName, MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.GetCluster().GetLocalNode().Id}, Service = binarizable ? new TestIgniteServiceBinarizable() : new TestIgniteServiceSerializable() }; Services.Deploy(cfg); CheckServiceStarted(Grid1, 3); } /// <summary> /// Tests several services deployment via DeployAll() method. /// </summary> [Test] public void TestDeployAll([Values(true, false)] bool binarizable) { const int num = 10; var cfgs = new List<ServiceConfiguration>(); for (var i = 0; i < num; i++) { cfgs.Add(new ServiceConfiguration { Name = MakeServiceName(i), MaxPerNodeCount = 3, TotalCount = 3, NodeFilter = new NodeFilter {NodeId = Grid1.GetCluster().GetLocalNode().Id}, Service = binarizable ? new TestIgniteServiceBinarizable() : new TestIgniteServiceSerializable() }); } Services.DeployAll(cfgs); for (var i = 0; i < num; i++) { CheckServiceStarted(Grid1, 3, MakeServiceName(i)); } } /// <summary> /// Tests cluster singleton deployment. /// </summary> [Test] public void TestDeployClusterSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployClusterSingleton(SvcName, svc); var svc0 = Services.GetServiceProxy<ITestIgniteService>(SvcName); // Check that only one node has the service. foreach (var grid in Grids) { if (grid.GetCluster().GetLocalNode().Id == svc0.NodeId) CheckServiceStarted(grid); else Assert.IsNull(grid.GetServices().GetService<TestIgniteServiceSerializable>(SvcName)); } } /// <summary> /// Tests node singleton deployment. /// </summary> [Test] public void TestDeployNodeSingleton() { var svc = new TestIgniteServiceSerializable(); Services.DeployNodeSingleton(SvcName, svc); Assert.AreEqual(1, Grid1.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(1, Grid2.GetServices().GetServices<ITestIgniteService>(SvcName).Count); Assert.AreEqual(0, Grid3.GetServices().GetServices<ITestIgniteService>(SvcName).Count); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingleton() { var svc = new TestIgniteServiceBinarizable(); Services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, AffKey); var affNode = Grid1.GetAffinity(CacheName).MapKeyToNode(AffKey); var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(affNode.Id, prx.NodeId); } /// <summary> /// Tests key affinity singleton deployment. /// </summary> [Test] public void TestDeployKeyAffinitySingletonBinarizable() { var services = Services.WithKeepBinary(); var svc = new TestIgniteServiceBinarizable(); var affKey = new BinarizableObject {Val = AffKey}; services.DeployKeyAffinitySingleton(SvcName, svc, CacheName, affKey); var prx = services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.IsTrue(prx.Initialized); } /// <summary> /// Tests multiple deployment. /// </summary> [Test] public void TestDeployMultiple() { var svc = new TestIgniteServiceSerializable(); Services.DeployMultiple(SvcName, svc, Grids.Length * 5, 5); foreach (var grid in Grids.Where(x => !x.GetConfiguration().ClientMode)) CheckServiceStarted(grid, 5); } /// <summary> /// Tests cancellation. /// </summary> [Test] public void TestCancel() { for (var i = 0; i < 10; i++) { Services.DeployNodeSingleton(SvcName + i, new TestIgniteServiceBinarizable()); Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); } Services.Cancel(SvcName + 0); AssertNoService(SvcName + 0); Services.Cancel(SvcName + 1); AssertNoService(SvcName + 1); for (var i = 2; i < 10; i++) Assert.IsNotNull(Services.GetService<ITestIgniteService>(SvcName + i)); Services.CancelAll(); for (var i = 0; i < 10; i++) AssertNoService(SvcName + i); } /// <summary> /// Tests service proxy. /// </summary> [Test] public void TestGetServiceProxy([Values(true, false)] bool binarizable) { // Test proxy without a service var ex = Assert.Throws<IgniteException>(()=> Services.GetServiceProxy<ITestIgniteService>(SvcName)); Assert.AreEqual("Failed to find deployed service: " + SvcName, ex.Message); // Deploy to grid1 & grid2 var svc = binarizable ? new TestIgniteServiceBinarizable {TestProperty = 17} : new TestIgniteServiceSerializable {TestProperty = 17}; Grid3.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id, Grid1.GetCluster().GetLocalNode().Id) .GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid3 Assert.IsNull(Grid3.GetServices().GetService<ITestIgniteService>(SvcName)); // Get proxy var prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName); // Check proxy properties Assert.IsNotNull(prx); Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual(17, prx.TestProperty); Assert.IsTrue(prx.Initialized); // ReSharper disable once AccessToModifiedClosure Assert.IsTrue(TestUtils.WaitForCondition(() => prx.Executed, 5000)); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Check err method Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); // Check local scenario (proxy should not be created for local instance) Assert.IsTrue(ReferenceEquals(Grid2.GetServices().GetService<ITestIgniteService>(SvcName), Grid2.GetServices().GetServiceProxy<ITestIgniteService>(SvcName))); // Check sticky = false: call multiple times, check that different nodes get invoked var invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(2, invokedIds.Count); // Check sticky = true: all calls should be to the same node prx = Grid3.GetServices().GetServiceProxy<ITestIgniteService>(SvcName, true); invokedIds = Enumerable.Range(1, 100).Select(x => prx.NodeId).Distinct().ToList(); Assert.AreEqual(1, invokedIds.Count); // Proxy does not work for cancelled service. Services.CancelAll(); Assert.Throws<ServiceInvocationException>(() => { Assert.IsTrue(prx.Cancelled); }); } /// <summary> /// Tests dynamic service proxies. /// </summary> [Test] public void TestGetDynamicServiceProxy() { // Deploy to remotes. var svc = new TestIgniteServiceSerializable { TestProperty = 37 }; Grid3.GetCluster().ForRemotes().GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is no local instance on grid3 Assert.IsNull(Grid3.GetServices().GetService<ITestIgniteService>(SvcName)); // Get proxy. dynamic prx = Grid3.GetServices().GetDynamicServiceProxy(SvcName, true); // Property getter. Assert.AreEqual(37, prx.TestProperty); Assert.IsTrue(prx.Initialized); Assert.IsTrue(TestUtils.WaitForCondition(() => prx.Executed, 5000)); Assert.IsFalse(prx.Cancelled); Assert.AreEqual(SvcName, prx.LastCallContextName); // Property setter. prx.TestProperty = 42; Assert.AreEqual(42, prx.TestProperty); // Method invoke. Assert.AreEqual(prx.ToString(), svc.ToString()); Assert.AreEqual("baz", prx.Method("baz")); // Non-existent member. var ex = Assert.Throws<ServiceInvocationException>(() => prx.FooBar(1)); Assert.AreEqual( string.Format("Failed to invoke proxy: there is no method 'FooBar' in type '{0}' with 1 arguments", typeof(TestIgniteServiceSerializable)), (ex.InnerException ?? ex).Message); // Exception in service. ex = Assert.Throws<ServiceInvocationException>(() => prx.ErrMethod(123)); Assert.AreEqual("ExpectedException", (ex.InnerException ?? ex).Message.Substring(0, 17)); } /// <summary> /// Tests dynamic service proxies with local service instance. /// </summary> [Test] public void TestGetDynamicServiceProxyLocal() { // Deploy to all nodes. var svc = new TestIgniteServiceSerializable { TestProperty = 37 }; Grid1.GetServices().DeployNodeSingleton(SvcName, svc); // Make sure there is an instance on grid1. var svcInst = Grid1.GetServices().GetService<ITestIgniteService>(SvcName); Assert.IsNotNull(svcInst); // Get dynamic proxy that simply wraps the service instance. var prx = Grid1.GetServices().GetDynamicServiceProxy(SvcName); Assert.AreSame(prx, svcInst); } /// <summary> /// Tests the duck typing: proxy interface can be different from actual service interface, /// only called method signature should be compatible. /// </summary> [Test] public void TestDuckTyping([Values(true, false)] bool local) { var svc = new TestIgniteServiceBinarizable {TestProperty = 33}; // Deploy locally or to the remote node var nodeId = (local ? Grid1 : Grid2).GetCluster().GetLocalNode().Id; var cluster = Grid1.GetCluster().ForNodeIds(nodeId); cluster.GetServices().DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.GetServiceProxy<ITestIgniteServiceProxyInterface>(SvcName); // NodeId signature is the same as in service Assert.AreEqual(nodeId, prx.NodeId); // Method signature is different from service signature (object -> object), but is compatible. Assert.AreEqual(15, prx.Method(15)); // TestProperty is object in proxy and int in service, getter works.. Assert.AreEqual(33, prx.TestProperty); // .. but setter does not var ex = Assert.Throws<ServiceInvocationException>(() => { prx.TestProperty = new object(); }); Assert.IsInstanceOf<InvalidCastException>(ex.InnerException); } /// <summary> /// Test call service proxy from remote node with a methods having an array of user types and objects. /// </summary> [Test] public void TestCallServiceProxyWithTypedArrayParameters() { // Deploy to the remote node. var nodeId = Grid2.GetCluster().GetLocalNode().Id; var cluster = Grid1.GetCluster().ForNodeIds(nodeId); cluster.GetServices().DeployNodeSingleton(SvcName, new TestIgniteServiceArraySerializable()); var typedArray = new[] {10, 11, 12} .Select(x => new PlatformComputeBinarizable {Field = x}).ToArray(); var objArray = typedArray.ToArray<object>(); // object[] var prx = Services.GetServiceProxy<ITestIgniteServiceArray>(SvcName); Assert.AreEqual(new[] {11, 12, 13}, prx.TestBinarizableArrayOfObjects(objArray) .OfType<PlatformComputeBinarizable>().Select(x => x.Field).ToArray()); Assert.IsNull(prx.TestBinarizableArrayOfObjects(null)); Assert.IsEmpty(prx.TestBinarizableArrayOfObjects(new object[0])); // T[] Assert.AreEqual(new[] {11, 12, 13}, prx.TestBinarizableArray(typedArray) .Select(x => x.Field).ToArray()); Assert.IsEmpty(prx.TestBinarizableArray(new PlatformComputeBinarizable[0])); Assert.IsNull(prx.TestBinarizableArray(null)); // BinaryObject[] var binPrx = cluster.GetServices() .WithKeepBinary() .WithServerKeepBinary() .GetServiceProxy<ITestIgniteServiceArray>(SvcName); var res = binPrx.TestBinaryObjectArray( typedArray.Select(Grid1.GetBinary().ToBinary<IBinaryObject>).ToArray()); Assert.AreEqual(new[] {11, 12, 13}, res.Select(b => b.GetField<int>("Field"))); // TestBinarizableArray2 has no corresponding class in Java. var typedArray2 = new[] {10, 11, 12} .Select(x => new PlatformComputeBinarizable2 {Field = x}).ToArray(); var actual = prx.TestBinarizableArray2(typedArray2) .Select(x => x.Field).ToArray(); Assert.AreEqual(new[] {11, 12, 13}, actual); } /// <summary> /// Tests service descriptors. /// </summary> [Test] public void TestServiceDescriptors() { Services.DeployKeyAffinitySingleton(SvcName, new TestIgniteServiceSerializable(), CacheName, 1); var descriptors = Services.GetServiceDescriptors(); Assert.AreEqual(1, descriptors.Count); var desc = descriptors.Single(); Assert.AreEqual(SvcName, desc.Name); Assert.AreEqual(CacheName, desc.CacheName); Assert.AreEqual(1, desc.AffinityKey); Assert.AreEqual(1, desc.MaxPerNodeCount); Assert.AreEqual(1, desc.TotalCount); Assert.AreEqual(Grid1.GetCluster().GetLocalNode().Id, desc.OriginNodeId); var top = desc.TopologySnapshot; var prx = Services.GetServiceProxy<ITestIgniteService>(SvcName); Assert.AreEqual(1, top.Count); Assert.AreEqual(prx.NodeId, top.Keys.Single()); Assert.AreEqual(1, top.Values.Single()); } /// <summary> /// Tests the client binary flag. /// </summary> [Test] public void TestWithKeepBinaryClient() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject {Val = 11}; var res = (IBinaryObject) prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject) prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests the server binary flag. /// </summary> [Test] public void TestWithKeepBinaryServer() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (BinarizableObject) prx.Method(obj); Assert.AreEqual(11, res.Val); res = (BinarizableObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Val); } /// <summary> /// Tests server and client binary flag. /// </summary> [Test] public void TestWithKeepBinaryBoth() { var svc = new TestIgniteServiceBinarizable(); // Deploy to grid2 Grid1.GetCluster().ForNodeIds(Grid2.GetCluster().GetLocalNode().Id).GetServices().WithKeepBinary().WithServerKeepBinary() .DeployNodeSingleton(SvcName, svc); // Get proxy var prx = Services.WithKeepBinary().WithServerKeepBinary().GetServiceProxy<ITestIgniteService>(SvcName); var obj = new BinarizableObject { Val = 11 }; var res = (IBinaryObject)prx.Method(obj); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); res = (IBinaryObject)prx.Method(Grid1.GetBinary().ToBinary<IBinaryObject>(obj)); Assert.AreEqual(11, res.Deserialize<BinarizableObject>().Val); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestDeployMultipleException([Values(true, false)] bool keepBinary) { VerifyDeploymentException((services, svc) => services.DeployMultiple(SvcName, svc, Grids.Length, 1), keepBinary); } /// <summary> /// Tests exception in Initialize. /// </summary> [Test] public void TestDeployException([Values(true, false)] bool keepBinary) { VerifyDeploymentException((services, svc) => services.Deploy(new ServiceConfiguration { Name = SvcName, Service = svc, TotalCount = Grids.Length, MaxPerNodeCount = 1 }), keepBinary); } /// <summary> /// Tests ServiceDeploymentException result via DeployAll() method. /// </summary> [Test] public void TestDeployAllException([Values(true, false)] bool binarizable) { const int num = 10; const int firstFailedIdx = 1; const int secondFailedIdx = 9; var cfgs = new List<ServiceConfiguration>(); for (var i = 0; i < num; i++) { var throwInit = (i == firstFailedIdx || i == secondFailedIdx); cfgs.Add(new ServiceConfiguration { Name = MakeServiceName(i), MaxPerNodeCount = 2, TotalCount = 2, NodeFilter = new NodeFilter { NodeId = Grid1.GetCluster().GetLocalNode().Id }, Service = binarizable ? new TestIgniteServiceBinarizable { TestProperty = i, ThrowInit = throwInit } : new TestIgniteServiceSerializable { TestProperty = i, ThrowInit = throwInit } }); } var deploymentException = Assert.Throws<ServiceDeploymentException>(() => Services.DeployAll(cfgs)); var failedCfgs = deploymentException.FailedConfigurations; Assert.IsNotNull(failedCfgs); Assert.AreEqual(2, failedCfgs.Count); var firstFailedSvc = binarizable ? failedCfgs.ElementAt(0).Service as TestIgniteServiceBinarizable : failedCfgs.ElementAt(0).Service as TestIgniteServiceSerializable; var secondFailedSvc = binarizable ? failedCfgs.ElementAt(1).Service as TestIgniteServiceBinarizable : failedCfgs.ElementAt(1).Service as TestIgniteServiceSerializable; Assert.IsNotNull(firstFailedSvc); Assert.IsNotNull(secondFailedSvc); int[] properties = { firstFailedSvc.TestProperty, secondFailedSvc.TestProperty }; Assert.IsTrue(properties.Contains(firstFailedIdx)); Assert.IsTrue(properties.Contains(secondFailedIdx)); for (var i = 0; i < num; i++) { if (i != firstFailedIdx && i != secondFailedIdx) { CheckServiceStarted(Grid1, 2, MakeServiceName(i)); } } } /// <summary> /// Tests input errors for DeployAll() method. /// </summary> [Test] public void TestDeployAllInputErrors() { var nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(null)); Assert.IsTrue(nullException.Message.Contains("configurations")); var argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration>())); Assert.IsTrue(argException.Message.Contains("empty collection")); nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(new List<ServiceConfiguration> { null })); Assert.IsTrue(nullException.Message.Contains("configurations[0]")); nullException = Assert.Throws<ArgumentNullException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Name = SvcName } })); Assert.IsTrue(nullException.Message.Contains("configurations[0].Service")); argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Service = new TestIgniteServiceSerializable() } })); Assert.IsTrue(argException.Message.Contains("configurations[0].Name")); argException = Assert.Throws<ArgumentException>(() => Services.DeployAll(new List<ServiceConfiguration> { new ServiceConfiguration { Service = new TestIgniteServiceSerializable(), Name = string.Empty } })); Assert.IsTrue(argException.Message.Contains("configurations[0].Name")); } /// <summary> /// Tests [Serializable] usage of ServiceDeploymentException. /// </summary> [Test] public void TestDeploymentExceptionSerializable() { var cfg = new ServiceConfiguration { Name = "foo", CacheName = "cacheName", AffinityKey = 1, MaxPerNodeCount = 2, Service = new TestIgniteServiceSerializable(), NodeFilter = new NodeFilter(), TotalCount = 3 }; var ex = new ServiceDeploymentException("msg", new Exception("in"), new[] {cfg}); var formatter = new BinaryFormatter(); var stream = new MemoryStream(); formatter.Serialize(stream, ex); stream.Seek(0, SeekOrigin.Begin); var res = (ServiceDeploymentException) formatter.Deserialize(stream); Assert.AreEqual(ex.Message, res.Message); Assert.IsNotNull(res.InnerException); Assert.AreEqual("in", res.InnerException.Message); var resCfg = res.FailedConfigurations.Single(); Assert.AreEqual(cfg.Name, resCfg.Name); Assert.AreEqual(cfg.CacheName, resCfg.CacheName); Assert.AreEqual(cfg.AffinityKey, resCfg.AffinityKey); Assert.AreEqual(cfg.MaxPerNodeCount, resCfg.MaxPerNodeCount); Assert.AreEqual(cfg.TotalCount, resCfg.TotalCount); Assert.IsInstanceOf<TestIgniteServiceSerializable>(cfg.Service); Assert.IsInstanceOf<NodeFilter>(cfg.NodeFilter); } /// <summary> /// Verifies the deployment exception. /// </summary> private void VerifyDeploymentException(Action<IServices, IService> deploy, bool keepBinary) { var svc = new TestIgniteServiceSerializable { ThrowInit = true }; var services = Services; if (keepBinary) { services = services.WithKeepBinary(); } var deploymentException = Assert.Throws<ServiceDeploymentException>(() => deploy(services, svc)); var text = keepBinary ? "Service deployment failed with a binary error. Examine BinaryCause for details." : "Service deployment failed with an exception. Examine InnerException for details."; Assert.AreEqual(text, deploymentException.Message); Exception ex; if (keepBinary) { Assert.IsNull(deploymentException.InnerException); ex = deploymentException.BinaryCause.Deserialize<Exception>(); } else { Assert.IsNull(deploymentException.BinaryCause); ex = deploymentException.InnerException; } Assert.IsNotNull(ex); Assert.AreEqual("Expected exception", ex.Message); Assert.IsTrue(ex.StackTrace.Trim().StartsWith( "at Apache.Ignite.Core.Tests.Services.ServicesTest.TestIgniteServiceSerializable.Init")); var failedCfgs = deploymentException.FailedConfigurations; Assert.IsNotNull(failedCfgs); Assert.AreEqual(1, failedCfgs.Count); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in Execute. /// </summary> [Test] public void TestExecuteException() { var svc = new TestIgniteServiceSerializable { ThrowExecute = true }; Services.DeployMultiple(SvcName, svc, Grids.Length, 1); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); // Execution failed, but service exists. Assert.IsNotNull(svc0); Assert.IsFalse(svc0.Executed); } /// <summary> /// Tests exception in Cancel. /// </summary> [Test] public void TestCancelException() { var svc = new TestIgniteServiceSerializable { ThrowCancel = true }; Services.DeployMultiple(SvcName, svc, 2, 1); CheckServiceStarted(Grid1); Services.CancelAll(); // Cancellation failed, but service is removed. AssertNoService(); } /// <summary> /// Tests exception in binarizable implementation. /// </summary> [Test] public void TestMarshalExceptionOnRead() { var svc = new TestIgniteServiceBinarizableErr(); var ex = Assert.Throws<ServiceDeploymentException>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.IsNotNull(ex.InnerException); Assert.AreEqual("Expected exception", ex.InnerException.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests exception in binarizable implementation. /// </summary> [Test] public void TestMarshalExceptionOnWrite() { var svc = new TestIgniteServiceBinarizableErr {ThrowOnWrite = true}; var ex = Assert.Throws<Exception>(() => Services.DeployMultiple(SvcName, svc, Grids.Length, 1)); Assert.AreEqual("Expected exception", ex.Message); var svc0 = Services.GetService<TestIgniteServiceSerializable>(SvcName); Assert.IsNull(svc0); } /// <summary> /// Tests Java service invocation. /// </summary> [Test] public void TestCallJavaService() { // Deploy Java service var javaSvcName = TestUtils.DeployJavaService(Grid1); // Verify descriptor var descriptor = Services.GetServiceDescriptors().Single(x => x.Name == javaSvcName); Assert.AreEqual(javaSvcName, descriptor.Name); var svc = Services.GetServiceProxy<IJavaService>(javaSvcName, false); var binSvc = Services.WithKeepBinary().WithServerKeepBinary() .GetServiceProxy<IJavaService>(javaSvcName, false); // Basics Assert.IsTrue(svc.isInitialized()); Assert.IsTrue(TestUtils.WaitForCondition(() => svc.isExecuted(), 500)); Assert.IsFalse(svc.isCancelled()); // Primitives Assert.AreEqual(4, svc.test((byte) 3)); Assert.AreEqual(5, svc.test((short) 4)); Assert.AreEqual(6, svc.test(5)); Assert.AreEqual(6, svc.test((long) 5)); Assert.AreEqual(3.8f, svc.test(2.3f)); Assert.AreEqual(5.8, svc.test(3.3)); Assert.IsFalse(svc.test(true)); Assert.AreEqual('b', svc.test('a')); Assert.AreEqual("Foo!", svc.test("Foo")); // Nullables (Java wrapper types) Assert.AreEqual(4, svc.testWrapper(3)); Assert.AreEqual(5, svc.testWrapper((short?) 4)); Assert.AreEqual(6, svc.testWrapper((int?)5)); Assert.AreEqual(6, svc.testWrapper((long?) 5)); Assert.AreEqual(3.8f, svc.testWrapper(2.3f)); Assert.AreEqual(5.8, svc.testWrapper(3.3)); Assert.AreEqual(false, svc.testWrapper(true)); Assert.AreEqual('b', svc.testWrapper('a')); // Arrays Assert.AreEqual(new byte[] {2, 3, 4}, svc.testArray(new byte[] {1, 2, 3})); Assert.AreEqual(new short[] {2, 3, 4}, svc.testArray(new short[] {1, 2, 3})); Assert.AreEqual(new[] {2, 3, 4}, svc.testArray(new[] {1, 2, 3})); Assert.AreEqual(new long[] {2, 3, 4}, svc.testArray(new long[] {1, 2, 3})); Assert.AreEqual(new float[] {2, 3, 4}, svc.testArray(new float[] {1, 2, 3})); Assert.AreEqual(new double[] {2, 3, 4}, svc.testArray(new double[] {1, 2, 3})); Assert.AreEqual(new[] {"a1", "b1"}, svc.testArray(new [] {"a", "b"})); Assert.AreEqual(new[] {'c', 'd'}, svc.testArray(new[] {'b', 'c'})); Assert.AreEqual(new[] {false, true, false}, svc.testArray(new[] {true, false, true})); // Nulls Assert.AreEqual(9, svc.testNull(8)); Assert.IsNull(svc.testNull(null)); // params / varargs Assert.AreEqual(5, svc.testParams(1, 2, 3, 4, "5")); Assert.AreEqual(0, svc.testParams()); // Overloads Assert.AreEqual(3, svc.test(2, "1")); Assert.AreEqual(3, svc.test("1", 2)); // Binary Assert.AreEqual(7, svc.testBinarizable(new PlatformComputeBinarizable {Field = 6}).Field); // Binary collections var arr = new[] {10, 11, 12}.Select( x => new PlatformComputeBinarizable {Field = x}).ToArray(); var arrOfObj = arr.ToArray<object>(); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableCollection(arr) .OfType<PlatformComputeBinarizable>().Select(x => x.Field)); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableArrayOfObjects(arrOfObj) .OfType<PlatformComputeBinarizable>().Select(x => x.Field)); Assert.IsNull(svc.testBinarizableArrayOfObjects(null)); Assert.AreEqual(new[] {11, 12, 13}, svc.testBinarizableArray(arr) .Select(x => x.Field)); Assert.IsNull(svc.testBinarizableArray(null)); // Binary object Assert.AreEqual(15, binSvc.testBinaryObject( Grid1.GetBinary().ToBinary<IBinaryObject>(new PlatformComputeBinarizable {Field = 6})) .GetField<int>("Field")); DateTime dt = new DateTime(1992, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); Assert.AreEqual(dt, svc.test(dt)); Assert.AreEqual(dt, svc.testNullTimestamp(dt)); Assert.IsNull(svc.testNullTimestamp(null)); Assert.AreEqual(dt, svc.testArray(new DateTime?[] {dt})[0]); Guid guid = Guid.NewGuid(); Assert.AreEqual(guid, svc.test(guid)); Assert.AreEqual(guid, svc.testNullUUID(guid)); Assert.IsNull(svc.testNullUUID(null)); Assert.AreEqual(guid, svc.testArray(new Guid?[] {guid})[0]); // Binary object array. var binArr = arr.Select(Grid1.GetBinary().ToBinary<IBinaryObject>).ToArray(); Assert.AreEqual(new[] {11, 12, 13}, binSvc.testBinaryObjectArray(binArr) .Select(x => x.GetField<int>("Field"))); Services.Cancel(javaSvcName); } /// <summary> /// Tests Java service invocation with dynamic proxy. /// </summary> [Test] public void TestCallJavaServiceDynamicProxy() { // Deploy Java service var javaSvcName = TestUtils.DeployJavaService(Grid1); var svc = Grid1.GetServices().GetDynamicServiceProxy(javaSvcName, true); // Basics Assert.IsTrue(svc.isInitialized()); Assert.IsTrue(TestUtils.WaitForCondition(() => svc.isExecuted(), 500)); Assert.IsFalse(svc.isCancelled()); // Primitives Assert.AreEqual(4, svc.test((byte)3)); Assert.AreEqual(5, svc.test((short)4)); Assert.AreEqual(6, svc.test(5)); Assert.AreEqual(6, svc.test((long)5)); Assert.AreEqual(3.8f, svc.test(2.3f)); Assert.AreEqual(5.8, svc.test(3.3)); Assert.IsFalse(svc.test(true)); Assert.AreEqual('b', svc.test('a')); Assert.AreEqual("Foo!", svc.test("Foo")); // Nullables (Java wrapper types) Assert.AreEqual(4, svc.testWrapper(3)); Assert.AreEqual(5, svc.testWrapper((short?)4)); Assert.AreEqual(6, svc.testWrapper((int?)5)); Assert.AreEqual(6, svc.testWrapper((long?)5)); Assert.AreEqual(3.8f, svc.testWrapper(2.3f)); Assert.AreEqual(5.8, svc.testWrapper(3.3)); Assert.AreEqual(false, svc.testWrapper(true)); Assert.AreEqual('b', svc.testWrapper('a')); // Arrays Assert.AreEqual(new byte[] { 2, 3, 4 }, svc.testArray(new byte[] { 1, 2, 3 })); Assert.AreEqual(new short[] { 2, 3, 4 }, svc.testArray(new short[] { 1, 2, 3 })); Assert.AreEqual(new[] { 2, 3, 4 }, svc.testArray(new[] { 1, 2, 3 })); Assert.AreEqual(new long[] { 2, 3, 4 }, svc.testArray(new long[] { 1, 2, 3 })); Assert.AreEqual(new float[] { 2, 3, 4 }, svc.testArray(new float[] { 1, 2, 3 })); Assert.AreEqual(new double[] { 2, 3, 4 }, svc.testArray(new double[] { 1, 2, 3 })); Assert.AreEqual(new[] { "a1", "b1" }, svc.testArray(new[] { "a", "b" })); Assert.AreEqual(new[] { 'c', 'd' }, svc.testArray(new[] { 'b', 'c' })); Assert.AreEqual(new[] { false, true, false }, svc.testArray(new[] { true, false, true })); // Nulls Assert.AreEqual(9, svc.testNull(8)); Assert.IsNull(svc.testNull(null)); // Overloads Assert.AreEqual(3, svc.test(2, "1")); Assert.AreEqual(3, svc.test("1", 2)); // Binary Assert.AreEqual(7, svc.testBinarizable(new PlatformComputeBinarizable { Field = 6 }).Field); // Binary object var binSvc = Services.WithKeepBinary().WithServerKeepBinary().GetDynamicServiceProxy(javaSvcName); Assert.AreEqual(15, binSvc.testBinaryObject( Grid1.GetBinary().ToBinary<IBinaryObject>(new PlatformComputeBinarizable { Field = 6 })) .GetField<int>("Field")); DateTime dt = new DateTime(1992, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); Assert.AreEqual(dt, svc.test(dt)); Assert.AreEqual(dt, svc.testNullTimestamp(dt)); Assert.IsNull(svc.testNullTimestamp(null)); Assert.AreEqual(dt, svc.testArray(new DateTime?[] { dt })[0]); Guid guid = Guid.NewGuid(); Assert.AreEqual(guid, svc.test(guid)); Assert.AreEqual(guid, svc.testNullUUID(guid)); Assert.IsNull(svc.testNullUUID(null)); Assert.AreEqual(guid, svc.testArray(new Guid?[] { guid })[0]); } /// <summary> /// Tests the footer setting. /// </summary> [Test] public void TestFooterSetting() { foreach (var grid in Grids) { Assert.AreEqual(CompactFooter, ((Ignite) grid).Marshaller.CompactFooter); Assert.AreEqual(CompactFooter, grid.GetConfiguration().BinaryConfiguration.CompactFooter); } } /// <summary> /// Starts the grids. /// </summary> private void StartGrids() { if (Grid1 != null) return; var path = Path.Combine("Config", "Compute", "compute-grid"); Grid1 = Ignition.Start(GetConfiguration(path + "1.xml")); Grid2 = Ignition.Start(GetConfiguration(path + "2.xml")); Grid3 = Ignition.Start(GetConfiguration(path + "3.xml")); Grids = new[] { Grid1, Grid2, Grid3 }; } /// <summary> /// Stops the grids. /// </summary> private void StopGrids() { Grid1 = Grid2 = Grid3 = null; Grids = null; Ignition.StopAll(true); } /// <summary> /// Checks that service has started on specified grid. /// </summary> private static void CheckServiceStarted(IIgnite grid, int count = 1, string svcName = SvcName) { Func<ICollection<TestIgniteServiceSerializable>> getServices = () => grid.GetServices().GetServices<TestIgniteServiceSerializable>(svcName); Assert.IsTrue(TestUtils.WaitForCondition(() => count == getServices().Count, 5000)); var svc = getServices().First(); Assert.IsNotNull(svc); Assert.IsTrue(svc.Initialized); Thread.Sleep(100); // Service runs in a separate thread, wait for it to execute. Assert.IsTrue(svc.Executed); Assert.IsFalse(svc.Cancelled); Assert.AreEqual(grid.GetCluster().GetLocalNode().Id, svc.NodeId); } /// <summary> /// Gets the Ignite configuration. /// </summary> private IgniteConfiguration GetConfiguration(string springConfigUrl) { if (!CompactFooter) { springConfigUrl = Compute.ComputeApiTestFullFooter.ReplaceFooterSetting(springConfigUrl); } return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { SpringConfigUrl = springConfigUrl, BinaryConfiguration = new BinaryConfiguration( typeof (TestIgniteServiceBinarizable), typeof (TestIgniteServiceBinarizableErr), typeof (PlatformComputeBinarizable), typeof (BinarizableObject)) { NameMapper = BinaryBasicNameMapper.SimpleNameInstance } }; } /// <summary> /// Asserts that there is no service on any grid with given name. /// </summary> /// <param name="name">The name.</param> private void AssertNoService(string name = SvcName) { foreach (var grid in Grids) Assert.IsTrue( // ReSharper disable once AccessToForEachVariableInClosure TestUtils.WaitForCondition(() => grid.GetServices() .GetService<ITestIgniteService>(name) == null, 5000)); } /// <summary> /// Gets the services. /// </summary> protected virtual IServices Services { get { return Grid1.GetServices(); } } /// <summary> /// Gets a value indicating whether compact footers should be used. /// </summary> protected virtual bool CompactFooter { get { return true; } } /// <summary> /// Makes Service1-{i} names for services. /// </summary> private static string MakeServiceName(int i) { // Please note that CheckContext() validates Name.StartsWith(SvcName). return string.Format("{0}-{1}", SvcName, i); } /// <summary> /// Test base service. /// </summary> public interface ITestIgniteServiceBase { /** */ int TestProperty { get; set; } /** */ object Method(object arg); } /// <summary> /// Test serializable service with a methods having an array of user types and objects. /// </summary> public interface ITestIgniteServiceArray { /** */ object[] TestBinarizableArrayOfObjects(object[] x); /** */ PlatformComputeBinarizable[] TestBinarizableArray(PlatformComputeBinarizable[] x); /** */ IBinaryObject[] TestBinaryObjectArray(IBinaryObject[] x); /** Class TestBinarizableArray2 has no an equals class in Java. */ PlatformComputeBinarizable2[] TestBinarizableArray2(PlatformComputeBinarizable2[] x); } /// <summary> /// Test serializable service with a methods having an array of user types and objects. /// </summary> [Serializable] private class TestIgniteServiceArraySerializable : TestIgniteServiceSerializable, ITestIgniteServiceArray { /** */ public object[] TestBinarizableArrayOfObjects(object[] arg) { if (arg == null) return null; for (var i = 0; i < arg.Length; i++) if (arg[i] != null) if (arg[i].GetType() == typeof(PlatformComputeBinarizable)) arg[i] = new PlatformComputeBinarizable() {Field = ((PlatformComputeBinarizable) arg[i]).Field + 1}; else arg[i] = new PlatformComputeBinarizable2() {Field = ((PlatformComputeBinarizable2) arg[i]).Field + 1}; return arg; } /** */ public PlatformComputeBinarizable[] TestBinarizableArray(PlatformComputeBinarizable[] arg) { // ReSharper disable once CoVariantArrayConversion return (PlatformComputeBinarizable[])TestBinarizableArrayOfObjects(arg); } /** */ public IBinaryObject[] TestBinaryObjectArray(IBinaryObject[] x) { for (var i = 0; i < x.Length; i++) { var binaryObject = x[i]; var fieldVal = binaryObject.GetField<int>("Field"); x[i] = binaryObject.ToBuilder().SetField("Field", fieldVal + 1).Build(); } return x; } /** */ public PlatformComputeBinarizable2[] TestBinarizableArray2(PlatformComputeBinarizable2[] arg) { // ReSharper disable once CoVariantArrayConversion return (PlatformComputeBinarizable2[])TestBinarizableArrayOfObjects(arg); } } /// <summary> /// Test service interface for proxying. /// </summary> public interface ITestIgniteService : IService, ITestIgniteServiceBase { /** */ bool Initialized { get; } /** */ bool Cancelled { get; } /** */ bool Executed { get; } /** */ Guid NodeId { get; } /** */ string LastCallContextName { get; } /** */ object ErrMethod(object arg); } /// <summary> /// Test service interface for proxy usage. /// Has some of the original interface members with different signatures. /// </summary> public interface ITestIgniteServiceProxyInterface { /** */ Guid NodeId { get; } /** */ object TestProperty { get; set; } /** */ int Method(int arg); } #pragma warning disable 649 /// <summary> /// Test serializable service. /// </summary> [Serializable] private class TestIgniteServiceSerializable : ITestIgniteService { /** */ [InstanceResource] // ReSharper disable once UnassignedField.Local private IIgnite _grid; /** <inheritdoc /> */ public int TestProperty { get; set; } /** <inheritdoc /> */ public bool Initialized { get; private set; } /** <inheritdoc /> */ public bool Cancelled { get; private set; } /** <inheritdoc /> */ public bool Executed { get; private set; } /** <inheritdoc /> */ public Guid NodeId { // ReSharper disable once InconsistentlySynchronizedField get { return _grid.GetCluster().GetLocalNode().Id; } } /** <inheritdoc /> */ public string LastCallContextName { get; private set; } /** */ public bool ThrowInit { get; set; } /** */ public bool ThrowExecute { get; set; } /** */ public bool ThrowCancel { get; set; } /** */ public object Method(object arg) { return arg; } /** */ public object ErrMethod(object arg) { throw new ArgumentNullException("arg", "ExpectedException"); } /** <inheritdoc /> */ public void Init(IServiceContext context) { lock (this) { if (ThrowInit) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Initialized = true; } } /** <inheritdoc /> */ public void Execute(IServiceContext context) { lock (this) { if (ThrowExecute) throw new Exception("Expected exception"); CheckContext(context); Assert.IsFalse(context.IsCancelled); Assert.IsTrue(Initialized); Assert.IsFalse(Cancelled); Executed = true; } } /** <inheritdoc /> */ public void Cancel(IServiceContext context) { lock (this) { if (ThrowCancel) throw new Exception("Expected exception"); CheckContext(context); Assert.IsTrue(context.IsCancelled); Cancelled = true; } } /// <summary> /// Checks the service context. /// </summary> private void CheckContext(IServiceContext context) { LastCallContextName = context.Name; if (context.AffinityKey != null && !(context.AffinityKey is int)) { var binaryObj = context.AffinityKey as IBinaryObject; var key = binaryObj != null ? binaryObj.Deserialize<BinarizableObject>() : (BinarizableObject) context.AffinityKey; Assert.AreEqual(AffKey, key.Val); } Assert.IsNotNull(_grid); Assert.IsTrue(context.Name.StartsWith(SvcName)); Assert.AreNotEqual(Guid.Empty, context.ExecutionId); } } /// <summary> /// Test binary service. /// </summary> private class TestIgniteServiceBinarizable : TestIgniteServiceSerializable, IBinarizable { /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); writer.WriteBoolean("ThrowInit", ThrowInit); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { ThrowInit = reader.ReadBoolean("ThrowInit"); TestProperty = reader.ReadInt("TestProp"); } } /// <summary> /// Test binary service with exceptions in marshalling. /// </summary> private class TestIgniteServiceBinarizableErr : TestIgniteServiceSerializable, IBinarizable { /** */ public bool ThrowOnWrite { get; set; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("TestProp", TestProperty); if (ThrowOnWrite) throw new Exception("Expected exception"); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { TestProperty = reader.ReadInt("TestProp"); throw new Exception("Expected exception"); } } /// <summary> /// Test node filter. /// </summary> [Serializable] private class NodeFilter : IClusterNodeFilter { /// <summary> /// Gets or sets the node identifier. /// </summary> public Guid NodeId { get; set; } /** <inheritdoc /> */ public bool Invoke(IClusterNode node) { return node.Id == NodeId; } } /// <summary> /// Binary object. /// </summary> private class BinarizableObject { public int Val { get; set; } } /// <summary> /// Interop class. /// </summary> public class PlatformComputeBinarizable { /** */ public int Field { get; set; } } /// <summary> /// Class has no an equals class in Java. /// </summary> public class PlatformComputeBinarizable2 { /** */ public int Field { get; set; } } } }
using System; using System.Reflection; using System.IO; using Newtonsoft.Json; using NUnit.Framework; using System.Collections.Generic; namespace OpenQA.Selenium.Environment { public class EnvironmentManager { private static EnvironmentManager instance; private Type driverType; private Browser browser; private IWebDriver driver; private UrlBuilder urlBuilder; private TestWebServer webServer; private DriverFactory driverFactory; private RemoteSeleniumServer remoteServer; private string remoteCapabilities; private EnvironmentManager() { string currentDirectory = this.CurrentDirectory; string defaultConfigFile = Path.Combine(currentDirectory, "appconfig.json"); string configFile = TestContext.Parameters.Get<string>("ConfigFile", defaultConfigFile).Replace('/', Path.DirectorySeparatorChar); string content = File.ReadAllText(configFile); TestEnvironment env = JsonConvert.DeserializeObject<TestEnvironment>(content); string activeDriverConfig = TestContext.Parameters.Get("ActiveDriverConfig", env.ActiveDriverConfig); string activeWebsiteConfig = TestContext.Parameters.Get("ActiveWebsiteConfig", env.ActiveWebsiteConfig); string driverServiceLocation = TestContext.Parameters.Get("DriverServiceLocation", env.DriverServiceLocation); DriverConfig driverConfig = env.DriverConfigs[activeDriverConfig]; WebsiteConfig websiteConfig = env.WebSiteConfigs[activeWebsiteConfig]; TestWebServerConfig webServerConfig = env.TestWebServerConfig; webServerConfig.CaptureConsoleOutput = TestContext.Parameters.Get<bool>("CaptureWebServerOutput", env.TestWebServerConfig.CaptureConsoleOutput); webServerConfig.HideCommandPromptWindow = TestContext.Parameters.Get<bool>("HideWebServerCommandPrompt", env.TestWebServerConfig.HideCommandPromptWindow); webServerConfig.JavaHomeDirectory = TestContext.Parameters.Get("WebServerJavaHome", env.TestWebServerConfig.JavaHomeDirectory); this.driverFactory = new DriverFactory(driverServiceLocation); this.driverFactory.DriverStarting += OnDriverStarting; Assembly driverAssembly = null; try { driverAssembly = Assembly.Load(driverConfig.AssemblyName); } catch (FileNotFoundException) { driverAssembly = Assembly.GetExecutingAssembly(); } driverType = driverAssembly.GetType(driverConfig.DriverTypeName); browser = driverConfig.BrowserValue; remoteCapabilities = driverConfig.RemoteCapabilities; urlBuilder = new UrlBuilder(websiteConfig); // When run using the `bazel test` command, the following environment // variable will be set. If not set, we're running from a build system // outside Bazel, and need to locate the directory containing the jar. string projectRoot = System.Environment.GetEnvironmentVariable("TEST_SRCDIR"); if (string.IsNullOrEmpty(projectRoot)) { // Walk up the directory tree until we find ourselves in a directory // where the path to the Java web server can be determined. bool continueTraversal = true; DirectoryInfo info = new DirectoryInfo(currentDirectory); while (continueTraversal) { if (info == info.Root) { break; } foreach (var childDir in info.EnumerateDirectories()) { // Case 1: The current directory of this assembly is in the // same direct sub-tree as the Java targets (usually meaning // executing tests from the same build system as that which // builds the Java targets). // If we find a child directory named "java", then the web // server should be able to be found under there. if (string.Compare(childDir.Name, "java", StringComparison.OrdinalIgnoreCase) == 0) { continueTraversal = false; break; } // Case 2: The current directory of this assembly is a different // sub-tree as the Java targets (usually meaning executing tests // from a different build system as that which builds the Java // targets). // If we travel to a place in the tree where there is a child // directory named "bazel-bin", the web server should be found // in the "java" subdirectory of that directory. if (string.Compare(childDir.Name, "bazel-bin", StringComparison.OrdinalIgnoreCase) == 0) { string javaOutDirectory = Path.Combine(childDir.FullName, "java"); if (Directory.Exists(javaOutDirectory)) { info = childDir; continueTraversal = false; break; } } } if (continueTraversal) { info = info.Parent; } } projectRoot = info.FullName; } else { projectRoot += "/selenium"; } webServer = new TestWebServer(projectRoot, webServerConfig); bool autoStartRemoteServer = false; if (browser == Browser.Remote) { autoStartRemoteServer = driverConfig.AutoStartRemoteServer; } remoteServer = new RemoteSeleniumServer(projectRoot, autoStartRemoteServer); } ~EnvironmentManager() { if (remoteServer != null) { remoteServer.Stop(); } if (webServer != null) { webServer.Stop(); } if (driver != null) { driver.Quit(); } } public event EventHandler<DriverStartingEventArgs> DriverStarting; public static EnvironmentManager Instance { get { if (instance == null) { instance = new EnvironmentManager(); } return instance; } } public Browser Browser { get { return browser; } } public string DriverServiceDirectory { get { return this.driverFactory.DriverServicePath; } } public string CurrentDirectory { get { string assemblyLocation = Path.GetDirectoryName(typeof(EnvironmentManager).Assembly.Location); string testDirectory = TestContext.CurrentContext.TestDirectory; if (assemblyLocation != testDirectory) { return assemblyLocation; } return testDirectory; } } public TestWebServer WebServer { get { return webServer; } } public RemoteSeleniumServer RemoteServer { get { return remoteServer; } } public string RemoteCapabilities { get { return remoteCapabilities; } } public UrlBuilder UrlBuilder { get { return urlBuilder; } } public IWebDriver GetCurrentDriver() { if (driver != null) { return driver; } else { return CreateFreshDriver(); } } public IWebDriver CreateDriverInstance() { return driverFactory.CreateDriver(driverType); } public IWebDriver CreateDriverInstance(DriverOptions options) { return driverFactory.CreateDriverWithOptions(driverType, options); } public IWebDriver CreateFreshDriver() { CloseCurrentDriver(); driver = CreateDriverInstance(); return driver; } public void CloseCurrentDriver() { if (driver != null) { driver.Quit(); } driver = null; } protected void OnDriverStarting(object sender, DriverStartingEventArgs e) { if (this.DriverStarting != null) { this.DriverStarting(sender, e); } } } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Threading; namespace NAudio.Wave { // BIG TODO: how to report errors back from functions? /// <summary> /// Represents a wave out device /// </summary> public class WaveOutThreadSafe : IWavePlayer { private IntPtr hWaveOut; private WaveOutBuffer[] buffers; private IWaveProvider waveStream; private int numBuffers; private PlaybackState playbackState; private WaveInterop.WaveCallback callback; private int devNumber; private int desiredLatency; private float volume = 1; private bool buffersQueued; private Thread waveOutThread; private Queue<WaveOutAction> actionQueue; private AutoResetEvent workAvailable; /// <summary> /// Playback stopped /// </summary> public event EventHandler PlaybackStopped; /// <summary> /// Retrieves the capabilities of a waveOut device /// </summary> /// <param name="devNumber">Device to test</param> /// <returns>The WaveOut device capabilities</returns> public static WaveOutCapabilities GetCapabilities(int devNumber) { WaveOutCapabilities caps = new WaveOutCapabilities(); int structSize = Marshal.SizeOf(caps); MmException.Try(WaveInterop.waveOutGetDevCaps((IntPtr)devNumber, out caps, structSize), "waveOutGetDevCaps"); return caps; } /// <summary> /// Returns the number of Wave Out devices available in the system /// </summary> public static Int32 DeviceCount { get { return WaveInterop.waveOutGetNumDevs(); } } /// <summary> /// Opens a WaveOut device /// </summary> /// <param name="devNumber">This is the device number to open. /// This must be between 0 and <see>DeviceCount</see> - 1.</param> /// <param name="desiredLatency">The number of milliseconds of audio to read before /// streaming to the audio device. This will be broken into 3 buffers</param> public WaveOutThreadSafe(int devNumber, int desiredLatency) { this.devNumber = devNumber; this.desiredLatency = desiredLatency; this.callback = new WaveInterop.WaveCallback(Callback); actionQueue = new Queue<WaveOutAction>(); workAvailable = new AutoResetEvent(false); waveOutThread = new Thread(new ThreadStart(ThreadProc)); waveOutThread.Start(); } private void ThreadProc() { while(true) { workAvailable.WaitOne(); bool loop = true; while(loop) { WaveOutAction waveOutAction = null; lock(actionQueue) { if (actionQueue.Count > 0) { waveOutAction = actionQueue.Dequeue(); } } if(waveOutAction != null) { try { switch (waveOutAction.Function) { case WaveOutFunction.Init: Init((WaveStream)waveOutAction.Data); break; case WaveOutFunction.Play: Play(); break; case WaveOutFunction.Pause: Pause(); break; case WaveOutFunction.Resume: Resume(); break; case WaveOutFunction.Stop: Stop(); break; case WaveOutFunction.BufferDone: OnBufferDone((WaveOutBuffer)waveOutAction.Data); break; case WaveOutFunction.Exit: Exit(); return; case WaveOutFunction.SetVolume: SetVolume((int)waveOutAction.Data); break; } } catch (Exception e) { string s = e.ToString(); if (waveOutAction.Function == WaveOutFunction.Exit) { return; } } } else { loop = false; } } } } /// <summary> /// Initialises the WaveOut device /// </summary> /// <param name="waveProvider">Wave provider to play</param> public void Init(IWaveProvider waveProvider) { if(Thread.CurrentThread.ManagedThreadId != waveOutThread.ManagedThreadId) { lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Init,waveStream)); workAvailable.Set(); } return; } this.waveStream = waveProvider; int bufferSize = waveProvider.WaveFormat.ConvertLatencyToByteSize(desiredLatency); //waveStream.GetReadSize((desiredLatency + 2) / 3); this.numBuffers = 3; MmException.Try(WaveInterop.waveOutOpen(out hWaveOut, (IntPtr)devNumber, waveStream.WaveFormat, callback, IntPtr.Zero, WaveInterop.CallbackFunction), "waveOutOpen"); buffers = new WaveOutBuffer[numBuffers]; playbackState = PlaybackState.Stopped; object waveOutLock = new object(); for (int n = 0; n < numBuffers; n++) { buffers[n] = new WaveOutBuffer(hWaveOut, bufferSize, waveStream, waveOutLock); } } /// <summary> /// Start playing the audio from the WaveStream /// </summary> public void Play() { if (playbackState != PlaybackState.Playing) { playbackState = PlaybackState.Playing; if(Thread.CurrentThread.ManagedThreadId != waveOutThread.ManagedThreadId) { lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Play,null)); workAvailable.Set(); } return; } } if (!buffersQueued) { Pause(); // to avoid a deadlock - we don't want two waveOutWrites at once for (int n = 0; n < numBuffers; n++) { System.Diagnostics.Debug.Assert(buffers[n].InQueue == false, "Adding a buffer that was already queued on play"); buffers[n].OnDone(); } buffersQueued = true; } Resume(); } /// <summary> /// Pause the audio /// </summary> public void Pause() { if(Thread.CurrentThread.ManagedThreadId != waveOutThread.ManagedThreadId) { lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Pause,null)); workAvailable.Set(); } return; } MmResult result = WaveInterop.waveOutPause(hWaveOut); if (result != MmResult.NoError) throw new MmException(result, "waveOutPause"); playbackState = PlaybackState.Paused; } /// <summary> /// Resume playing after a pause from the same position /// </summary> public void Resume() { if(Thread.CurrentThread.ManagedThreadId != waveOutThread.ManagedThreadId) { lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Resume,null)); workAvailable.Set(); } return; } MmResult result = WaveInterop.waveOutRestart(hWaveOut); if (result != MmResult.NoError) throw new MmException(result, "waveOutRestart"); playbackState = PlaybackState.Playing; } private void Exit() { if (hWaveOut != IntPtr.Zero) { Stop(); WaveInterop.waveOutClose(hWaveOut); hWaveOut = IntPtr.Zero; } if (buffers != null) { for (int n = 0; n < numBuffers; n++) { buffers[n].Dispose(); } buffers = null; } } /// <summary> /// Stop and reset the WaveOut device /// </summary> public void Stop() { if(Thread.CurrentThread.ManagedThreadId != waveOutThread.ManagedThreadId) { lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Stop,null)); workAvailable.Set(); } return; } playbackState = PlaybackState.Stopped; buffersQueued = false; MmResult result = WaveInterop.waveOutReset(hWaveOut); if (result != MmResult.NoError) throw new MmException(result, "waveOutReset"); } /// <summary> /// Playback State /// </summary> public PlaybackState PlaybackState { get { return playbackState; } } /// <summary> /// Volume for this device 1.0 is full scale /// </summary> public float Volume { get { return volume; } set { volume = value; float left = volume; float right = volume; int stereoVolume = (int)(left * 0xFFFF) + ((int)(right * 0xFFFF) << 16); lock (actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.SetVolume, stereoVolume)); workAvailable.Set(); } } } private void SetVolume(int stereoVolume) { MmException.Try(WaveInterop.waveOutSetVolume(hWaveOut, stereoVolume), "waveOutSetVolume"); } #region Dispose Pattern /// <summary> /// Closes this WaveOut device /// </summary> public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } /// <summary> /// Closes the WaveOut device and disposes of buffers /// </summary> /// <param name="disposing">True if called from <see>Dispose</see></param> protected void Dispose(bool disposing) { lock (actionQueue) { actionQueue.Clear(); actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.Exit,null)); workAvailable.Set(); } waveOutThread.Join(); } /// <summary> /// Finalizer. Only called when user forgets to call <see>Dispose</see> /// </summary> ~WaveOutThreadSafe() { System.Diagnostics.Debug.Assert(false, "WaveOut device was not closed"); Dispose(false); } #endregion // made non-static so that playing can be stopped here private void Callback(IntPtr hWaveOut, WaveInterop.WaveMessage uMsg, IntPtr dwUser, WaveHeader wavhdr, IntPtr dwReserved) { if (uMsg == WaveInterop.WaveMessage.WaveOutDone) { // check that we're not here through pressing stop GCHandle hBuffer = (GCHandle)wavhdr.userData; WaveOutBuffer buffer = (WaveOutBuffer)hBuffer.Target; lock(actionQueue) { actionQueue.Enqueue(new WaveOutAction(WaveOutFunction.BufferDone,buffer)); workAvailable.Set(); } // n.b. this was wrapped in an exception handler, but bug should be fixed now } } private void OnBufferDone(WaveOutBuffer buffer) { if (playbackState == PlaybackState.Playing) { if (!buffer.OnDone()) { playbackState = PlaybackState.Stopped; RaisePlaybackStopped(); } } } private void RaisePlaybackStopped() { if (PlaybackStopped != null) { PlaybackStopped(this, EventArgs.Empty); } } } class WaveOutAction { private WaveOutFunction function; private object data; public WaveOutAction(WaveOutFunction function, object data) { this.function = function; this.data = data; } public WaveOutFunction Function { get { return function; } } public object Data { get { return data; } } } enum WaveOutFunction { Init, Stop, BufferDone, Pause, Play, Resume, SetVolume, Exit } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Logging.V2.Tests { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Logging.V2; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Moq; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; using Xunit; /// <summary>Generated unit tests</summary> public class GeneratedMetricsServiceV2ClientTest { [Fact] public void GetLogMetric() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); GetLogMetricRequest expectedRequest = new GetLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.GetLogMetric(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); LogMetric response = client.GetLogMetric(metricName); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetLogMetricAsync() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); GetLogMetricRequest expectedRequest = new GetLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.GetLogMetricAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); LogMetric response = await client.GetLogMetricAsync(metricName); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void GetLogMetric2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); GetLogMetricRequest request = new GetLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.GetLogMetric(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = client.GetLogMetric(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task GetLogMetricAsync2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); GetLogMetricRequest request = new GetLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.GetLogMetricAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = await client.GetLogMetricAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateLogMetric() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); CreateLogMetricRequest expectedRequest = new CreateLogMetricRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.CreateLogMetric(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogMetric metric = new LogMetric(); LogMetric response = client.CreateLogMetric(parent, metric); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateLogMetricAsync() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); CreateLogMetricRequest expectedRequest = new CreateLogMetricRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.CreateLogMetricAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); ParentNameOneof parent = ParentNameOneof.From(new ProjectName("[PROJECT]")); LogMetric metric = new LogMetric(); LogMetric response = await client.CreateLogMetricAsync(parent, metric); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void CreateLogMetric2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); CreateLogMetricRequest request = new CreateLogMetricRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.CreateLogMetric(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = client.CreateLogMetric(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task CreateLogMetricAsync2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); CreateLogMetricRequest request = new CreateLogMetricRequest { ParentAsParentNameOneof = ParentNameOneof.From(new ProjectName("[PROJECT]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.CreateLogMetricAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = await client.CreateLogMetricAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateLogMetric() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); UpdateLogMetricRequest expectedRequest = new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.UpdateLogMetric(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); LogMetric metric = new LogMetric(); LogMetric response = client.UpdateLogMetric(metricName, metric); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateLogMetricAsync() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); UpdateLogMetricRequest expectedRequest = new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.UpdateLogMetricAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); LogMetric metric = new LogMetric(); LogMetric response = await client.UpdateLogMetricAsync(metricName, metric); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void UpdateLogMetric2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); UpdateLogMetricRequest request = new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.UpdateLogMetric(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = client.UpdateLogMetric(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public async Task UpdateLogMetricAsync2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); UpdateLogMetricRequest request = new UpdateLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Metric = new LogMetric(), }; LogMetric expectedResponse = new LogMetric { MetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), Description = "description-1724546052", Filter = "filter-1274492040", ValueExtractor = "valueExtractor2047672534", }; mockGrpcClient.Setup(x => x.UpdateLogMetricAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<LogMetric>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); LogMetric response = await client.UpdateLogMetricAsync(request); Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteLogMetric() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); DeleteLogMetricRequest expectedRequest = new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLogMetric(expectedRequest, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); client.DeleteLogMetric(metricName); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteLogMetricAsync() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); DeleteLogMetricRequest expectedRequest = new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLogMetricAsync(expectedRequest, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); MetricNameOneof metricName = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")); await client.DeleteLogMetricAsync(metricName); mockGrpcClient.VerifyAll(); } [Fact] public void DeleteLogMetric2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); DeleteLogMetricRequest request = new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLogMetric(request, It.IsAny<CallOptions>())) .Returns(expectedResponse); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); client.DeleteLogMetric(request); mockGrpcClient.VerifyAll(); } [Fact] public async Task DeleteLogMetricAsync2() { Mock<MetricsServiceV2.MetricsServiceV2Client> mockGrpcClient = new Mock<MetricsServiceV2.MetricsServiceV2Client>(MockBehavior.Strict); DeleteLogMetricRequest request = new DeleteLogMetricRequest { MetricNameAsMetricNameOneof = MetricNameOneof.From(new MetricName("[PROJECT]", "[METRIC]")), }; Empty expectedResponse = new Empty(); mockGrpcClient.Setup(x => x.DeleteLogMetricAsync(request, It.IsAny<CallOptions>())) .Returns(new Grpc.Core.AsyncUnaryCall<Empty>(Task.FromResult(expectedResponse), null, null, null, null)); MetricsServiceV2Client client = new MetricsServiceV2ClientImpl(mockGrpcClient.Object, null); await client.DeleteLogMetricAsync(request); mockGrpcClient.VerifyAll(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using IndexInput = Lucene.Net.Store.IndexInput; namespace Lucene.Net.Index { public sealed class SegmentTermEnum : TermEnum, System.ICloneable { private IndexInput input; internal FieldInfos fieldInfos; internal long size; internal long position = - 1; private TermBuffer termBuffer = new TermBuffer(); private TermBuffer prevBuffer = new TermBuffer(); private TermBuffer scanBuffer = new TermBuffer(); private TermInfo termInfo = new TermInfo(); private int format; private bool isIndex = false; internal long indexPointer = 0; internal int indexInterval; internal int skipInterval; internal int maxSkipLevels; private int formatM1SkipInterval; internal SegmentTermEnum(IndexInput i, FieldInfos fis, bool isi) { input = i; fieldInfos = fis; isIndex = isi; maxSkipLevels = 1; // use single-level skip lists for formats > -3 int firstInt = input.ReadInt(); if (firstInt >= 0) { // original-format file, without explicit format version number format = 0; size = firstInt; // back-compatible settings indexInterval = 128; skipInterval = System.Int32.MaxValue; // switch off skipTo optimization } else { // we have a format version number format = firstInt; // check that it is a format we can understand if (format < TermInfosWriter.FORMAT_CURRENT) throw new CorruptIndexException("Unknown format version:" + format + " expected " + TermInfosWriter.FORMAT_CURRENT + " or higher"); size = input.ReadLong(); // read the size if (format == - 1) { if (!isIndex) { indexInterval = input.ReadInt(); formatM1SkipInterval = input.ReadInt(); } // switch off skipTo optimization for file format prior to 1.4rc2 in order to avoid a bug in // skipTo implementation of these versions skipInterval = System.Int32.MaxValue; } else { indexInterval = input.ReadInt(); skipInterval = input.ReadInt(); if (format <= TermInfosWriter.FORMAT) { // this new format introduces multi-level skipping maxSkipLevels = input.ReadInt(); } } } if (format > TermInfosWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) { termBuffer.SetPreUTF8Strings(); scanBuffer.SetPreUTF8Strings(); prevBuffer.SetPreUTF8Strings(); } } public object Clone() { SegmentTermEnum clone = null; try { clone = (SegmentTermEnum) base.MemberwiseClone(); } catch (System.Exception) { } clone.input = (IndexInput) input.Clone(); clone.termInfo = new TermInfo(termInfo); clone.termBuffer = (TermBuffer) termBuffer.Clone(); clone.prevBuffer = (TermBuffer)prevBuffer.Clone(); clone.scanBuffer = new TermBuffer(); return clone; } internal void Seek(long pointer, int p, Term t, TermInfo ti) { input.Seek(pointer); position = p; termBuffer.Set(t); prevBuffer.Reset(); termInfo.Set(ti); } /// <summary>Increments the enumeration to the next element. True if one exists.</summary> public override bool Next() { if (position++ >= size - 1) { prevBuffer.Set(termBuffer); termBuffer.Reset(); return false; } prevBuffer.Set(termBuffer); termBuffer.Read(input, fieldInfos); termInfo.docFreq = input.ReadVInt(); // read doc freq termInfo.freqPointer += input.ReadVLong(); // read freq pointer termInfo.proxPointer += input.ReadVLong(); // read prox pointer if (format == - 1) { // just read skipOffset in order to increment file pointer; // value is never used since skipTo is switched off if (!isIndex) { if (termInfo.docFreq > formatM1SkipInterval) { termInfo.skipOffset = input.ReadVInt(); } } } else { if (termInfo.docFreq >= skipInterval) termInfo.skipOffset = input.ReadVInt(); } if (isIndex) indexPointer += input.ReadVLong(); // read index pointer return true; } /// <summary>Optimized scan, without allocating new terms. Return numver of invocations to Next(). </summary> internal int ScanTo(Term term) { scanBuffer.Set(term); int count = 0; while (scanBuffer.CompareTo(termBuffer) > 0 && Next()) { count++; } return count; } /// <summary>Returns the current Term in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> public override Term Term() { return termBuffer.ToTerm(); } /// <summary>Returns the previous Term enumerated. Initially null.</summary> public /*internal*/ Term Prev() { return prevBuffer.ToTerm(); } /// <summary>Returns the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> internal TermInfo TermInfo() { return new TermInfo(termInfo); } /// <summary>Sets the argument to the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> internal void TermInfo(TermInfo ti) { ti.Set(termInfo); } /// <summary>Returns the docFreq from the current TermInfo in the enumeration. /// Initially invalid, valid after next() called for the first time. /// </summary> public override int DocFreq() { return termInfo.docFreq; } /* Returns the freqPointer from the current TermInfo in the enumeration. Initially invalid, valid after next() called for the first time.*/ internal long FreqPointer() { return termInfo.freqPointer; } /* Returns the proxPointer from the current TermInfo in the enumeration. Initially invalid, valid after next() called for the first time.*/ internal long ProxPointer() { return termInfo.proxPointer; } /// <summary>Closes the enumeration to further activity, freeing resources. </summary> public override void Close() { input.Close(); } } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Burrows.Configuration; using Burrows.Endpoints; namespace Burrows { using System; using System.Collections.Generic; using System.Diagnostics; using Context; using Diagnostics.Introspection; using Events; using Exceptions; using Logging; using Magnum; using Magnum.Extensions; using Magnum.Reflection; using Monitoring; using Pipeline; using Pipeline.Configuration; using Pipeline.Inspectors; using Stact; using Threading; using Util; /// <summary> /// A service bus is used to attach message handlers (services) to endpoints, as well as /// communicate with other service bus instances in a distributed application /// </summary> [DebuggerDisplay("{DebugDisplay}")] public class ServiceBus : IControlBus { private static readonly ILog _log; IConsumerPool _consumerPool; int _consumerThreadLimit = Environment.ProcessorCount*4; ServiceBusInstancePerformanceCounters _counters; volatile bool _disposed; UntypedChannel _eventChannel; ChannelConnection _performanceCounterConnection; int _receiveThreadLimit = 1; TimeSpan _receiveTimeout = 3.Seconds(); IServiceContainer _serviceContainer; volatile bool _started; static ServiceBus() { try { _log = Logger.Get(typeof(ServiceBus)); } catch (Exception ex) { throw new ConfigurationException("log4net isn't referenced", ex); } } /// <summary> /// Creates an instance of the ServiceBus, which implements IServiceBus. This is normally /// not called and should be created using the ServiceBusConfigurator to ensure proper defaults /// and operation. /// </summary> public ServiceBus(IEndpoint endpointToListenOn, IEndpointCache endpointCache, bool enablePerformanceCounters) { ReceiveTimeout = TimeSpan.FromSeconds(3); Guard.AgainstNull(endpointToListenOn, "endpointToListenOn", "This parameter cannot be null"); Guard.AgainstNull(endpointCache, "endpointFactory", "This parameter cannot be null"); Endpoint = endpointToListenOn; EndpointCache = endpointCache; _eventChannel = new ChannelAdapter(); _serviceContainer = new ServiceContainer(this); OutboundPipeline = new OutboundPipelineConfigurator(this).Pipeline; InboundPipeline = InboundPipelineConfigurator.CreateDefault(this); ControlBus = this; if(enablePerformanceCounters) InitializePerformanceCounters(); } public int ConcurrentReceiveThreads { get { return _receiveThreadLimit; } set { if (_started) throw new ConfigurationException( "The receive thread limit cannot be changed once the bus is in motion. Beep! Beep!"); _receiveThreadLimit = value; } } public int MaximumConsumerThreads { get { return _consumerThreadLimit; } set { if (_started) throw new ConfigurationException( "The consumer thread limit cannot be changed once the bus is in motion. Beep! Beep!"); _consumerThreadLimit = value; } } public TimeSpan ReceiveTimeout { get { return _receiveTimeout; } set { if (_started) throw new ConfigurationException( "The receive timeout cannot be changed once the bus is in motion. Beep! Beep!"); _receiveTimeout = value; } } public TimeSpan ShutdownTimeout { get; set; } public UntypedChannel EventChannel { get { return _eventChannel; } } [UsedImplicitly] protected string DebugDisplay { get { return string.Format("{0}: ", Endpoint.Address); } } public IEndpointCache EndpointCache { get; private set; } public void Dispose() { Dispose(true); } public void Publish<T>(T message) where T : class { Publish(message, NoContext); } /// <summary> /// Publishes a message to all subscribed consumers for the message type /// </summary> /// <typeparam name="T">The type of the message</typeparam> /// <param name="message">The messages to be published</param> /// <param name="contextCallback">The callback to perform operations on the context</param> public void Publish<T>(T message, Action<IPublishContext<T>> contextCallback) where T : class { PublishContext<T> context = ContextStorage.CreatePublishContext(message); context.SetSourceAddress(Endpoint.Address.Uri); contextCallback(context); IList<Exception> exceptions = new List<Exception>(); int publishedCount = 0; foreach (var consumer in OutboundPipeline.Enumerate(context)) { try { consumer(context); publishedCount++; } catch (Exception ex) { _log.Error(string.Format("'{0}' threw an exception publishing message '{1}'", consumer.GetType().FullName, message.GetType().FullName), ex); exceptions.Add(ex); } } context.Complete(); if (publishedCount == 0) { context.NotifyNoSubscribers(); } _eventChannel.Send(new MessagePublished { MessageType = typeof(T), ConsumerCount = publishedCount, Duration = context.Duration, }); if (exceptions.Count > 0) throw new PublishException(typeof(T), exceptions); } public void Publish(object message) { if (message == null) throw new ArgumentNullException("message"); BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message); } public void Publish(object message, Type messageType) { if (message == null) throw new ArgumentNullException("message"); if (messageType == null) throw new ArgumentNullException("messageType"); BusObjectPublisherCache.Instance[messageType].Publish(this, message); } public void Publish(object message, Action<IPublishContext> contextCallback) { if (message == null) throw new ArgumentNullException("message"); if (contextCallback == null) throw new ArgumentNullException("contextCallback"); BusObjectPublisherCache.Instance[message.GetType()].Publish(this, message, contextCallback); } public void Publish(object message, Type messageType, Action<IPublishContext> contextCallback) { if (message == null) throw new ArgumentNullException("message"); if (messageType == null) throw new ArgumentNullException("messageType"); if (contextCallback == null) throw new ArgumentNullException("contextCallback"); BusObjectPublisherCache.Instance[messageType].Publish(this, message, contextCallback); } /// <summary> /// <see cref="IServiceBus.Publish{T}"/>: this is a "dynamically" /// typed overload - give it an interface as its type parameter, /// and a loosely typed dictionary of values and the Burrows /// underlying infrastructure will populate an object instance /// with the passed values. It actually does this with DynamicProxy /// in the background. /// </summary> /// <typeparam name="T">The type of the interface or /// non-sealed class with all-virtual members.</typeparam> /// <param name="bus">The bus to publish on.</param> /// <param name="values">The dictionary of values to place in the /// object instance to implement the interface.</param> public void Publish<T>(object values) where T : class { if (values == null) throw new ArgumentNullException("values"); var message = InterfaceImplementationExtensions.InitializeProxy<T>(values); Publish(message, x => { }); } /// <summary> /// <see cref="Publish{T}(Burrows.IServiceBus,object)"/>: this /// overload further takes an action; it allows you to set <see cref="IPublishContext"/> /// meta-data. Also <see cref="IServiceBus.Publish{T}"/>. /// </summary> /// <typeparam name="T">The type of the message to publish</typeparam> /// <param name="bus">The bus to publish the message on.</param> /// <param name="values">The dictionary of values to become hydrated and /// published under the type of the interface.</param> /// <param name="contextCallback">The context callback.</param> public void Publish<T>(object values, Action<IPublishContext<T>> contextCallback) where T : class { if (values == null) throw new ArgumentNullException("values"); var message = InterfaceImplementationExtensions.InitializeProxy<T>(values); Publish(message, contextCallback); } public IOutboundMessagePipeline OutboundPipeline { get; private set; } public IInboundMessagePipeline InboundPipeline { get; private set; } /// <summary> /// The endpoint associated with this instance /// </summary> public IEndpoint Endpoint { get; private set; } public UnsubscribeAction Configure(Func<IInboundPipelineConfigurator, UnsubscribeAction> configure) { return InboundPipeline.Configure(configure); } public IServiceBus ControlBus { get; set; } public IEndpoint GetEndpoint(Uri address) { return EndpointCache.GetEndpoint(address); } public void Inspect(IDiagnosticsProbe probe) { new StandardDiagnosticsInfo().WriteCommonItems(probe); probe.Add("mt.version", typeof(IServiceBus).Assembly.GetName().Version); probe.Add("mt.receive_from", Endpoint.Address); probe.Add("mt.control_bus", ControlBus.Endpoint.Address); probe.Add("mt.max_consumer_threads", MaximumConsumerThreads); probe.Add("mt.concurrent_receive_threads", ConcurrentReceiveThreads); probe.Add("mt.receive_timeout", ReceiveTimeout); EndpointCache.Inspect(probe); _serviceContainer.Inspect(probe); OutboundPipeline.View(pipe => probe.Add("zz.mt.outbound_pipeline", pipe)); InboundPipeline.View(pipe => probe.Add("zz.mt.inbound_pipeline", pipe)); } public IBusService GetService(Type type) { return _serviceContainer.GetService(type); } public bool TryGetService(Type type, out IBusService result) { return _serviceContainer.TryGetService(type, out result); } void NoContext<T>(IPublishContext<T> context) where T : class { } public void Start() { if (_started) return; try { _serviceContainer.Start(); _consumerPool = new ThreadPoolConsumerPool(this, _eventChannel, _receiveTimeout) { MaximumConsumerCount = MaximumConsumerThreads, }; _consumerPool.Start(); } catch (Exception) { if (_consumerPool != null) _consumerPool.Dispose(); throw; } _started = true; } public void AddService(IBusServiceLayer layer, IBusService service) { _serviceContainer.AddService(layer, service); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { if (_consumerPool != null) { _consumerPool.Stop(); _consumerPool.Dispose(); _consumerPool = null; } if (_serviceContainer != null) { _serviceContainer.Stop(); _serviceContainer.Dispose(); _serviceContainer = null; } if (ControlBus != this) ControlBus.Dispose(); if (_performanceCounterConnection != null) { _performanceCounterConnection.Dispose(); _performanceCounterConnection = null; } _eventChannel = null; Endpoint = null; if (_counters != null) { _counters.Dispose(); _counters = null; } EndpointCache.Dispose(); } _disposed = true; } void InitializePerformanceCounters() { try { string instanceName = string.Format("{0}_{1}{2}", Endpoint.Address.Uri.Scheme, Endpoint.Address.Uri.Host, Endpoint.Address.Uri.AbsolutePath.Replace("/", "_")); _counters = new ServiceBusInstancePerformanceCounters(instanceName); _performanceCounterConnection = _eventChannel.Connect(x => { x.AddConsumerOf<MessageReceived>() .UsingConsumer(message => { _counters.ReceiveCount.Increment(); _counters.ReceiveRate.Increment(); _counters.ReceiveDuration.IncrementBy( (long)message.ReceiveDuration.TotalMilliseconds); _counters.ReceiveDurationBase.Increment(); _counters.ConsumerDuration.IncrementBy( (long)message.ConsumeDuration.TotalMilliseconds); _counters.ConsumerDurationBase.Increment(); }); x.AddConsumerOf<MessagePublished>() .UsingConsumer(message => { _counters.PublishCount.Increment(); _counters.PublishRate.Increment(); _counters.PublishDuration.IncrementBy((long)message.Duration.TotalMilliseconds); _counters.PublishDurationBase.Increment(); _counters.SentCount.IncrementBy(message.ConsumerCount); _counters.SendRate.IncrementBy(message.ConsumerCount); }); x.AddConsumerOf<ThreadPoolEvent>() .UsingConsumer(message => { _counters.ReceiveThreadCount.Set(message.ReceiverCount); _counters.ConsumerThreadCount.Set(message.ConsumerCount); }); }); } catch (Exception ex) { _log.Warn( "The performance counters could not be created, try running the program in the Administrator role. Just once.", ex); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using Measter; using Parsers; using Parsers.Culture; using Parsers.Dynasty; using Parsers.Localisations; using Parsers.Map; using Parsers.Mod; using Parsers.Options; using Parsers.Province; using Parsers.Religion; using Parsers.Title; using TitleGenerator.HistoryRules; namespace TitleGenerator { public class CK2Data { [Flags] public enum DataTypes { Cultures = 1, Dynasties = 2, LandedTitles = 4, Nicknames = 8, Religions = 16, Traits = 32, Characters = 64, Localisations = 128, Mods = 256, Provinces = 512, ConvertTable = 1024, History = 2048, MarkovChains = 4096 } private readonly ModReader m_modReader; private readonly CultureReader m_cultureReader; private readonly ReligionReader m_religionReader; private readonly DynastyReader m_dynastyReader; private readonly TitleReader m_titleReader; private readonly ProvinceReader m_provinceReader; private readonly LocalisationReader m_localisationStrings; private readonly ConverterTableReader m_converterTableReader; private readonly Logger m_log; private readonly Dictionary<string, CultureGroup> m_customCultureGroups; private readonly Dictionary<string, Culture> m_customCultures; private bool m_useCustomCulture; private readonly List<List<MarkovWordGenerator>> m_wordGenerators; public bool HasFullMarkovChains { get; private set; } public CK2Data( Logger log ) { m_modReader = new ModReader(); m_cultureReader = new CultureReader(); m_religionReader = new ReligionReader(); m_dynastyReader = new DynastyReader(); m_titleReader = new TitleReader(); m_localisationStrings = new LocalisationReader(); m_provinceReader = new ProvinceReader(); m_converterTableReader = new ConverterTableReader(); m_customCultureGroups = new Dictionary<string, CultureGroup>(); m_customCultures = new Dictionary<string, Culture>(); m_wordGenerators = new List<List<MarkovWordGenerator>>(); m_log = log; HadError = false; } public string Error { get; private set; } public bool HadError { get; private set; } public DirectoryInfo InstallDir { get; private set; } public DirectoryInfo MyDocsDir { get; private set; } #region Accessors public ReadOnlyCollection<Mod> GetMods { get; private set; } public ReadOnlyDictionary<string, CultureGroup> CultureGroups { get; private set; } public ReadOnlyDictionary<string, Culture> Cultures { get; private set; } public ReadOnlyDictionary<string, ReligionGroup> ReligionGroups { get; private set; } public ReadOnlyDictionary<string, Religion> Religions { get; private set; } public ReadOnlyDictionary<int, Dynasty> Dynasties { get; private set; } public ReadOnlyDictionary<string, Title> Counties { get; private set; } public ReadOnlyDictionary<string, Title> Duchies { get; private set; } public ReadOnlyDictionary<string, Title> Kingdoms { get; private set; } public ReadOnlyDictionary<string, Title> Empires { get; private set; } public ReadOnlyDictionary<string, string> Localisations { get; private set; } public ReadOnlyDictionary<int, Province> Provinces { get; private set; } public ReadOnlyDictionary<string, string> NationTable { get; private set; } public ReadOnlyDictionary<string, ReadOnlyCollection<EventOption>> History { get; private set; } #endregion public void SetCustomCultures( List<CultureGroup> cultureGroups ) { m_useCustomCulture = true; m_customCultureGroups.Clear(); m_customCultures.Clear(); foreach( CultureGroup cg in cultureGroups ) { m_customCultureGroups.Add( cg.Name, cg ); foreach( var culture in cg.Cultures ) m_customCultures.Add( culture.Key, culture.Value ); } } public void ClearCustomCultures( Options options ) { m_log.Log( "Clearing custom cultures from data.", Logger.LogType.Data ); foreach( var pair in m_customCultureGroups ) { options.RuleSet.MaleCultures.Remove( pair.Key ); options.RuleSet.FemaleCultures.Remove( pair.Key ); options.RuleSet.MuslimLawFollowers.Remove( pair.Key ); foreach( Law law in options.RuleSet.LawRules.GenderLaws ) { law.AllowedCultures.Remove( pair.Key ); law.BannedCultures.Remove( pair.Key ); } foreach( Law law in options.RuleSet.LawRules.SuccessionLaws ) { law.AllowedCultures.Remove( pair.Key ); law.BannedCultures.Remove( pair.Key ); } } foreach( var pair in m_customCultures ) { options.RuleSet.MaleCultures.Remove( pair.Key ); options.RuleSet.FemaleCultures.Remove( pair.Key ); options.RuleSet.MuslimLawFollowers.Remove( pair.Key ); foreach( Law law in options.RuleSet.LawRules.GenderLaws ) { law.AllowedCultures.Remove( pair.Key ); law.BannedCultures.Remove( pair.Key ); } foreach( Law law in options.RuleSet.LawRules.SuccessionLaws ) { law.AllowedCultures.Remove( pair.Key ); law.BannedCultures.Remove( pair.Key ); } } m_useCustomCulture = false; m_customCultureGroups.Clear(); m_customCultures.Clear(); } public bool TryGetCulture( string key, out Culture cul ) { bool found = false; if( m_useCustomCulture ) found = m_customCultures.TryGetValue( key, out cul ); if( !found ) found = Cultures.TryGetValue( key, out cul ); cul = null; return found; } public bool TryGetCultureGroup( string key, out CultureGroup culGroup ) { bool found = false; if( m_useCustomCulture ) found = m_customCultureGroups.TryGetValue( key, out culGroup ); if( !found ) found = CultureGroups.TryGetValue( key, out culGroup ); culGroup = null; return found; } public bool ContainsCulture( string key ) { bool found = false; if( m_useCustomCulture ) found = m_customCultures.ContainsKey( key ); if( !found ) found = Cultures.ContainsKey( key ); return found; } public bool ContainsCultureGroup( string key ) { bool found = false; if( m_useCustomCulture ) found = m_customCultureGroups.ContainsKey( key ); if( !found ) found = CultureGroups.ContainsKey( key ); return found; } public Culture GetCulture( string key ) { if( m_useCustomCulture && m_customCultures.ContainsKey( key ) ) return m_customCultures[key]; return Cultures[key]; } public CultureGroup GetCultureGroup( string key ) { if( m_useCustomCulture && m_customCultureGroups.ContainsKey( key ) ) return m_customCultureGroups[key]; return CultureGroups[key]; } public KeyValuePair<string, Culture> GetRandomCulture( Random rand ) { if( m_useCustomCulture && rand.Next(2) == 0 ) return m_customCultures.RandomItem( rand ); return Cultures.RandomItem( rand ); } public bool SetInstallPath( DirectoryInfo ckDir ) { if( !ckDir.Exists ) { Error = "Unable to find the directory.\n\n" + ckDir.FullName; HadError = true; return false; } if( !File.Exists( Path.Combine( ckDir.FullName, "ck2.exe" ).Replace( '\\', '/' ) ) && !File.Exists( Path.Combine( ckDir.FullName, "ck2" ).Replace( '\\', '/' ) ) && !File.Exists( Path.Combine( ckDir.FullName, "CK2game.exe" ).Replace( '\\', '/' ) ) && !File.Exists( Path.Combine( ckDir.FullName, "GK2game" ).Replace( '\\', '/' ) ) ) { Error = "Unable to find Crusader Kings II in the following directory:\n\n" + ckDir.FullName; HadError = true; return false; } InstallDir = ckDir; SetModDirs(); return true; } public void Clear( DataTypes dataList ) { #region Cultures and Dynasties if( dataList.IsFlagSet<DataTypes>( DataTypes.Cultures ) ) { m_cultureReader.CultureGroups.Clear(); m_cultureReader.Cultures.Clear(); m_cultureReader.Errors.Clear(); } if( dataList.IsFlagSet<DataTypes>( DataTypes.Dynasties ) ) { m_dynastyReader.Dynasties.Clear(); m_dynastyReader.Errors.Clear(); } #endregion #region Landed Titles if( dataList.IsFlagSet<DataTypes>( DataTypes.LandedTitles ) ) { m_titleReader.Counties.Clear(); m_titleReader.Duchies.Clear(); m_titleReader.Kingdoms.Clear(); m_titleReader.Empires.Clear(); m_titleReader.Errors.Clear(); } #endregion #region Religions and Traits if( dataList.IsFlagSet<DataTypes>( DataTypes.Religions ) ) { m_religionReader.Religions.Clear(); m_religionReader.ReligionGroups.Clear(); m_religionReader.Errors.Clear(); } #endregion #region Localisations if( dataList.IsFlagSet<DataTypes>( DataTypes.Localisations ) ) { m_localisationStrings.LocalisationStrings.Clear(); m_localisationStrings.Errors.Clear(); } #endregion #region Mods and Provinces if( dataList.IsFlagSet<DataTypes>( DataTypes.Mods ) ) { m_modReader.Mods.Clear(); m_modReader.Errors.Clear(); } if( dataList.IsFlagSet<DataTypes>( DataTypes.Provinces ) ) { m_provinceReader.Provinces.Clear(); m_provinceReader.Errors.Clear(); } #endregion } public bool LoadData( List<Mod> selected, DataTypes dataList ) { Clear( dataList ); #region Dynasties and Cultures if( dataList.IsFlagSet<DataTypes>( DataTypes.Dynasties ) ) { m_log.Log( "Loading Dynasties", Logger.LogType.Data ); if( !LoadData( m_dynastyReader, selected, @"common\dynasties", "dynasties", "*.txt", true ) ) return false; Dynasties = new ReadOnlyDictionary<int, Dynasty>( m_dynastyReader.Dynasties ); m_log.Log( " --Dynasties: " + m_dynastyReader.Dynasties.Count, Logger.LogType.Data ); } if( dataList.IsFlagSet<DataTypes>( DataTypes.Cultures ) ) { m_log.Log( "Loading Cultures", Logger.LogType.Data ); if( !LoadData( m_cultureReader, selected, @"common\cultures", "cultures", "*.txt", true ) ) return false; Cultures = new ReadOnlyDictionary<string, Culture>( m_cultureReader.Cultures ); CultureGroups = new ReadOnlyDictionary<string, CultureGroup>( m_cultureReader.CultureGroups ); m_log.Log( " --Culture Groups: " + m_cultureReader.CultureGroups.Count, Logger.LogType.Data ); m_log.Log( " --Cultures: " + m_cultureReader.Cultures.Count, Logger.LogType.Data ); } #endregion #region Titles if( dataList.IsFlagSet<DataTypes>( DataTypes.LandedTitles ) ) { m_log.Log( "Loading Titles", Logger.LogType.Data ); if( !LoadData( m_titleReader, selected, @"common\landed_titles", "landed_titles", "*.txt", true ) ) return false; Counties = new ReadOnlyDictionary<string, Title>( m_titleReader.Counties ); Duchies = new ReadOnlyDictionary<string, Title>( m_titleReader.Duchies ); Kingdoms = new ReadOnlyDictionary<string, Title>( m_titleReader.Kingdoms ); Empires = new ReadOnlyDictionary<string, Title>( m_titleReader.Empires ); m_log.Log( " --Empires: " + m_titleReader.Empires.Count, Logger.LogType.Data ); m_log.Log( " --Kingdoms: " + m_titleReader.Kingdoms.Count, Logger.LogType.Data ); m_log.Log( " --Duchies: " + m_titleReader.Duchies.Count, Logger.LogType.Data ); m_log.Log( " --Counties: " + m_titleReader.Counties.Count, Logger.LogType.Data ); } #endregion #region Religions if( dataList.IsFlagSet<DataTypes>( DataTypes.Religions ) ) { m_log.Log( "Loading Religions", Logger.LogType.Data ); if( !LoadData( m_religionReader, selected, @"common\religions", "religions", "*.txt", true ) ) return false; Religions = new ReadOnlyDictionary<string, Religion>( m_religionReader.Religions ); ReligionGroups = new ReadOnlyDictionary<string, ReligionGroup>( m_religionReader.ReligionGroups ); m_log.Log( " --Religion Groups: " + m_religionReader.ReligionGroups.Count, Logger.LogType.Data ); m_log.Log( " --Religions: " + m_religionReader.Religions.Count, Logger.LogType.Data ); } #endregion #region Localisations if( dataList.IsFlagSet<DataTypes>( DataTypes.Localisations ) ) { m_log.Log( "Loading Localisations", Logger.LogType.Data ); if( !LoadData( m_localisationStrings, selected, @"localisation", "localisations", "*.csv", true ) ) return false; Localisations = new ReadOnlyDictionary<string, string>( m_localisationStrings.LocalisationStrings ); m_log.Log( " --Localisations: " + m_localisationStrings.LocalisationStrings.Count, Logger.LogType.Data ); } #endregion #region Provinces and Mods if( dataList.IsFlagSet<DataTypes>( DataTypes.Provinces ) ) { m_log.Log( "Loading Provinces", Logger.LogType.Data ); if( !LoadData( m_provinceReader, selected, @"history\provinces", "provinces", "*.txt", true ) ) return false; Provinces = new ReadOnlyDictionary<int, Province>( m_provinceReader.Provinces ); m_log.Log( " --Provinces: " + m_provinceReader.Provinces.Count, Logger.LogType.Data ); } if( dataList.IsFlagSet<DataTypes>( DataTypes.Mods ) ) { m_log.Log( "Loading Mods", Logger.LogType.Data ); if( !LoadMods() ) return false; GetMods = m_modReader.Mods.AsReadOnly(); m_log.Log( " --Mods:" + m_modReader.Mods.Count, Logger.LogType.Data ); } #endregion #region Converter Table and History if( dataList.IsFlagSet<DataTypes>( DataTypes.ConvertTable ) ) { m_log.Log( "Loading Converter Table", Logger.LogType.Data ); if( !LoadData( m_converterTableReader, selected, "common/eu4_converter", "converter", "*.csv", false ) ) return false; NationTable = new ReadOnlyDictionary<string, string>( m_converterTableReader.Nations ); m_log.Log( " --Nation Tables: " + m_converterTableReader.Nations.Count, Logger.LogType.Data ); } #endregion if( dataList.IsFlagSet<DataTypes>( DataTypes.MarkovChains ) ) { m_log.Log( "Loading Markov Chains", Logger.LogType.Data ); HasFullMarkovChains = LoadMarkovChains(); if( HasFullMarkovChains ) m_log.Log( "Markov Chains Loaded.", Logger.LogType.Data ); } return true; } private void OutputError( ReaderBase reader, string errorString ) { StringBuilder sb = new StringBuilder(); sb.AppendLine( "Errors encountered loading " + errorString + ":" ); sb.AppendLine(); foreach( string err in reader.Errors ) sb.AppendLine( err ); Error = sb.ToString(); HadError = true; } public Dynasty GetDynastyByCulture( Dictionary<int, Dynasty> availDynasties, Culture cul, Random rand ) { if( m_useCustomCulture && cul.CustomFlags.ContainsKey( "orig" ) ) cul = (Culture)cul.CustomFlags["orig"]; return m_dynastyReader.GetDynastyByCulture( availDynasties, cul, rand ); } private void SetModDirs() { string myDocs = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments ); MyDocsDir = new DirectoryInfo( Path.Combine( myDocs, @"Paradox Interactive\Crusader Kings II\" ).Replace( '\\', '/' ) ); } private bool LoadMods() { m_modReader.Mods.Clear(); m_modReader.Errors.Clear(); m_modReader.ParseFolder( Path.Combine( InstallDir.FullName, @"mod" ).Replace( '\\', '/' ), ModReader.Folder.CKDir ); m_modReader.ParseFolder( Path.Combine( MyDocsDir.FullName, @"mod" ).Replace( '\\', '/' ), ModReader.Folder.MyDocs ); if( m_modReader.Errors.Count != 0 ) { StringBuilder sb = new StringBuilder(); sb.AppendLine( "Errors encountered during mod loading: " ); sb.AppendLine(); foreach( string err in m_modReader.Errors ) sb.AppendLine( err ); Error = sb.ToString(); HadError = true; return false; } return true; } public bool LinkData( List<Mod> selected, DataTypes dataList ) { if ( dataList.IsFlagSet<DataTypes>( DataTypes.Cultures | DataTypes.Dynasties ) ) m_dynastyReader.LinkCultures( m_cultureReader.Cultures ); if( dataList.IsFlagSet<DataTypes>( DataTypes.LandedTitles | DataTypes.Provinces ) ) m_titleReader.LinkCounties( m_provinceReader.Provinces ); //Parse adjacencies if ( dataList.IsFlagSet<DataTypes>( DataTypes.Provinces ) ) if ( !ParseAdjacencies( selected ) ) return false; return true; } private bool ParseAdjacencies( List<Mod> selected ) { m_log.Log( "Parsing Adjacencies", Logger.LogType.Data ); string userDir = string.Empty, dirTemp; string mapFile = Path.Combine( InstallDir.FullName, "map/default.map" ).Replace( '\\', '/' ); //Discover which default.map and setup.log file to read. foreach( Mod m in selected ) { dirTemp = m.ModPathType == ModReader.Folder.CKDir ? InstallDir.FullName : MyDocsDir.FullName; dirTemp = Path.Combine( dirTemp, m.Path ); dirTemp = Path.Combine( dirTemp, "map/default.map" ).Replace( '\\', '/' ); if( File.Exists( dirTemp ) ) { mapFile = dirTemp; userDir = m.UserDir; } } string setupLog = Path.Combine( MyDocsDir.FullName, userDir ); setupLog = Path.Combine( setupLog, "logs/setup.log" ).Replace( '\\', '/' ); if ( !File.Exists( setupLog ) ) { // Fall back to vanilla file. m_log.Log( "Unable to find the following file: " + setupLog, Logger.LogType.Error ); m_log.Log( "Falling back to vanilla", Logger.LogType.Error ); setupLog = Path.Combine( MyDocsDir.FullName, "logs/setup.log" ).Replace( '\\', '/' ); } if( !File.Exists( setupLog ) ) { Error = "Unable to find the following file: "; Error += setupLog; Error += "\n"; Error += "Please start CKII with the mods you wish to use."; HadError = true; return false; } Map map = Map.Parse( mapFile ); //Discover which mod to get adjacency from. string adjFile = Path.Combine( InstallDir.FullName, "map/" ); adjFile = Path.Combine( adjFile, map.Adjacencies ).Replace( '\\', '/' ); foreach( Mod m in selected ) { dirTemp = m.ModPathType == ModReader.Folder.CKDir ? InstallDir.FullName : MyDocsDir.FullName; dirTemp = Path.Combine( dirTemp, m.Path ); dirTemp = Path.Combine( dirTemp, "map/" + map.Adjacencies ).Replace( '\\', '/' ); if( File.Exists( dirTemp ) ) adjFile = dirTemp; } m_provinceReader.ParseAdjacencies( setupLog, map, adjFile ); return true; } private bool LoadData( ReaderBase reader, IEnumerable<Mod> mods, string subDir, string errorString, string ext, bool falseOnNoDirectory ) { Dictionary<string, string> files = new Dictionary<string, string>(); DirectoryInfo dir; // Oldest First. Discover if vanilla should be loaded. bool loadVanilla = mods.All( m => !m.Replaces.Contains( subDir ) ); if( loadVanilla ) { dir = new DirectoryInfo( Path.Combine( InstallDir.FullName, subDir ).Replace( '\\', '/' ) ); // Hack so it works when the eu4 converter isn't present. if( !dir.Exists && falseOnNoDirectory ) return false; if( !dir.Exists ) return true; m_log.Log( "Loading files from " + dir.FullName, Logger.LogType.Data ); FileInfo[] list = dir.GetFiles( ext ); foreach( FileInfo f in list ) files[f.Name] = f.FullName; } // If using mods, load files. string dirTemp; foreach( Mod m in mods ) { dirTemp = m.ModPathType == ModReader.Folder.CKDir ? InstallDir.FullName : MyDocsDir.FullName; dirTemp = Path.Combine( dirTemp, m.Path ); dirTemp = Path.Combine( dirTemp, subDir ).Replace( '\\', '/' ); if( !Directory.Exists( dirTemp ) ) continue; dir = new DirectoryInfo( dirTemp ); m_log.Log( "Loading files from " + dir.FullName, Logger.LogType.Data ); FileInfo[] list = dir.GetFiles( ext ); foreach( FileInfo f in list ) files[f.Name] = f.FullName; } foreach( var file in files ) { m_log.Log( "Reading File: " + file.Value, Logger.LogType.Data ); reader.Parse( file.Value ); } if( reader.Errors.Count > 0 ) { OutputError( reader, errorString ); return false; } return true; } private bool LoadMarkovChains() { DirectoryInfo dir = new DirectoryInfo( "namedata" ); if( !dir.Exists ) return false; FileInfo[] files = dir.GetFiles( "*.bin" ); var groups = files.GroupBy( f => f.Name[0] ); MarkovWordGenerator gen; List<MarkovWordGenerator> genList; foreach( var gr in groups ) { genList = new List<MarkovWordGenerator>(); foreach( FileInfo file in gr ) { using( FileStream fs = new FileStream( file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read ) ) using( BinaryReader br = new BinaryReader( fs ) ) { gen = new MarkovWordGenerator( br ); genList.Add( gen ); } } m_wordGenerators.Add( genList ); } if ( m_wordGenerators.Count == 0 ) return false; return true; } public List<string> GenerateWords( int genGroup, int genID, int count, int minLen, int maxLen ) { List<string> names = new List<string>(); List<MarkovWordGenerator> genList = m_wordGenerators[genGroup % m_wordGenerators.Count]; MarkovWordGenerator gen = genList[genID % genList.Count]; for( int i = 0; i < count; i++ ) { names.Add( gen.NextName( minLen, maxLen ) ); } return names; } public string GenerateWord( int genGroup, int genID, int minLen, int maxLen ) { List<MarkovWordGenerator> genList = m_wordGenerators[genGroup % m_wordGenerators.Count]; MarkovWordGenerator gen = genList[genID % genList.Count]; return gen.NextName( minLen, maxLen ); } public void SetMarkovRandom( Random rand ) { foreach ( var genList in m_wordGenerators ) { foreach ( var gen in genList ) { gen.SetRandom( rand ); } } } } }
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using Avalonia.Automation.Peers; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Input.Platform; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Rendering; using Avalonia.Styling; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// Base class for Avalonia controls. /// </summary> /// <remarks> /// The control class extends <see cref="InputElement"/> and adds the following features: /// /// - A <see cref="Tag"/> property to allow user-defined data to be attached to the control. /// - <see cref="ContextRequestedEvent"/> and other context menu related members. /// </remarks> public class Control : InputElement, IControl, INamed, IVisualBrushInitialize, ISetterValue { /// <summary> /// Defines the <see cref="FocusAdorner"/> property. /// </summary> public static readonly StyledProperty<ITemplate<IControl>?> FocusAdornerProperty = AvaloniaProperty.Register<Control, ITemplate<IControl>?>(nameof(FocusAdorner)); /// <summary> /// Defines the <see cref="Tag"/> property. /// </summary> public static readonly StyledProperty<object?> TagProperty = AvaloniaProperty.Register<Control, object?>(nameof(Tag)); /// <summary> /// Defines the <see cref="ContextMenu"/> property. /// </summary> public static readonly StyledProperty<ContextMenu?> ContextMenuProperty = AvaloniaProperty.Register<Control, ContextMenu?>(nameof(ContextMenu)); /// <summary> /// Defines the <see cref="ContextFlyout"/> property /// </summary> public static readonly StyledProperty<FlyoutBase?> ContextFlyoutProperty = AvaloniaProperty.Register<Control, FlyoutBase?>(nameof(ContextFlyout)); /// <summary> /// Event raised when an element wishes to be scrolled into view. /// </summary> public static readonly RoutedEvent<RequestBringIntoViewEventArgs> RequestBringIntoViewEvent = RoutedEvent.Register<Control, RequestBringIntoViewEventArgs>("RequestBringIntoView", RoutingStrategies.Bubble); /// <summary> /// Provides event data for the <see cref="ContextRequested"/> event. /// </summary> public static readonly RoutedEvent<ContextRequestedEventArgs> ContextRequestedEvent = RoutedEvent.Register<Control, ContextRequestedEventArgs>(nameof(ContextRequested), RoutingStrategies.Tunnel | RoutingStrategies.Bubble); /// <summary> /// Defines the <see cref="FlowDirection"/> property. /// </summary> public static readonly AttachedProperty<FlowDirection> FlowDirectionProperty = AvaloniaProperty.RegisterAttached<Control, Control, FlowDirection>(nameof(FlowDirection), inherits: true); private DataTemplates? _dataTemplates; private IControl? _focusAdorner; private AutomationPeer? _automationPeer; /// <summary> /// Gets or sets the control's focus adorner. /// </summary> public ITemplate<IControl>? FocusAdorner { get => GetValue(FocusAdornerProperty); set => SetValue(FocusAdornerProperty, value); } /// <summary> /// Gets or sets the data templates for the control. /// </summary> /// <remarks> /// Each control may define data templates which are applied to the control itself and its /// children. /// </remarks> public DataTemplates DataTemplates => _dataTemplates ??= new DataTemplates(); /// <summary> /// Gets or sets a context menu to the control. /// </summary> public ContextMenu? ContextMenu { get => GetValue(ContextMenuProperty); set => SetValue(ContextMenuProperty, value); } /// <summary> /// Gets or sets a context flyout to the control /// </summary> public FlyoutBase? ContextFlyout { get => GetValue(ContextFlyoutProperty); set => SetValue(ContextFlyoutProperty, value); } /// <summary> /// Gets or sets a user-defined object attached to the control. /// </summary> public object? Tag { get => GetValue(TagProperty); set => SetValue(TagProperty, value); } /// <summary> /// Gets or sets the text flow direction. /// </summary> public FlowDirection FlowDirection { get => GetValue(FlowDirectionProperty); set => SetValue(FlowDirectionProperty, value); } /// <summary> /// Occurs when the user has completed a context input gesture, such as a right-click. /// </summary> public event EventHandler<ContextRequestedEventArgs>? ContextRequested { add => AddHandler(ContextRequestedEvent, value); remove => RemoveHandler(ContextRequestedEvent, value); } public new IControl? Parent => (IControl?)base.Parent; /// <inheritdoc/> bool IDataTemplateHost.IsDataTemplatesInitialized => _dataTemplates != null; /// <inheritdoc/> void ISetterValue.Initialize(ISetter setter) { if (setter is Setter s && s.Property == ContextFlyoutProperty) { return; // Allow ContextFlyout to not need wrapping in <Template> } throw new InvalidOperationException( "Cannot use a control as a Setter value. Wrap the control in a <Template>."); } /// <inheritdoc/> void IVisualBrushInitialize.EnsureInitialized() { if (VisualRoot == null) { if (!IsInitialized) { foreach (var i in this.GetSelfAndVisualDescendants()) { var c = i as IControl; if (c?.IsInitialized == false && c is ISupportInitialize init) { init.BeginInit(); init.EndInit(); } } } if (!IsArrangeValid) { Measure(Size.Infinity); Arrange(new Rect(DesiredSize)); } } } /// <summary> /// Gets the element that receives the focus adorner. /// </summary> /// <returns>The control that receives the focus adorner.</returns> protected virtual IControl? GetTemplateFocusTarget() => this; /// <inheritdoc/> protected sealed override void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTreeCore(e); InitializeIfNeeded(); } /// <inheritdoc/> protected sealed override void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e) { base.OnDetachedFromVisualTreeCore(e); } /// <inheritdoc/> protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); if (IsFocused && (e.NavigationMethod == NavigationMethod.Tab || e.NavigationMethod == NavigationMethod.Directional)) { var adornerLayer = AdornerLayer.GetAdornerLayer(this); if (adornerLayer != null) { if (_focusAdorner == null) { var template = GetValue(FocusAdornerProperty); if (template != null) { _focusAdorner = template.Build(); } } if (_focusAdorner != null && GetTemplateFocusTarget() is Visual target) { AdornerLayer.SetAdornedElement((Visual)_focusAdorner, target); adornerLayer.Children.Add(_focusAdorner); } } } } /// <inheritdoc/> protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); if (_focusAdorner?.Parent != null) { var adornerLayer = (IPanel)_focusAdorner.Parent; adornerLayer.Children.Remove(_focusAdorner); _focusAdorner = null; } } protected virtual AutomationPeer OnCreateAutomationPeer() { return new NoneAutomationPeer(this); } internal AutomationPeer GetOrCreateAutomationPeer() { VerifyAccess(); if (_automationPeer is object) { return _automationPeer; } _automationPeer = OnCreateAutomationPeer(); return _automationPeer; } protected override void OnPointerReleased(PointerReleasedEventArgs e) { base.OnPointerReleased(e); if (e.Source == this && !e.Handled && e.InitialPressMouseButton == MouseButton.Right) { var args = new ContextRequestedEventArgs(e); RaiseEvent(args); e.Handled = args.Handled; } } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (e.Source == this && !e.Handled) { var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>()?.OpenContextMenu; if (keymap is null) return; var matches = false; for (var index = 0; index < keymap.Count; index++) { var key = keymap[index]; matches |= key.Matches(e); if (matches) { break; } } if (matches) { var args = new ContextRequestedEventArgs(); RaiseEvent(args); e.Handled = args.Handled; } } } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using FizzWare.NBuilder.Implementation; using System.Linq; using FizzWare.NBuilder.Extensions; namespace FizzWare.NBuilder.PropertyNaming { public class RandomValuePropertyNamer : PropertyNamer { private readonly bool generatePositiveValuesOnly; private readonly DateTime minDate; private readonly DateTime maxDate; private static readonly List<char> allowedChars; private static readonly string[] words; private readonly IRandomGenerator generator; private readonly bool useLoremIpsumForStrings; public RandomValuePropertyNamer(BuilderSettings builderSettings) : this (new RandomGenerator(), new ReflectionUtil(), false, builderSettings) { } public RandomValuePropertyNamer(IRandomGenerator generator, IReflectionUtil reflectionUtil, bool generatePositiveValuesOnly,BuilderSettings builderSettings) : this(generator, reflectionUtil, generatePositiveValuesOnly, DateTime.MinValue, DateTime.MaxValue, false,builderSettings) { this.generator = generator; } public RandomValuePropertyNamer(IRandomGenerator generator, IReflectionUtil reflectionUtil, bool generatePositiveValuesOnly, DateTime minDate, DateTime maxDate, bool useLoremIpsumForStrings,BuilderSettings builderSettings) : base(reflectionUtil, builderSettings) { this.generator = generator; this.generatePositiveValuesOnly = generatePositiveValuesOnly; this.useLoremIpsumForStrings = useLoremIpsumForStrings; this.minDate = minDate; this.maxDate = maxDate; } static RandomValuePropertyNamer() { allowedChars = new List<char>(); for (char c = 'a'; c < 'z'; c++) allowedChars.Add(c); for (char c = 'A'; c < 'Z'; c++) allowedChars.Add(c); for (char c = '0'; c < '9'; c++) allowedChars.Add(c); // words = @"lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum".Split(' '); } public override void SetValuesOfAllIn<T>(IList<T> objects) { var type = typeof(T); for (int i = 0; i < objects.Count; i++) { foreach (var propertyInfo in type.GetProperties(FLAGS).Where(p => p.CanWrite)) { SetMemberValue(propertyInfo, objects[i]); } foreach (var fieldInfo in type.GetFields().Where(f => !f.IsLiteral)) { SetMemberValue(fieldInfo, objects[i]); } } } protected override short GetInt16(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? (short)0 : short.MinValue; return generator.Next(minValue, short.MaxValue); } protected override int GetInt32(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? 0 : int.MinValue; return generator.Next(minValue, int.MaxValue); } protected override long GetInt64(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? 0 : long.MinValue; return generator.Next(minValue, long.MaxValue); } protected override decimal GetDecimal(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? 0 : decimal.MinValue; return generator.Next(minValue, decimal.MaxValue); } protected override float GetSingle(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? 0 : float.MinValue; return generator.Next(minValue, float.MaxValue); } protected override double GetDouble(MemberInfo memberInfo) { var minValue = generatePositiveValuesOnly ? 0 : double.MinValue; return generator.Next(minValue, double.MaxValue); } protected override ushort GetUInt16(MemberInfo memberInfo) { return generator.Next(ushort.MinValue, ushort.MaxValue); } protected override uint GetUInt32(MemberInfo memberInfo) { return generator.Next(uint.MinValue, uint.MaxValue); } protected override ulong GetUInt64(MemberInfo memberInfo) { return generator.Next(ulong.MinValue, ulong.MaxValue); } protected override byte GetByte(MemberInfo memberInfo) { return generator.Next(byte.MinValue, byte.MaxValue); } protected override sbyte GetSByte(MemberInfo memberInfo) { return generator.Next(sbyte.MinValue, sbyte.MaxValue); } protected override DateTime GetDateTime(MemberInfo memberInfo, DateTimeKind kind = DateTimeKind.Unspecified) { return generator.Next(minDate, maxDate, kind); } protected override string GetString(MemberInfo memberInfo) { if (useLoremIpsumForStrings) { int length = generator.Next(1, 10); string[] sentence = new string[length]; for (int i = 0; i < length; i++) { int index = generator.Next(0, allowedChars.Count - 1); sentence[i] = words[index]; } return string.Join(" ", sentence); } else { int length = generator.Next(0, 255); char[] chars = new char[length]; for (int i = 0; i < length; i++) { int index = generator.Next(0, allowedChars.Count - 1); chars[i] = allowedChars[index]; } byte[] bytes = Encoding.UTF8.GetBytes(chars); return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } } protected override bool GetBoolean(MemberInfo memberInfo) { return generator.Next(); } protected override char GetChar(MemberInfo memberInfo) { return generator.Next(char.MinValue, char.MaxValue); } protected override Enum GetEnum(MemberInfo memberInfo) { Type enumType = GetMemberType(memberInfo); var enumValues = GetEnumValues(enumType); return Enum.Parse(enumType,enumValues.GetValue(generator.Next(0, enumValues.Length)).ToString(), true) as Enum; } protected override Guid GetGuid(MemberInfo memberInfo) { return generator.Guid(); } protected override TimeSpan GetTimeSpan(MemberInfo memberInfo) { return new TimeSpan(generator.Long()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using System.Collections.Generic; using System.Threading; using OLEDB.Test.ModuleCore; using XmlCoreTest.Common; namespace XmlReaderTest.Common { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadToNextSibling : TCXMLReaderBaseGeneral { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test 1", Pri = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test 2", Pri = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test 3", Pri = 0, Params = new object[] { "NS" })] public int v() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); DataReader.ReadToNextSibling("elem"); if (DataReader.HasAttributes) { CError.Compare(DataReader.GetAttribute("att"), "1", "Not the expected attribute"); } else { CError.WriteLine("Positioned on wrong element"); DumpStat(); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("elem", "elem"); DataReader.ReadToNextSibling("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("att") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } else { CError.WriteLine("Positioned on wrong element"); DumpStat(); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("e:elem"); DataReader.ReadToNextSibling("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { CError.WriteLine("Positioned on wrong element, not on DNS"); return TEST_FAIL; } } else { CError.WriteLine("Positioned on wrong element"); DumpStat(); return TEST_FAIL; } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("Read on a deep tree atleast more than 4K boundary", Pri = 2)] public int v2() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (mnw.GetNodes().Length < 4096); mnw.PutText("<a/><b/>"); mnw.Finish(); CError.WriteIgnore(mnw.GetNodes() + "\n"); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_1"); CError.Compare(DataReader.ReadToDescendant("a"), true, "Couldnt go to Descendant"); int depth = DataReader.Depth; CError.Compare(DataReader.ReadToNextSibling("b"), true, "Couldnt go to NextSibling"); CError.Compare(DataReader.Depth, depth, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read on a deep tree with more than 65536 elems", Pri = 2)] public int v2_1() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); int count = 0; do { mnw.PutPattern("E/"); count++; } while (count < 65536); mnw.PutText("<a/><b/>"); mnw.Finish(); CError.WriteIgnore(mnw.GetNodes() + "\n"); ReloadSource(new StringReader(mnw.GetNodes())); DataReader.PositionOnElement("ELEMENT_0"); CError.Compare(DataReader.ReadToDescendant("a"), "Couldnt go to Descendant"); int depth = DataReader.Depth; CError.Compare(DataReader.ReadToNextSibling("b"), "Couldnt go to NextSibling"); CError.Compare(DataReader.Depth, depth, "Depth is not correct"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Nodetype is not correct"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } //[Variation("Read to next sibling with same names 1", Pri = 1, Params = new object[] { "NNS", "<root><a att='1'/><a att='2'/><a att='3'/></root>" })] //[Variation("Read on next sibling with same names 2", Pri = 1, Params = new object[] { "DNS", "<root xmlns='a'><a att='1'/><a att='2'/><a att='3'/></root>" })] //[Variation("Read on next sibling with same names 3", Pri = 1, Params = new object[] { "NS", "<root xmlns:a='a'><a:a att='1'/><a:a att='2'/><a:a att='3'/></root>" })] public int v3() { string type = CurVariation.Params[0].ToString(); string xml = CurVariation.Params[1].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(xml)); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); //Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("a"); DataReader.ReadToNextSibling("a"); DataReader.ReadToNextSibling("a"); CError.Compare(DataReader.GetAttribute("att"), "3", "Wrong node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToDescendant("a", "a"); DataReader.ReadToNextSibling("a", "a"); DataReader.ReadToNextSibling("a", "a"); CError.Compare(DataReader.GetAttribute("att"), "3", "Wrong node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToDescendant("a:a"); DataReader.ReadToNextSibling("a:a"); DataReader.ReadToNextSibling("a:a"); CError.Compare(DataReader.GetAttribute("att"), "3", "Wrong node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("If name not found, stop at end element of the subtree", Pri = 1)] public int v4() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("elem"); int depth = DataReader.Depth; CError.Compare(DataReader.ReadToNextSibling("abc"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); CError.Compare(DataReader.Depth, depth - 1, "Wrong Depth"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Positioning on a level and try to find the name which is on a level higher", Pri = 1)] public int v5() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToNextSibling("child1"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); DataReader.PositionOnElement("child3"); CError.Compare(DataReader.ReadToNextSibling("child2", "child2"), false, "Reader returned true for an invalid name,ns"); CError.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type for name,ns"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to next sibling on one level and again to level below it", Pri = 1)] public int v6() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToDescendant("elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToNextSibling("elem", "elem"), true, "Cant find elem,elem"); CError.Compare(DataReader.ReadToNextSibling("e:elem"), true, "Cant find e:elem"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Call from different nodetypes", Pri = 1)] public int v12() { ReloadSource(new StringReader(_xmlStr)); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { CError.WriteLine(DataReader.NodeType.ToString()); CError.Compare(DataReader.ReadToNextSibling("abc"), false, "Fails on node"); } else { if (DataReader.HasAttributes) { while (DataReader.MoveToNextAttribute()) { CError.Compare(DataReader.ReadToNextSibling("abc"), false, "Fails on attribute node"); } } } } DataReader.Close(); return TEST_PASS; } [Variation("Pass null to both arguments throws ArgumentException", Pri = 2)] public int v16() { ReloadSource(new StringReader("<root><e/></root>")); DataReader.Read(); try { DataReader.ReadToNextSibling(null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } try { DataReader.ReadToNextSibling("e", null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Different names, same uri works correctly", Pri = 2)] public int v17() { ReloadSource(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); DataReader.ReadToDescendant("child1", "foo"); DataReader.ReadToNextSibling("child1", "bar"); CError.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } } }
using System; using System.Collections.Generic; using System.IO; using LightIndexer.Lucene; using Lucene.Net.Analysis; using Lucene.Net.Index; using Lucene.Net.Search; using Lucene.Net.Store; using Directory = Lucene.Net.Store.Directory; using log4net; namespace LightIndexer.Config { /// <summary> /// Class provides methods for work with index /// </summary> public sealed class IndexManager : IDisposable { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private object _lock = new object(); private readonly DirectoryType directoryType; private readonly string directoryPath; private Directory _directory; private IndexReader _indexReader; private Searcher _searcher; // maximum terms amount, lucene default is 10000 private const int MAX_FIELD_LENGTH = 50000; /// <summary> /// Static ctor. Initializes Lucene parameters. /// </summary> static IndexManager() { // this allows us make really long queries // we need it for proper work of phrase queries BooleanQuery.MaxClauseCount = int.MaxValue; } internal IndexManager(DirectoryType directoryType, string directoryPath) { this.directoryType = directoryType; this.directoryPath = directoryPath; } /// <summary> /// Calls Close() on Directory, IndexReader and Search object instances. /// Used to refresh IndexReader. Could be used for releasing resources as well. /// </summary> internal void Close() { // sync lock (_lock) { Dispose(true); } } /// <summary> /// Gets an instance of <see cref="Directory"/> configured against the configuration /// </summary> private Directory GetDirectory(DirectoryType directoryType, string directoryPath) { lock (_lock) { if (_directory == null) { switch (directoryType) { case DirectoryType.RAM: _directory = new RAMDirectory(); break; case DirectoryType.DISK: { _directory = _InitializeDirectory(directoryPath); // if path doesn't exist we create an empty index and close it // so we'll have pre-created index if (!System.IO.Directory.Exists(directoryPath)) { //this is empty intentionally, all the magic happens in usings using (_InitializeDirectory(directoryPath)) using (_InitializeWriter(_directory, GetAnalyzer(), true)) ; } break; } default: throw new InvalidOperationException("can't initialize lucene directory"); } } return _directory; } } private static FSDirectory _InitializeDirectory(string dirPath) { return FSDirectory.Open(new DirectoryInfo(dirPath), new SimpleFSLockFactory()); } /// <summary> /// Get the new instance of <see cref="Analyzer"/> /// Now it uses <see cref="WhitespaceAnalyzerLowerCase"/> /// </summary> internal Analyzer GetAnalyzer() { return new WhitespaceAnalyzerLowerCase(); } /// <summary> /// Get the new instance of <see cref="WhitespaceAnalyzerLowerCase"/> /// </summary> internal Analyzer GetAnalyzerLowerCase() { return new WhitespaceAnalyzerLowerCase(); } /// <summary> /// Opens an IndexReader. Next call returns the same instance. /// Use Close() method to reset indexreader. /// </summary> public IndexReader GetOpenIndexReader() { lock (_lock) { if (_indexReader == null) { _indexReader = IndexReader.Open(GetDirectory(directoryType, directoryPath), true); } } return _indexReader; } /// <summary> /// Gets an <see cref="IndexSearcher"/> instance. Next call returns the same instance. /// Use Close() to reset. /// </summary> internal Searcher GetSearcher() { lock (_lock) { if (_searcher == null) { _searcher = new IndexSearcher(GetOpenIndexReader()); } } return _searcher; } /// <summary> /// Instantiate <see cref="IndexWriter"/> according to application configuration. /// </summary> /// <returns>new instance of <see cref="IndexWriter"/></returns> internal IndexWriter OpenIndexWriter() { return _InitializeWriter(GetDirectory(directoryType, directoryPath), GetAnalyzer(), false); } public void DeleteItems(IEnumerable<string> paths) { lock (_lock) { using (var w = _InitializeWriter(GetDirectory(directoryType, directoryPath), GetAnalyzer(), false)) { w.DeleteDocuments(QueryBuilder.MakeQueryForDelete(paths)); w.Commit(); Refresh(); } } } public void DeleteIndex() { lock (_lock) { using (var w = _InitializeWriter(GetDirectory(directoryType, directoryPath), GetAnalyzer(), true)) { w.Commit(); } Refresh(); } } private IndexWriter _InitializeWriter(Directory directory, Analyzer analyzer, bool create) { try { var writer = new IndexWriter(directory, analyzer, create, IndexWriter.MaxFieldLength.LIMITED); writer.SetMaxFieldLength(MAX_FIELD_LENGTH); //writer.SetTermIndexInterval(1024); return writer; } catch (Exception ex) { log.Error("Couldn't initialize writer.", ex); throw; } } private void Refresh() { if (_directory != null) { _directory.Dispose(); _directory = null; } if (_indexReader != null) { _indexReader.Dispose(); _indexReader = null; } if (_searcher != null) { _searcher.Dispose(); _searcher = null; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool isDisposable) { if (!isDisposable) { return; } if (_directory != null) { _directory.Dispose(); _directory = null; } if (_indexReader != null) { _indexReader.Dispose(); _indexReader = null; } if (_searcher != null) { _searcher.Dispose(); _searcher = null; } } ~IndexManager() { Dispose(false); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 11.0Release // Tag = $Name: AKW11_000 $ //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the Goal profile message. /// </summary> public class GoalMesg : Mesg { #region Fields #endregion #region Constructors public GoalMesg() : base(Profile.mesgs[Profile.GoalIndex]) { } public GoalMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Sport field</summary> /// <returns>Returns nullable Sport enum representing the Sport field</returns> public Sport? GetSport() { object obj = GetFieldValue(0, 0, Fit.SubfieldIndexMainField); Sport? value = obj == null ? (Sport?)null : (Sport)obj; return value; } /// <summary> /// Set Sport field</summary> /// <param name="sport_">Nullable field value to be set</param> public void SetSport(Sport? sport_) { SetFieldValue(0, 0, sport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SubSport field</summary> /// <returns>Returns nullable SubSport enum representing the SubSport field</returns> public SubSport? GetSubSport() { object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField); SubSport? value = obj == null ? (SubSport?)null : (SubSport)obj; return value; } /// <summary> /// Set SubSport field</summary> /// <param name="subSport_">Nullable field value to be set</param> public void SetSubSport(SubSport? subSport_) { SetFieldValue(1, 0, subSport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StartDate field</summary> /// <returns>Returns DateTime representing the StartDate field</returns> public DateTime GetStartDate() { return TimestampToDateTime((uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set StartDate field</summary> /// <param name="startDate_">Nullable field value to be set</param> public void SetStartDate(DateTime startDate_) { SetFieldValue(2, 0, startDate_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the EndDate field</summary> /// <returns>Returns DateTime representing the EndDate field</returns> public DateTime GetEndDate() { return TimestampToDateTime((uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set EndDate field</summary> /// <param name="endDate_">Nullable field value to be set</param> public void SetEndDate(DateTime endDate_) { SetFieldValue(3, 0, endDate_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Type field</summary> /// <returns>Returns nullable Goal enum representing the Type field</returns> new public Goal? GetType() { object obj = GetFieldValue(4, 0, Fit.SubfieldIndexMainField); Goal? value = obj == null ? (Goal?)null : (Goal)obj; return value; } /// <summary> /// Set Type field</summary> /// <param name="type_">Nullable field value to be set</param> public void SetType(Goal? type_) { SetFieldValue(4, 0, type_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Value field</summary> /// <returns>Returns nullable uint representing the Value field</returns> public uint? GetValue() { return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Value field</summary> /// <param name="value_">Nullable field value to be set</param> public void SetValue(uint? value_) { SetFieldValue(5, 0, value_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Repeat field</summary> /// <returns>Returns nullable Bool enum representing the Repeat field</returns> public Bool? GetRepeat() { object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Repeat field</summary> /// <param name="repeat_">Nullable field value to be set</param> public void SetRepeat(Bool? repeat_) { SetFieldValue(6, 0, repeat_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TargetValue field</summary> /// <returns>Returns nullable uint representing the TargetValue field</returns> public uint? GetTargetValue() { return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TargetValue field</summary> /// <param name="targetValue_">Nullable field value to be set</param> public void SetTargetValue(uint? targetValue_) { SetFieldValue(7, 0, targetValue_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Recurrence field</summary> /// <returns>Returns nullable GoalRecurrence enum representing the Recurrence field</returns> public GoalRecurrence? GetRecurrence() { object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField); GoalRecurrence? value = obj == null ? (GoalRecurrence?)null : (GoalRecurrence)obj; return value; } /// <summary> /// Set Recurrence field</summary> /// <param name="recurrence_">Nullable field value to be set</param> public void SetRecurrence(GoalRecurrence? recurrence_) { SetFieldValue(8, 0, recurrence_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RecurrenceValue field</summary> /// <returns>Returns nullable ushort representing the RecurrenceValue field</returns> public ushort? GetRecurrenceValue() { return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RecurrenceValue field</summary> /// <param name="recurrenceValue_">Nullable field value to be set</param> public void SetRecurrenceValue(ushort? recurrenceValue_) { SetFieldValue(9, 0, recurrenceValue_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Enabled field</summary> /// <returns>Returns nullable Bool enum representing the Enabled field</returns> public Bool? GetEnabled() { object obj = GetFieldValue(10, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Enabled field</summary> /// <param name="enabled_">Nullable field value to be set</param> public void SetEnabled(Bool? enabled_) { SetFieldValue(10, 0, enabled_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// Created by Paul Gonzalez Becerra using System; using Saserdote.DataSystems; using Saserdote.GamingServices; using Saserdote.Graphics; using Saserdote.Input; using Saserdote.Mathematics; using Saserdote.Text; namespace Saserdote.UI { public class GUIComponent { #region --- Field Variables --- // Variables protected Point2i pLocation; protected Size2i pSize; protected Size2i pMinSize; protected Size2i pMaxSize; protected TexCoord pTopLeftTexCoord; protected TexCoord pBottomRightTexCoord; protected Texture pTexture; protected Color pBackColor; protected Color pForeColor; protected Color pDisabledColor; protected Color pHoveredColor; protected Color pPressedColor; protected bool pSuppressColors; protected Font font; protected string pText; protected string pTag; protected bool pVisible; protected bool pEnabled; protected GUISprite pSprite; protected bool bHover; public byte click; protected MouseState tempClickState; internal GUIContainer parent; internal bool pFocused; internal int pTabIndex; internal GUI gui; #endregion // Field Variables #region --- Constructors --- public GUIComponent() { pLocation= Point2i.ORIGIN; pSize= Size2i.NO_SIZE; pMinSize= Size2i.NO_SIZE; pMaxSize= new Size2i(int.MaxValue, int.MaxValue); pTexture= Texture.NULL; pBackColor= new Color(1f); pForeColor= new Color(0f); pDisabledColor= new Color(0.5f); pHoveredColor= new Color(0, 128, 255); pPressedColor= new Color(255, 128, 0); pSuppressColors= false; pTopLeftTexCoord= new TexCoord(0f, 0f); pBottomRightTexCoord= new TexCoord(1f, 1f); font= null; pText= ""; pTag= ""; pVisible= true; pEnabled= true; bHover= false; click= 0; pSprite= new GUISprite(); pFocused= false; pTabIndex= 0; parent= null; gui= null; parent= null; tempClickState= MouseState.getEmpty(); pSprite.resize(pLocation, pSize); } #endregion // Constructors #region --- Properties --- // Gets and sets the location of the component public Point2i location { get { return pLocation; } set { pLocation= value; callLocationChanged(); } } // Gets and sets the size of the component public Size2i size { get { return pSize; } set { pSize= value; callSizeChanged(); } } // Gets and sets the minimum size of the component public Size2i minSize { get { return pMinSize; } set { pMinSize= value; restructureSizeRestraints(true); if(onMinSizeChanged!= null) onMinSizeChanged(this); } } // Gets and sets the maximum size of the component public Size2i maxSize { get { return pMaxSize; } set { pMaxSize= value; restructureSizeRestraints(false); if(onMaxSizeChanged!= null) onMaxSizeChanged(this); } } // Gets and sets the top left texture coordinates that the sprite uses public TexCoord topLeftTexCoord { get { return pTopLeftTexCoord; } set { pTopLeftTexCoord= value; restructureTexCoord(onTopLeftTexCoordChanged); } } // Gets and sets the bottom right texture coordinates that the sprite uses public TexCoord bottomRightTexCoord { get { return pBottomRightTexCoord; } set { pBottomRightTexCoord= value; restructureTexCoord(onBottomRightTexCoordChanged); } } // Gets and sets the background color of the component public Color backColor { get { return pBackColor; } set { pBackColor= value; if(pSuppressColors) suppressColors(pBackColor); else { if(onBackColorChanged!= null) onBackColorChanged(this); } } } // Gets and sets the foreground color of the component public Color foreColor { get { return pForeColor; } set { pForeColor= value; if(onForeColorChanged!= null) onForeColorChanged(this); } } // Gets and sets the disabled color of the component public Color disabledColor { get { return pDisabledColor; } set { pDisabledColor= value; if(onDisabledColorChanged!= null) onDisabledColorChanged(this); } } // Gets and sets the hovered color of the component public Color hoveredColor { get { return pHoveredColor; } set { pHoveredColor= value; if(pSuppressColors) suppressColors(pHoveredColor); else { if(onHoveredColorChanged!= null) onHoveredColorChanged(this); } } } // Gets and sets the hovered color of the component public Color pressedColor { get { return pPressedColor; } set { pPressedColor= value; if(pSuppressColors) suppressColors(pPressedColor); else { if(onPressedColorChanged!= null) onPressedColorChanged(this); } } } // Gets and sets if the pressed and hover colors will be forced to use the same back color regardless public bool bSuppressColors { get { return pSuppressColors; } set { pSuppressColors= value; if(pSuppressColors) suppressColors(pBackColor); } } // Gets and sets the text of the component public string text { get { return pText; } set { pText= value; if(onTextChanged!= null) onTextChanged(this); } } // Gets and sets the tag of the component public string tag { get { return pTag; } set { pTag= value; if(onTagChanged!= null) onTagChanged(this); } } // Gets and sets if the component is visible or not public bool bVisible { get { return pVisible; } set { pVisible= value; if(onVisibleChanged!= null) onVisibleChanged(this); } } // Gets and sets if the component is enabled or not public bool bEnabled { get { return pEnabled; } set { pEnabled= value; if(onEnabledChanged!= null) onEnabledChanged(this); } } // Gets and sets the texture of the gui component's sprite public Texture texture { get { return pTexture; } set { pTexture= value; if(pSprite!= null) pSprite.texture= pTexture; if(onTextureChanged!= null) onTextureChanged(this); } } #endregion // Properties #region --- Events --- // Event for when the mouse has been clicked public event GActionEvent<MouseState> onMouseClick; // Event for when the mouse has entered the component public event GActionEvent<MouseState> onMouseEnter; // Event for when the mouse has left the component public event GActionEvent<MouseState> onMouseLeave; // Event for when the mouse is hovering over the component public event GActionEvent<MouseState> onMouseHover; // Event for when there is a key press public event GActionEvent<KeyboardState> onKeyPress; // Event for when there is a gamepad press public event GActionEvent<GamepadState> onGamepadPress; // Event for when the component has gained focus public event GEvent onGotFocus; // Event for when the component has lost focus public event GEvent onLostFocus; // Event for when the component has moved public event GEvent onMove; // Event for when the component has resized public event GEvent onResize; // Event for when the component has its visibility changed public event GEvent onVisibleChanged; // Event for when the component has its enability changed public event GEvent onEnabledChanged; // Event for when the component has its text changed public event GEvent onTextChanged; // Event for when the component has its tag changed public event GEvent onTagChanged; // Event for when the component has its back color changed public event GEvent onBackColorChanged; // Event for when the component has its fore color changed public event GEvent onForeColorChanged; // Event for when the component has its disabled color changed public event GEvent onDisabledColorChanged; // Event for when the component has its hovered color changed public event GEvent onHoveredColorChanged; // Event for when the component has its pressed color changed public event GEvent onPressedColorChanged; // Event for when the component has is minimum size changed public event GEvent onMinSizeChanged; // Evenet for when the component has is maximum size changed public event GEvent onMaxSizeChanged; // Event for when the component's texture has changed public event GEvent onTextureChanged; // Event for when the component's top left texture coordinates has changed public event GEvent onTopLeftTexCoordChanged; // Event for when the component's bottom right texture coordinates has changed public event GEvent onBottomRightTexCoordChanged; #endregion // Events #region --- Methods --- // Calls the given event protected virtual void call(string eventName) { switch(eventName) { default: break; } } // Calls the given params event protected virtual void call<T>(string eventName, T args) { switch(eventName) { case "onMouseClick": if(typeof(T)== typeof(MouseState)) onMouseClick(this, (MouseState)((object)(args))); break; case "onMouseEnter": if(typeof(T)== typeof(MouseState)) onMouseEnter(this, (MouseState)((object)(args))); break; case "onMouseLeave": if(typeof(T)== typeof(MouseState)) onMouseLeave(this, (MouseState)((object)(args))); break; case "onMouseHover": if(typeof(T)== typeof(MouseState)) onMouseHover(this, (MouseState)((object)(args))); break; case "onKeyPress": if(typeof(T)== typeof(KeyboardState)) onKeyPress(this, (KeyboardState)((object)(args))); break; case "onGamepadPress": if(typeof(T)== typeof(GamepadState)) onGamepadPress(this, (GamepadState)((object)(args))); break; } } // Finds if the given event name is null protected virtual bool isEventNull(string eventName) { switch(eventName) { case "onMouseClick": return (onMouseClick== null); case "onMouseEnter": return (onMouseEnter== null); case "onMouseLeave": return (onMouseLeave== null); case "onMouseHover": return (onMouseHover== null); case "onKeyPress": return (onKeyPress== null); case "onGamepadPress": return (onGamepadPress== null); } return false; } // Renders the gui component public virtual void render(ref GameTime time, ref Game game) { if(!bVisible) return; if(pSprite== null) return; if(!pEnabled) renderDisabled(ref time, ref game); else if(bHover) renderHovered(ref time, ref game); else if(click!= 0) renderPressed(ref time, ref game); else renderNormal(ref time, ref game); } // Renders the gui component normally protected virtual void renderNormal(ref GameTime time, ref Game game) { if(pSprite.getColors()[0]!= pBackColor) pSprite.applyColor(pBackColor); game.graphics.render(pSprite); } // Renders the gui component when it is disabled protected virtual void renderDisabled(ref GameTime time, ref Game game) { if(pSprite.getColors()[0]!= pDisabledColor) pSprite.applyColor(pDisabledColor); game.graphics.render(pSprite); } // Renders the gui component when it is hovered over protected virtual void renderHovered(ref GameTime time, ref Game game) { if(pSprite.getColors()[0]!= pHoveredColor) pSprite.applyColor(pHoveredColor); game.graphics.render(pSprite); } // Redners the gui component when it is pressed down protected virtual void renderPressed(ref GameTime time, ref Game game) { if(pSprite.getColors()[0]!= pPressedColor) pSprite.applyColor(pPressedColor); game.graphics.render(pSprite); } // Updates the gui component public virtual void update(ref GameTime time, ref Game game) { if(!bVisible) return; } // Handles the gui component's input public virtual void handleInput(ref InputArgs args) { // Variables bool bBounds= false; if(pSprite!= null && pSprite.bvolume!= null) bBounds= pSprite.bvolume.contains(args.mouse.position); if(parent!= null && parent.focusedComp== this) { if(onKeyPress!= null && args.keyboard.size!= 0) onKeyPress(this, args.keyboard); if(onGamepadPress!= null && args.gamepad.buttonsHeld!= GBL.NONE) onGamepadPress(this, args.gamepad); } if(!bBounds) click= 0; if(click!= 0) { if((click&1)!= 0) if(args.isKeyUp(MBL.LMB)) click-= 1; if((click&2)!= 0) if(args.isKeyUp(MBL.MMB)) click-= 2; if((click&4)!= 0) if(args.isKeyUp(MBL.RMB)) click-= 4; if((click&8)!= 0) if(args.isKeyUp(MBL.XB1)) click-= 8; if((click&16)!= 0) if(args.isKeyUp(MBL.XB2)) click-= 16; if(click== 0 && bBounds) { if(onMouseClick!= null) onMouseClick(this, tempClickState); } } if(pEnabled && !bHover && bBounds) { bHover= true; if(onMouseEnter!= null) onMouseEnter(this, args.mouse); } if(pEnabled && bHover && bBounds) { if(onMouseHover!= null) onMouseHover(this, args.mouse); if(click== 0 && parent!= null && parent.focusedComp== this) { if(args.isKeyDown(MBL.LMB)) click+= 1; if(args.isKeyDown(MBL.MMB)) click+= 2; if(args.isKeyDown(MBL.RMB)) click+= 4; if(args.isKeyDown(MBL.XB1)) click+= 8; if(args.isKeyDown(MBL.XB2)) click+= 16; if(click!= 0) tempClickState= args.mouse; } if(parent!= null && parent.focusedComp!= this && parent.focusedComp.click== 0) parent.focusedComp= this; } if(pEnabled && bHover && !bBounds) { if(onMouseLeave!= null) onMouseLeave(this, args.mouse); bHover= false; } } // Sets the gui to the given gui internal virtual void setGUI(ref GUI pmGUI) { gui= pmGUI; if(gui!= null) font= gui.game.loadedFonts["default"]; } // Resizes the sprite of the component internal virtual void resize() { resizeSprite(); } // Gets the mouse coordinates relative to the position of the component public virtual Point2i pointToComponent(Point2i mousePos) { return mousePos; } // Gets the mouse coordinates relative to the position of the screen public virtual Point2i pointToScreen(Point2i mousePos) { return mousePos; } // Resizes the sprite given if it is on a percentage or not private void resizeSprite() { if(pSprite== null) return; pSprite.resize(pLocation, pSize); } // Calls the location changed event and changed the location private void callLocationChanged() { if(parent!= null) pLocation+= parent.location.toVector3(); resizeSprite(); if(onMove!= null) onMove(this); } // Calls the location changed event and changes the location private void callSizeChanged() { resizeSprite(); if(onResize!= null) onResize(this); } // Restructure the size constraints private void restructureSizeRestraints(bool min) { // Variables Size2i[] temp= new Size2i[2]; temp[0]= Mathx.getMostMin(pMinSize, pMaxSize); temp[1]= Mathx.getMostMax(pMinSize, pMaxSize); pMinSize= temp[0]; pMaxSize= temp[1]; } // Restructures the texture coordinates private void restructureTexCoord(GEvent e) { // Variables float[] uv= new float[4]; uv[0]= pTopLeftTexCoord.u; uv[1]= 1f-pTopLeftTexCoord.v; uv[2]= pBottomRightTexCoord.u; uv[3]= 1f-pBottomRightTexCoord.v; pTopLeftTexCoord= new TexCoord(uv[0], uv[1]); pBottomRightTexCoord= new TexCoord(uv[2], uv[3]); if(e!= null) e(this); } // Finds if the given point is within the component's bounds public bool isPointInBounds(Point2i pt) { if(pSprite== null && pSprite.bvolume== null) return false; return (pSprite.bvolume.contains(pt)); } // Sets focus to the gui component public virtual void setFocus() { if(parent== null) return; parent.focusedComp= this; if(onGotFocus!= null) onGotFocus(this); } // Sets the focus to the next component on the set public virtual void setFocusToNextComponent() { if(parent== null) return; /* parent.setFocusOnNext(this); */ } // Sets the focus to the previous component on the set public virtual void setFocusToPrevComponent() { if(parent== null) return; /* parent.setFocusOnPrev(this); */ } // Sets not focused to the gui component public virtual void setUnfocus() { if(parent== null) return; if(parent.focusedComp== this) { parent.focusedComp= null; if(onLostFocus!= null) onLostFocus(this); } } // Resets the background color to it's default state public virtual void resetBackColor() { pBackColor= new Color(1f); if(pSuppressColors) suppressColors(pBackColor); else { if(onBackColorChanged!= null) onBackColorChanged(this); } } // Resets the foreground color to it's default state public virtual void resetForeColor() { pForeColor= new Color(0f); if(onBackColorChanged!= null) onBackColorChanged(this); } // Resets the font to it's default state //public virtual void resetFont(); // Suppresses the hover and pressed colors to look the same as the back color public virtual void suppressColors(Color c) { pBackColor= c; pHoveredColor= c; pPressedColor= c; if(onBackColorChanged!= null) onBackColorChanged(this); } #endregion // Methods } } // End of File
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.DeployedDevices.Fleet { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// Fetch information about a specific Certificate credential in the Fleet. /// </summary> public class FetchCertificateOptions : IOptions<CertificateResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Certificate. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchCertificateOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Certificate. </param> public FetchCertificateOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// Unregister a specific Certificate credential from the Fleet, effectively disallowing any inbound client connections /// that are presenting it. /// </summary> public class DeleteCertificateOptions : IOptions<CertificateResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Certificate. /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteCertificateOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Certificate. </param> public DeleteCertificateOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// Enroll a new Certificate credential to the Fleet, optionally giving it a friendly name and assigning to a Device. /// </summary> public class CreateCertificateOptions : IOptions<CertificateResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// The public certificate data. /// </summary> public string CertificateData { get; } /// <summary> /// The human readable description for this Certificate. /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique identifier of a Device to be authenticated. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new CreateCertificateOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="certificateData"> The public certificate data. </param> public CreateCertificateOptions(string pathFleetSid, string certificateData) { PathFleetSid = pathFleetSid; CertificateData = certificateData; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (CertificateData != null) { p.Add(new KeyValuePair<string, string>("CertificateData", CertificateData)); } if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// Retrieve a list of all Certificate credentials belonging to the Fleet. /// </summary> public class ReadCertificateOptions : ReadOptions<CertificateResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// Find all Certificates authenticating specified Device. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new ReadCertificateOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> public ReadCertificateOptions(string pathFleetSid) { PathFleetSid = pathFleetSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// Update the given properties of a specific Certificate credential in the Fleet, giving it a friendly name or /// assigning to a Device. /// </summary> public class UpdateCertificateOptions : IOptions<CertificateResource> { /// <summary> /// The fleet_sid /// </summary> public string PathFleetSid { get; } /// <summary> /// A string that uniquely identifies the Certificate. /// </summary> public string PathSid { get; } /// <summary> /// The human readable description for this Certificate. /// </summary> public string FriendlyName { get; set; } /// <summary> /// The unique identifier of a Device to be authenticated. /// </summary> public string DeviceSid { get; set; } /// <summary> /// Construct a new UpdateCertificateOptions /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Certificate. </param> public UpdateCertificateOptions(string pathFleetSid, string pathSid) { PathFleetSid = pathFleetSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (DeviceSid != null) { p.Add(new KeyValuePair<string, string>("DeviceSid", DeviceSid.ToString())); } return p; } } }