context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileSystemGlobbing; using Microsoft.Extensions.FileSystemGlobbing.Abstractions; using Microsoft.Extensions.Primitives; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.TagHelpers { public class GlobbingUrlBuilderTest { [Fact] public void ReturnsOnlyStaticUrlWhenPatternDoesntFindAnyMatches() { // Arrange var fileProvider = MakeFileProvider(); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList("/site.css", "**/*.css", excludePattern: null); // Assert Assert.Collection(urlList, url => Assert.Equal("/site.css", url)); } [Fact] public void DedupesStaticUrlAndPatternMatches() { // Arrange var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList("/site.css", "**/*.css", excludePattern: null); // Assert Assert.Collection(urlList, url => Assert.Equal("/site.css", url), url => Assert.Equal("/blank.css", url)); } public static TheoryData OrdersGlobbedMatchResultsCorrectly_Data { get { return new TheoryData<string, FileNode, string[]> { { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("B", new [] { new FileNode("a.css"), new FileNode("b.css"), new FileNode("ba.css"), new FileNode("b", new [] { new FileNode("a.css") }) }), new FileNode("A", new [] { new FileNode("c.css"), new FileNode("d.css") }), new FileNode("a.css") }), /* expectedPaths */ new [] { "/site.css", "/a.css", "/A/c.css", "/A/d.css", "/B/a.css", "/B/b.css", "/B/ba.css", "/B/b/a.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("A", new [] { new FileNode("c.css"), new FileNode("d.css") }), new FileNode("_A", new [] { new FileNode("1.css"), new FileNode("2.css") }), new FileNode("__A", new [] { new FileNode("1.css"), new FileNode("_1.css") }) }), /* expectedPaths */ new [] { "/site.css", "/A/c.css", "/A/d.css", "/_A/1.css", "/_A/2.css", "/__A/1.css", "/__A/_1.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("A", new [] { new FileNode("a.b.css"), new FileNode("a-b.css"), new FileNode("a_b.css"), new FileNode("a.css"), new FileNode("a.c.css") }) }), /* expectedPaths */ new [] { "/site.css", "/A/a.css", "/A/a-b.css", "/A/a.b.css", "/A/a.c.css", "/A/a_b.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("B", new [] { new FileNode("a.bss"), new FileNode("a.css") }), new FileNode("A", new [] { new FileNode("a.css"), new FileNode("a.bss") }) }), /* expectedPaths */ new [] { "/site.css", "/A/a.bss", "/A/a.css", "/B/a.bss", "/B/a.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("B", new [] { new FileNode("site2.css"), new FileNode("site11.css") }), new FileNode("A", new [] { new FileNode("site2.css"), new FileNode("site11.css") }) }), /* expectedPaths */ new [] { "/site.css", "/A/site11.css", "/A/site2.css", "/B/site11.css", "/B/site2.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("B", new [] { new FileNode("site"), new FileNode("site.css") }), new FileNode("A", new [] { new FileNode("site.css"), new FileNode("site") }) }), /* expectedPaths */ new [] { "/site.css", "/A/site", "/A/site.css", "/B/site", "/B/site.css" } }, { /* staticUrl */ "/site.css", /* dirStructure */ new FileNode(null, new [] { new FileNode("B.B", new [] { new FileNode("site"), new FileNode("site.css") }), new FileNode("A.A", new [] { new FileNode("site.css"), new FileNode("site") }) }), /* expectedPaths */ new [] { "/site.css", "/A.A/site", "/A.A/site.css", "/B.B/site", "/B.B/site.css" } } }; } } [Theory] [MemberData(nameof(OrdersGlobbedMatchResultsCorrectly_Data))] public void OrdersGlobbedMatchResultsCorrectly(string staticUrl, FileNode dirStructure, string[] expectedPaths) { // Arrange var fileProvider = MakeFileProvider(dirStructure); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList(staticUrl, "**/*.*", excludePattern: null); // Assert var collectionAssertions = expectedPaths.Select<string, Action<string>>(expected => actual => Assert.Equal(expected, actual)); Assert.Collection(urlList, collectionAssertions.ToArray()); } [Theory] [InlineData("/sub")] [InlineData("/sub/again")] public void ResolvesMatchedUrlsAgainstPathBase(string pathBase) { // Arrange var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = new PathString(pathBase); var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: "**/*.css", excludePattern: null); // Assert Assert.Collection(urlList, url => Assert.Equal($"{pathBase}/blank.css", url), url => Assert.Equal($"{pathBase}/site.css", url)); } [Fact] public void UsesCachedMatchResults() { // Arrange var fileProvider = MakeFileProvider(); var expected = new List<string> { "/blank.css", "/site.css" }; var cache = MakeCache(result: expected); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var actual = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: "**/*.css", excludePattern: null); // Assert Assert.Collection(actual, url => Assert.Equal("/blank.css", url), url => Assert.Equal("/site.css", url)); } [Fact] public void CachesMatchResults() { // Arrange var changeToken = new Mock<IChangeToken>(); var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); Mock.Get(fileProvider).Setup(f => f.Watch(It.IsAny<string>())).Returns(changeToken.Object); var value = new Mock<ICacheEntry>(); value.Setup(c => c.Value).Returns(null); value.Setup(c => c.ExpirationTokens).Returns(new List<IChangeToken>()); var cache = MakeCache(); Mock.Get(cache).Setup(c => c.CreateEntry( /*key*/ It.IsAny<object>())) .Returns((object key) => value.Object) .Verifiable(); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: "**/*.css", excludePattern: null); // Assert Assert.Collection(urlList, url => Assert.Equal("/blank.css", url), url => Assert.Equal("/site.css", url)); Mock.Get(cache).VerifyAll(); } public static TheoryData CommaSeparatedPatternData { get { // Include pattern, expected output return new TheoryData<string, string[]> { { "~/*.css, ~/*.txt", new[] { "/site.css", "/site2.txt" } }, { "*.css, /*.txt", new[] { "/site.css", "/site2.txt" } }, { "\\*.css,~/*.txt", new[] { "/site.css", "/site2.txt" } }, { "~/*.js, *.txt", new[] { "/blank.js", "/site.js", "/site2.txt" } }, { " ~/*.js,*.txt, /*.css", new[] { "/blank.js", "/site.css", "/site.js", "/site2.txt" } }, { "~/blank.js, blank.js,/blank.js, \\blank.js", new[] { "/blank.js" } }, }; } } [Theory] [MemberData(nameof(CommaSeparatedPatternData))] public void HandlesCommaSeparatedPatterns(string includePattern, string[] expectedOutput) { // Arrange var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.js", "site2.txt", "site.js")); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: includePattern, excludePattern: null); // Assert Assert.Equal(expectedOutput, urlList, StringComparer.Ordinal); } [Theory] [InlineData("")] [InlineData("/")] [InlineData(" \\")] [InlineData("~/")] [InlineData(" ~/")] public void TrimsLeadingTildeAndSlashFromPatterns(string prefix) { // Arrange var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var includePatterns = new List<string>(); var excludePatterns = new List<string>(); var matcher = MakeMatcher(includePatterns, excludePatterns); var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); globbingUrlBuilder.MatcherBuilder = () => matcher; // Act var urlList = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: $"{prefix}**/*.css", excludePattern: $"{prefix}**/*.min.css"); // Assert Assert.Collection(includePatterns, pattern => Assert.Equal("**/*.css", pattern)); Assert.Collection(excludePatterns, pattern => Assert.Equal("**/*.min.css", pattern)); } [Theory] [InlineData("~/")] [InlineData("/")] [InlineData("\\")] public void TrimsOnlySingleLeadingSlashOrTildeSlashFromPatterns(string prefix) { // Arrange var leadingSlashes = $"{prefix}{prefix}"; var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); var cache = new MemoryCache(new MemoryCacheOptions()); var requestPathBase = PathString.Empty; var includePatterns = new List<string>(); var excludePatterns = new List<string>(); var matcher = MakeMatcher(includePatterns, excludePatterns); var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); globbingUrlBuilder.MatcherBuilder = () => matcher; // Act var urlList = globbingUrlBuilder.BuildUrlList( staticUrl: null, includePattern: $"{leadingSlashes}**/*.css", excludePattern: $"{leadingSlashes}**/*.min.css"); // Assert Assert.Collection(includePatterns, pattern => Assert.Equal($"{prefix}**/*.css", pattern)); Assert.Collection(excludePatterns, pattern => Assert.Equal($"{prefix}**/*.min.css", pattern)); } [Fact] public void BuildUrlList_AddsToMemoryCache_WithSizeLimit() { // Arrange var cacheEntry = Mock.Of<ICacheEntry>(m => m.ExpirationTokens == new List<IChangeToken>()); var cache = Mock.Of<IMemoryCache>(m => m.CreateEntry(It.IsAny<object>()) == cacheEntry); var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css")); var requestPathBase = PathString.Empty; var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase); // Act var urlList = globbingUrlBuilder.BuildUrlList("/site.css", "**/*.css", excludePattern: null); // Assert Assert.Equal(38, cacheEntry.Size); } public class FileNode { public FileNode(string name) { Name = name; } public FileNode(string name, IList<FileNode> children) { Name = name; Children = children; } public string Name { get; } public IList<FileNode> Children { get; } public bool IsDirectory => Children != null && Children.Any(); } private static IFileInfo MakeFileInfo(string name, bool isDirectory = false) { var fileInfo = new Mock<IFileInfo>(); fileInfo.Setup(f => f.Name).Returns(name); fileInfo.Setup(f => f.IsDirectory).Returns(isDirectory); return fileInfo.Object; } private static IFileProvider MakeFileProvider(FileNode rootNode) { if (rootNode.Children == null || !rootNode.Children.Any()) { throw new ArgumentNullException(nameof(rootNode)); } var fileProvider = new Mock<IFileProvider>(MockBehavior.Strict); fileProvider.Setup(fp => fp.GetDirectoryContents(string.Empty)) .Returns(MakeDirectoryContents(rootNode, fileProvider)); fileProvider.Setup(fp => fp.Watch(It.IsAny<string>())) .Returns(new TestFileChangeToken()); return fileProvider.Object; } private static IDirectoryContents MakeDirectoryContents(FileNode fileNode, Mock<IFileProvider> fileProviderMock) { var children = new List<IFileInfo>(); foreach (var node in fileNode.Children) { children.Add(MakeFileInfo(node.Name, node.IsDirectory)); if (node.IsDirectory) { var subPath = fileNode.Name != null ? (fileNode.Name + "/" + node.Name) : node.Name; fileProviderMock.Setup(fp => fp.GetDirectoryContents(subPath)) .Returns(MakeDirectoryContents(node, fileProviderMock)); } } var directoryContents = new Mock<IDirectoryContents>(); directoryContents.Setup(dc => dc.GetEnumerator()).Returns(children.GetEnumerator()); return directoryContents.Object; } private static IDirectoryContents MakeDirectoryContents(params string[] fileNames) { var files = fileNames.Select(name => MakeFileInfo(name)); var directoryContents = new Mock<IDirectoryContents>(); directoryContents.Setup(dc => dc.GetEnumerator()).Returns(files.GetEnumerator()); return directoryContents.Object; } private static IFileProvider MakeFileProvider(IDirectoryContents directoryContents = null) { if (directoryContents == null) { directoryContents = MakeDirectoryContents(); } var fileProvider = new Mock<IFileProvider>(); fileProvider.Setup(fp => fp.GetDirectoryContents(It.IsAny<string>())) .Returns(directoryContents); fileProvider.Setup(fp => fp.Watch(It.IsAny<string>())) .Returns(new TestFileChangeToken()); return fileProvider.Object; } private static IMemoryCache MakeCache(object result = null) { var cache = new Mock<IMemoryCache>(); cache.Setup(c => c.TryGetValue(It.IsAny<object>(), out result)) .Returns(result != null); return cache.Object; } private static Matcher MakeMatcher(List<string> includePatterns, List<string> excludePatterns) { var matcher = new Mock<Matcher>(); matcher.Setup(m => m.AddInclude(It.IsAny<string>())) .Returns<string>(pattern => { includePatterns.Add(pattern); return matcher.Object; }); matcher.Setup(m => m.AddExclude(It.IsAny<string>())) .Returns<string>(pattern => { excludePatterns.Add(pattern); return matcher.Object; }); var patternMatchingResult = new PatternMatchingResult(Enumerable.Empty<FilePatternMatch>()); matcher.Setup(m => m.Execute(It.IsAny<DirectoryInfoBase>())).Returns(patternMatchingResult); return matcher.Object; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class GetAllKeysTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; NameValueCollection nvc; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count string[] ks; // keys array // initialize IntStrings intl = new IntlStrings(); // [] NameValueCollection is constructed as expected //----------------------------------------------------------------- nvc = new NameValueCollection(); // [] AllKeys on empty collection // if (nvc.Count > 0) nvc.Clear(); ks = nvc.AllKeys; if (ks.Length != 0) { Assert.False(true, string.Format("Error, number of keys is {0} instead of 0", ks.Length)); } // [] AllKeys on collection filled with simple strings // for (int i = 0; i < values.Length; i++) { cnt = nvc.Count; nvc.Add(keys[i], values[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added item // if (nvc.AllKeys.Length != cnt + 1) { Assert.False(true, string.Format("Error, incorrects Keys array", i)); } if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } } // // Intl strings // [] AllKeys on collection filled with Intl strings // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = nvc.Count; nvc.Add(intlValues[i + len], intlValues[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added item // if (nvc.AllKeys.Length != cnt + 1) { Assert.False(true, string.Format("Error, wrong keys array", i)); } if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0) { Assert.False(true, string.Format("Error, Array doesn't contain key of new item", i)); } } // // [] Case sensitivity // Casing doesn't change ( keys are not converted to lower!) // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } nvc.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = nvc.Count; // add uppercase items nvc.Add(intlValues[i + len], intlValues[i]); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (nvc.AllKeys.Length != cnt + 1) { Assert.False(true, string.Format("Error, wrong keys array", i)); } if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // key is not converted to lower if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0) { Assert.False(true, string.Format("Error, key was converted to lower", i)); } } // // [] AllKeys for multiple values with the same key // nvc.Clear(); len = values.Length; string k = "keykey"; for (int i = 0; i < len; i++) { nvc.Add(k, "Value" + i); if (nvc.Count != 1) { Assert.False(true, string.Format("Error, count is {0} instead of 1", nvc.Count, i)); } if (nvc.AllKeys.Length != 1) { Assert.False(true, string.Format("Error, AllKeys contains {0} instead of 1", nvc.AllKeys.Length, i)); } if (Array.IndexOf(nvc.AllKeys, k) != 0) { Assert.False(true, string.Format("Error, wrong key", i)); } } // access the item // string[] vals = nvc.GetValues(k); if (vals.Length != len) { Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, 1)); } // // [] AllKeys when collection has null value // k = "kk"; nvc.Remove(k); // make sure there is no such item already cnt = nvc.Count; nvc.Add(k, null); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1)); } if (Array.IndexOf(nvc.AllKeys, k) < 0) { Assert.False(true, "Error, collection doesn't contain key of new item"); } // verify that collection contains null // if (nvc[k] != null) { Assert.False(true, "Error, returned non-null on place of null"); } // // [] Allkeys when item with null key is present // nvc.Remove(null); cnt = nvc.Count; nvc.Add(null, "item"); if (nvc.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1)); } if (Array.IndexOf(nvc.AllKeys, null) < 0) { Assert.False(true, "Error, collection doesn't contain null key "); } // verify that collection contains null // if (nvc[null] != "item") { Assert.False(true, "Error, returned wrong value at null key"); } } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.6.9. Change state information with the data contained in this. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class SetDataPdu : SimulationManagementFamilyPdu, IEquatable<SetDataPdu> { /// <summary> /// ID of request /// </summary> private uint _requestID; /// <summary> /// padding /// </summary> private uint _padding1; /// <summary> /// Number of fixed datum records /// </summary> private uint _numberOfFixedDatumRecords; /// <summary> /// Number of variable datum records /// </summary> private uint _numberOfVariableDatumRecords; /// <summary> /// variable length list of fixed datums /// </summary> private List<FixedDatum> _fixedDatums = new List<FixedDatum>(); /// <summary> /// variable length list of variable length datums /// </summary> private List<VariableDatum> _variableDatums = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="SetDataPdu"/> class. /// </summary> public SetDataPdu() { PduType = (byte)19; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(SetDataPdu left, SetDataPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(SetDataPdu left, SetDataPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 4; // this._requestID marshalSize += 4; // this._padding1 marshalSize += 4; // this._numberOfFixedDatumRecords marshalSize += 4; // this._numberOfVariableDatumRecords for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the ID of request /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(uint), ElementName = "padding1")] public uint Padding1 { get { return this._padding1; } set { this._padding1 = value; } } /// <summary> /// Gets or sets the Number of fixed datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfFixedDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfFixedDatumRecords")] public uint NumberOfFixedDatumRecords { get { return this._numberOfFixedDatumRecords; } set { this._numberOfFixedDatumRecords = value; } } /// <summary> /// Gets or sets the Number of variable datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")] public uint NumberOfVariableDatumRecords { get { return this._numberOfVariableDatumRecords; } set { this._numberOfVariableDatumRecords = value; } } /// <summary> /// Gets the variable length list of fixed datums /// </summary> [XmlElement(ElementName = "fixedDatumsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatums { get { return this._fixedDatums; } } /// <summary> /// Gets the variable length list of variable length datums /// </summary> [XmlElement(ElementName = "variableDatumsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatums { get { return this._variableDatums; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedInt((uint)this._requestID); dos.WriteUnsignedInt((uint)this._padding1); dos.WriteUnsignedInt((uint)this._fixedDatums.Count); dos.WriteUnsignedInt((uint)this._variableDatums.Count); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._requestID = dis.ReadUnsignedInt(); this._padding1 = dis.ReadUnsignedInt(); this._numberOfFixedDatumRecords = dis.ReadUnsignedInt(); this._numberOfVariableDatumRecords = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.NumberOfFixedDatumRecords; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatums.Add(anX); } for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatums.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<SetDataPdu>"); base.Reflection(sb); try { sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("<padding1 type=\"uint\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>"); sb.AppendLine("<fixedDatums type=\"uint\">" + this._fixedDatums.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatums>"); sb.AppendLine("<variableDatums type=\"uint\">" + this._variableDatums.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatums>"); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { sb.AppendLine("<fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { sb.AppendLine("<variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</SetDataPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as SetDataPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(SetDataPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._requestID != obj._requestID) { ivarsEqual = false; } if (this._padding1 != obj._padding1) { ivarsEqual = false; } if (this._numberOfFixedDatumRecords != obj._numberOfFixedDatumRecords) { ivarsEqual = false; } if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords) { ivarsEqual = false; } if (this._fixedDatums.Count != obj._fixedDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { if (!this._fixedDatums[idx].Equals(obj._fixedDatums[idx])) { ivarsEqual = false; } } } if (this._variableDatums.Count != obj._variableDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { if (!this._variableDatums[idx].Equals(obj._variableDatums[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); result = GenerateHash(result) ^ this._padding1.GetHashCode(); result = GenerateHash(result) ^ this._numberOfFixedDatumRecords.GetHashCode(); result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode(); if (this._fixedDatums.Count > 0) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatums[idx].GetHashCode(); } } if (this._variableDatums.Count > 0) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { result = GenerateHash(result) ^ this._variableDatums[idx].GetHashCode(); } } return result; } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; namespace WebApplication2 { /// <summary> /// Summary description for Templates. /// </summary> public partial class Templates : System.Web.UI.Page { private string OrgIdT; private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Main(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Select); } #endregion private void Load_Main() { lblOrg.Text=Session["OrgName"].ToString(); if (!IsPostBack) { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveTemplates"; cmd.Parameters.Add("@MenuType", SqlDbType.NVarChar); cmd.Parameters["@MenuType"].Value=Session["MenuType"].ToString(); cmd.Connection=this.epsDbConn; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"UserOrg"); Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); } } private void Done () { Response.Redirect (strURL + "frmMain.aspx?"); } private void Select(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { OrgIdT=(e.Item.Cells[0].Text); TemplateOrgs(); TemplateProcesses(); TemplateProcessSteps(); TemplateStaffing(); TemplateResources(); TemplateResourceInputs(); TemplateAssess(); TemplateEnd(); } private void Exit() { Response.Redirect (strURL + "frmStart.aspx?"); } private void TemplateEnd() { DataGrid1.Visible=false; btnNoTemplates.Visible=false; lblOK.Text="Congratulations. Emergency Plans have been successfully prepared for " + Session["OrgName"].ToString().Trim() + ". Please make a note of your User Id and keep in a secure place" + " for future reference." + " Your User Id is: " + "'" + Session["UserId"].ToString().Trim() + "'." + " Your Password is: " + "'" + Session["Password"].ToString().Trim() + "'." + "Press button to Exit"; btnExit.Visible=true; } private void TemplateOrgs() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateOrgs"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdT", SqlDbType.Int); cmd.Parameters["@OrgIdT"].Value=OrgIdT; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } public void TemplateProcesses() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateProcEmergency"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void TemplateProcessSteps() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateProcessSteps"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void TemplateStaffing() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateStaffing"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void TemplateResources() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateResources"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void TemplateResourceInputs() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateResourceInputs"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void TemplateAssess() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_TemplateAssess"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } protected void btnNoTemplates_Click(object sender, System.EventArgs e) { Exit(); } protected void btnExit_Click(object sender, System.EventArgs e) { Exit(); } } }
// 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 Microsoft.Win32; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { public static Version OSXVersion => throw new PlatformNotSupportedException(); public static Version OpenSslVersion => throw new PlatformNotSupportedException(); public static bool IsDrawingSupported => IsNotWindowsNanoServer && IsNotWindowsServerCore; public static bool IsSoundPlaySupported => IsNotWindowsNanoServer; public static bool IsSuperUser => throw new PlatformNotSupportedException(); public static bool IsCentos6 => false; public static bool IsOpenSUSE => false; public static bool IsUbuntu => false; public static bool IsDebian => false; public static bool IsAlpine => false; public static bool IsDebian8 => false; public static bool IsUbuntu1404 => false; public static bool IsUbuntu1604 => false; public static bool IsUbuntu1704 => false; public static bool IsUbuntu1710 => false; public static bool IsUbuntu1710OrHigher => false; public static bool IsUbuntu1804 => false; public static bool IsUbuntu1810OrHigher => false; public static bool IsTizen => false; public static bool IsNotFedoraOrRedHatFamily => true; public static bool IsFedora => false; public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase)); public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase); public static int WindowsVersion => (int)GetWindowsVersion(); public static bool IsMacOsHighSierraOrHigher { get; } = false; public static bool IsMacOsMojaveOrHigher { get; } = false; public static Version ICUVersion => new Version(0, 0, 0, 0); public static bool IsRedHatFamily => false; public static bool IsNotRedHatFamily => true; public static bool IsRedHatFamily6 => false; public static bool IsRedHatFamily7 => false; public static bool IsNotRedHatFamily6 => true; public static bool IsInContainer => !String.IsNullOrEmpty(GetContainerType()); public static bool SupportsSsl3 => GetSsl3Support(); // >= Windows 10 Anniversary Update public static bool IsWindows10Version1607OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; // >= Windows 10 Creators Update public static bool IsWindows10Version1703OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; // >= Windows 10 Fall Creators Update public static bool IsWindows10Version1709OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16299; // >= Windows 10 April 2018 Update public static bool IsWindows10Version1803OrGreater => GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 17134; // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll")); public static bool IsWindowsIoTCore { get { int productType = GetWindowsProductType(); if ((productType == PRODUCT_IOTUAPCOMMERCIAL) || (productType == PRODUCT_IOTUAP)) { return true; } return false; } } public static bool IsWindowsHomeEdition { get { int productType = GetWindowsProductType(); switch (productType) { case PRODUCT_CORE: case PRODUCT_CORE_COUNTRYSPECIFIC: case PRODUCT_CORE_N: case PRODUCT_CORE_SINGLELANGUAGE: case PRODUCT_HOME_BASIC: case PRODUCT_HOME_BASIC_N: case PRODUCT_HOME_PREMIUM: case PRODUCT_HOME_PREMIUM_N: return true; default: return false; } } } public static bool IsWindows => true; public static bool IsWindows7 => GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static bool IsWindows8xOrLater => new Version((int)GetWindowsVersion(), (int)GetWindowsMinorVersion()) >= new Version(6, 2); public static string LibcRelease => "glibc_not_found"; public static string LibcVersion => "glibc_not_found"; public static string GetDistroVersionString() { return "WindowsProductType=" + GetWindowsProductType() + " WindowsInstallationType=" + GetInstallationType(); } private static int s_isInAppContainer = -1; public static bool IsInAppContainer { // This actually checks whether code is running in a modern app. // Currently this is the only situation where we run in app container. // If we want to distinguish the two cases in future, // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token. get { if (s_isInAppContainer != -1) return s_isInAppContainer == 1; if (!IsWindows || IsWindows7) { s_isInAppContainer = 0; return false; } byte[] buffer = Array.Empty<byte>(); uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isInAppContainer = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isInAppContainer = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isInAppContainer = 0; } else { throw; } } return s_isInAppContainer == 1; } } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsInAppContainer) { s_isWindowsElevated = 0; return false; } s_isWindowsElevated = AdminHelpers.IsProcessElevated() ? 1 : 0; return s_isWindowsElevated == 1; } } private static string GetInstallationType() { string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; string value = ""; try { value = (string)Registry.GetValue(key, "InstallationType", defaultValue: ""); } catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */) { } return value; } private static bool GetSsl3Support() { string clientKey = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client"; string serverKey = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server"; bool enabled = true; // This may change in future but for now, missing key means protocol is enabled. try { if ((int)Registry.GetValue(clientKey, "Enabled", 1) == 0 || (int)Registry.GetValue(serverKey, "Enabled", 1) == 0) { enabled = false; } } catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is NullReferenceException) { } return enabled; } private static int GetWindowsProductType() { Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType)); return productType; } private static string GetContainerType() { string key = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control"; string value = ""; try { value = (string)Registry.GetValue(key, "ContainerType", defaultValue: ""); } catch { } return value; } private const int PRODUCT_IOTUAP = 0x0000007B; private const int PRODUCT_IOTUAPCOMMERCIAL = 0x00000083; private const int PRODUCT_CORE = 0x00000065; private const int PRODUCT_CORE_COUNTRYSPECIFIC = 0x00000063; private const int PRODUCT_CORE_N = 0x00000062; private const int PRODUCT_CORE_SINGLELANGUAGE = 0x00000064; private const int PRODUCT_HOME_BASIC = 0x00000002; private const int PRODUCT_HOME_BASIC_N = 0x00000005; private const int PRODUCT_HOME_PREMIUM = 0x00000003; private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A; [DllImport("kernel32.dll", SetLastError = false)] private static extern bool GetProductInfo( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, out int pdwReturnedProductType ); [DllImport("kernel32.dll", ExactSpelling = true)] private static extern int GetCurrentApplicationUserModelId(ref uint applicationUserModelIdLength, byte[] applicationUserModelId); internal static uint GetWindowsVersion() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwMajorVersion; } internal static uint GetWindowsMinorVersion() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwMinorVersion; } internal static uint GetWindowsBuildNumber() { Assert.Equal(0, Interop.NtDll.RtlGetVersionEx(out Interop.NtDll.RTL_OSVERSIONINFOEX osvi)); return osvi.dwBuildNumber; } } }
// // PropertyDefinition.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Text; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider { bool? has_this; ushort attributes; Collection<CustomAttribute> custom_attributes; internal MethodDefinition get_method; internal MethodDefinition set_method; internal Collection<MethodDefinition> other_methods; object constant = Mixin.NotResolved; public PropertyAttributes Attributes { get { return (PropertyAttributes) attributes; } set { attributes = (ushort) value; } } public bool HasThis { get { if (has_this.HasValue) return has_this.Value; if (GetMethod != null) return get_method.HasThis; if (SetMethod != null) return set_method.HasThis; return false; } set { has_this = value; } } 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 MethodDefinition GetMethod { get { if (get_method != null) return get_method; InitializeMethods (); return get_method; } set { get_method = value; } } public MethodDefinition SetMethod { get { if (set_method != null) return set_method; InitializeMethods (); return set_method; } set { set_method = value; } } public bool HasOtherMethods { get { if (other_methods != null) return other_methods.Count > 0; InitializeMethods (); return !other_methods.IsNullOrEmpty (); } } public Collection<MethodDefinition> OtherMethods { get { if (other_methods != null) return other_methods; InitializeMethods (); if (other_methods != null) return other_methods; return other_methods = new Collection<MethodDefinition> (); } } public bool HasParameters { get { InitializeMethods (); if (get_method != null) return get_method.HasParameters; if (set_method != null) return set_method.HasParameters && set_method.Parameters.Count > 1; return false; } } public override Collection<ParameterDefinition> Parameters { get { InitializeMethods (); if (get_method != null) return MirrorParameters (get_method, 0); if (set_method != null) return MirrorParameters (set_method, 1); return new Collection<ParameterDefinition> (); } } static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound) { var parameters = new Collection<ParameterDefinition> (); if (!method.HasParameters) return parameters; var original_parameters = method.Parameters; var end = original_parameters.Count - bound; for (int i = 0; i < end; i++) parameters.Add (original_parameters [i]); return parameters; } public bool HasConstant { get { this.ResolveConstant (ref constant, Module); return constant != Mixin.NoValue; } set { if (!value) constant = Mixin.NoValue; } } public object Constant { get { return HasConstant ? constant : null; } set { constant = value; } } #region PropertyAttributes public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); } } public bool HasDefault { get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public override bool IsDefinition { get { return true; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (PropertyType.ToString ()); builder.Append (' '); builder.Append (MemberFullName ()); builder.Append ('('); if (HasParameters) { var parameters = Parameters; for (int i = 0; i < parameters.Count; i++) { if (i > 0) builder.Append (','); builder.Append (parameters [i].ParameterType.FullName); } } builder.Append (')'); return builder.ToString (); } } public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType) : base (name, propertyType) { this.attributes = (ushort) attributes; this.token = new MetadataToken (TokenType.Property); } void InitializeMethods () { var module = this.Module; if (module == null) return; lock (module.SyncRoot) { if (get_method != null || set_method != null) return; if (!module.HasImage ()) return; module.Read (this, (property, reader) => reader.ReadMethods (property)); } } public override PropertyDefinition Resolve () { return this; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; namespace Microsoft.Msagl.Routing.Visibility { /// <summary> /// the visibility graph /// </summary> public class VisibilityGraph { Dictionary<VisibilityVertex, VisibilityEdge> _prevEdgesDictionary = new Dictionary<VisibilityVertex, VisibilityEdge>(); internal Dictionary<VisibilityVertex, int> visVertexToId = new Dictionary<VisibilityVertex, int>(); internal void ClearPrevEdgesTable() { _prevEdgesDictionary.Clear(); } internal void ShrinkLengthOfPrevEdge(VisibilityVertex v, double lengthMultiplier) { _prevEdgesDictionary[v].LengthMultiplier = lengthMultiplier; } /// <summary> /// needed for shortest path calculations /// </summary> internal VisibilityVertex PreviosVertex(VisibilityVertex v) { VisibilityEdge prev; if (!_prevEdgesDictionary.TryGetValue(v, out prev)) return null; if (prev.Source == v) return prev.Target; return prev.Source; } internal void SetPreviousEdge(VisibilityVertex v, VisibilityEdge e) { Debug.Assert(v == e.Source || v == e.Target); _prevEdgesDictionary[v] = e; } /// <summary> /// the default is just to return VisibilityVertex /// </summary> Func<Point, VisibilityVertex> vertexFactory = (point => new VisibilityVertex(point)); internal Func<Point, VisibilityVertex> VertexFactory { get { return vertexFactory; } set { vertexFactory = value; } } readonly Dictionary<Point, VisibilityVertex> pointToVertexMap = new Dictionary<Point, VisibilityVertex>(); /// <summary> /// /// </summary> /// <param name="pathStart"></param> /// <param name="pathEnd"></param> /// <param name="obstacles"></param> /// <param name="sourceVertex">graph vertex corresponding to the source</param> /// <param name="targetVertex">graph vertex corresponding to the target</param> /// <returns></returns> internal static VisibilityGraph GetVisibilityGraphForShortestPath(Point pathStart, Point pathEnd, IEnumerable<Polyline> obstacles, out VisibilityVertex sourceVertex, out VisibilityVertex targetVertex) { var holes = new List<Polyline>(OrientHolesClockwise(obstacles)); var visibilityGraph = CalculateGraphOfBoundaries(holes); var polygons = holes.Select(hole => new Polygon(hole)).ToList(); TangentVisibilityGraphCalculator.AddTangentVisibilityEdgesToGraph(polygons, visibilityGraph); PointVisibilityCalculator.CalculatePointVisibilityGraph(holes, visibilityGraph, pathStart, VisibilityKind.Tangent, out sourceVertex); PointVisibilityCalculator.CalculatePointVisibilityGraph(holes, visibilityGraph, pathEnd, VisibilityKind.Tangent, out targetVertex); return visibilityGraph; } /// <summary> /// Calculates the tangent visibility graph /// </summary> /// <param name="obstacles">a list of polylines representing obstacles</param> /// <returns></returns> public static VisibilityGraph FillVisibilityGraphForShortestPath(IEnumerable<Polyline> obstacles) { var holes = new List<Polyline>(OrientHolesClockwise(obstacles)); var visibilityGraph = CalculateGraphOfBoundaries(holes); var polygons = holes.Select(hole => new Polygon(hole)).ToList(); TangentVisibilityGraphCalculator.AddTangentVisibilityEdgesToGraph(polygons, visibilityGraph); return visibilityGraph; } static internal VisibilityGraph CalculateGraphOfBoundaries(List<Polyline> holes) { var graphOfHoleBoundaries = new VisibilityGraph(); foreach (Polyline polyline in holes) graphOfHoleBoundaries.AddHole(polyline); return graphOfHoleBoundaries; } internal void AddHole(Polyline polyline) { var p = polyline.StartPoint; while (p != polyline.EndPoint) { AddEdge(p, p.Next); p = p.Next; } AddEdge(polyline.EndPoint, polyline.StartPoint); } internal static IEnumerable<Polyline> OrientHolesClockwise(IEnumerable<Polyline> holes) { #if TEST_MSAGL || VERIFY CheckThatPolylinesAreConvex(holes); #endif // TEST || VERIFY foreach (Polyline poly in holes) { for (PolylinePoint p = poly.StartPoint; ; p = p.Next) { // Find the first non-collinear segments and see which direction the triangle is. // If it's consistent with Clockwise, then return the polyline, else return its Reverse. var orientation = Point.GetTriangleOrientation(p.Point, p.Next.Point, p.Next.Next.Point); if (orientation != TriangleOrientation.Collinear) { yield return orientation == TriangleOrientation.Clockwise ? poly : (Polyline)poly.Reverse(); break; } } } } #if TEST_MSAGL || VERIFY internal static void CheckThatPolylinesAreConvex(IEnumerable<Polyline> holes) { foreach (var polyline in holes) CheckThatPolylineIsConvex(polyline); } [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] internal static void CheckThatPolylineIsConvex(Polyline polyline) { Debug.Assert(polyline.Closed, "Polyline is not closed"); PolylinePoint a = polyline.StartPoint; PolylinePoint b = a.Next; PolylinePoint c = b.Next; TriangleOrientation orient = Point.GetTriangleOrientation(a.Point, b.Point, c.Point); while (c != polyline.EndPoint) { a = a.Next; b = b.Next; c = c.Next; var currentOrient = Point.GetTriangleOrientation(a.Point, b.Point, c.Point); if (currentOrient == TriangleOrientation.Collinear) continue; if (orient == TriangleOrientation.Collinear) orient = currentOrient; else if (orient != currentOrient) throw new InvalidOperationException(); } var o = Point.GetTriangleOrientation(polyline.EndPoint.Point, polyline.StartPoint.Point, polyline.StartPoint.Next.Point); if (o != TriangleOrientation.Collinear && o != orient) throw new InvalidOperationException(); } #endif // TEST || VERIFY /// <summary> /// Enumerate all VisibilityEdges in the VisibilityGraph. /// </summary> public IEnumerable<VisibilityEdge> Edges { get { return PointToVertexMap.Values.SelectMany(vertex => vertex.OutEdges); } } internal Dictionary<Point, VisibilityVertex> PointToVertexMap { get { return pointToVertexMap; } } internal int VertexCount { get { return PointToVertexMap.Count; } } internal VisibilityVertex AddVertex(PolylinePoint polylinePoint) { return AddVertex(polylinePoint.Point); } internal VisibilityVertex AddVertex(Point point) { #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=370 //SharpKit/Colin - http://code.google.com/p/sharpkit/issues/detail?id=277 VisibilityVertex currentVertex; if (PointToVertexMap.TryGetValue(point, out currentVertex)) return currentVertex; var newVertex = VertexFactory(point); PointToVertexMap[point] = newVertex; return newVertex; #else VisibilityVertex vertex; return !PointToVertexMap.TryGetValue(point, out vertex) ? (PointToVertexMap[point] = VertexFactory(point)) : vertex; #endif } internal void AddVertex(VisibilityVertex vertex) { Debug.Assert(!PointToVertexMap.ContainsKey(vertex.Point), "A vertex already exists at this location"); PointToVertexMap[vertex.Point] = vertex; } internal bool ContainsVertex(Point point) { return PointToVertexMap.ContainsKey(point); } static internal VisibilityEdge AddEdge(VisibilityVertex source, VisibilityVertex target) { VisibilityEdge visEdge; if (source.TryGetEdge(target, out visEdge)) return visEdge; if (source == target) { Debug.Assert(false, "Self-edges are not allowed"); throw new InvalidOperationException("Self-edges are not allowed"); } var edge = new VisibilityEdge(source, target); source.OutEdges.Insert(edge); target.InEdges.Add(edge); return edge; } void AddEdge(PolylinePoint source, PolylinePoint target) { AddEdge(source.Point, target.Point); } static internal void AddEdge(VisibilityEdge edge) { Debug.Assert(edge.Source != edge.Target); edge.Source.OutEdges.Insert(edge); edge.Target.InEdges.Add(edge); } internal VisibilityEdge AddEdge(Point source, Point target) { VisibilityEdge edge; var sourceV = FindVertex(source); VisibilityVertex targetV = null; if (sourceV != null) { targetV = FindVertex(target); if (targetV != null && sourceV.TryGetEdge(targetV, out edge)) return edge; } if (sourceV == null) { //then targetV is also null sourceV = AddVertex(source); targetV = AddVertex(target); } else if (targetV == null) targetV = AddVertex(target); edge = new VisibilityEdge(sourceV, targetV); sourceV.OutEdges.Insert(edge); targetV.InEdges.Add(edge); return edge; } /* internal static bool DebugClose(Point target, Point source) { var a = new Point(307, 7); var b = new Point(540.6, 15); return (target - a).Length < 2 && (source - b).Length < 5 || (source - a).Length < 2 && (target - b).Length<5; } */ internal VisibilityEdge AddEdge(Point source, Point target, Func<VisibilityVertex, VisibilityVertex, VisibilityEdge> edgeCreator) { VisibilityEdge edge; var sourceV = FindVertex(source); VisibilityVertex targetV = null; if (sourceV != null) { targetV = FindVertex(target); if (targetV != null && sourceV.TryGetEdge(targetV, out edge)) return edge; } if (sourceV == null) { //then targetV is also null sourceV = AddVertex(source); targetV = AddVertex(target); } else if (targetV == null) targetV = AddVertex(target); edge = edgeCreator(sourceV, targetV); sourceV.OutEdges.Insert(edge); targetV.InEdges.Add(edge); return edge; } internal VisibilityVertex FindVertex(Point point) { VisibilityVertex v; return PointToVertexMap.TryGetValue(point, out v) ? v : null; } internal VisibilityVertex GetVertex(PolylinePoint polylinePoint) { return FindVertex(polylinePoint.Point); } internal IEnumerable<VisibilityVertex> Vertices() { return PointToVertexMap.Values; } internal void RemoveVertex(VisibilityVertex vertex) { // Debug.Assert(PointToVertexMap.ContainsKey(vertex.Point), "Cannot find vertex in PointToVertexMap"); foreach (var edge in vertex.OutEdges) edge.Target.RemoveInEdge(edge); foreach (var edge in vertex.InEdges) edge.Source.RemoveOutEdge(edge); PointToVertexMap.Remove(vertex.Point); } internal void RemoveEdge(VisibilityVertex v1, VisibilityVertex v2) { VisibilityEdge edge; if (!v1.TryGetEdge(v2, out edge)) return; edge.Source.RemoveOutEdge(edge); edge.Target.RemoveInEdge(edge); } internal void RemoveEdge(Point p1, Point p2) { // the order of p1 and p2 is not important. VisibilityEdge edge = FindEdge(p1, p2); if (edge == null) return; edge.Source.RemoveOutEdge(edge); edge.Target.RemoveInEdge(edge); } static internal VisibilityEdge FindEdge(VisibilityEdge edge) { if (edge.Source.TryGetEdge(edge.Target, out edge)) return edge; return null; } internal VisibilityEdge FindEdge(Point source, Point target) { var sourceV = FindVertex(source); if (sourceV == null) return null; var targetV = FindVertex(target); if (targetV == null) return null; VisibilityEdge edge; if (sourceV.TryGetEdge(targetV, out edge)) return edge; return null; } static internal void RemoveEdge(VisibilityEdge edge) { edge.Source.OutEdges.Remove(edge);//not efficient! edge.Target.InEdges.Remove(edge);//not efficient } public void ClearEdges() { foreach (var visibilityVertex in Vertices()) { visibilityVertex.ClearEdges(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// Hud1Es /// </summary> public sealed partial class Hud1Es : DirtyExtensibleObject, IIdentifiable { private DirtyValue<decimal?>? _annualCityTax; private DirtyValue<int?>? _annualFeeCushion; private DirtyValue<decimal?>? _annualFloodInsurance; private DirtyValue<decimal?>? _annualHazardInsurance; private DirtyValue<decimal?>? _annualMortgageInsurance; private DirtyValue<decimal?>? _annualTax; private DirtyValue<decimal?>? _annualUserEscrow1; private DirtyValue<decimal?>? _annualUserEscrow2; private DirtyValue<decimal?>? _annualUserEscrow3; private DirtyValue<decimal?>? _biweeklyCityPropertyTaxes; private DirtyValue<decimal?>? _biweeklyCountyTaxes; private DirtyValue<decimal?>? _biweeklyFloodInsurance; private DirtyValue<decimal?>? _biweeklyHazardInsurance; private DirtyValue<decimal?>? _biweeklyMortgageInsurance; private DirtyValue<decimal?>? _biweeklyPITI; private DirtyValue<decimal?>? _biweeklyTotalBiweeklyPayment; private DirtyValue<decimal?>? _biweeklyTotalBiweeklyPaymentToEscrow; private DirtyValue<decimal?>? _biweeklyUSDAFee; private DirtyValue<decimal?>? _biweeklyUserDefinedEscrowFee1; private DirtyValue<decimal?>? _biweeklyUserDefinedEscrowFee2; private DirtyValue<decimal?>? _biweeklyUserDefinedEscrowFee3; private DirtyValue<string?>? _cityPropertyTaxAddress; private DirtyValue<decimal?>? _cityPropertyTaxAmountLastPay; private DirtyValue<decimal?>? _cityPropertyTaxAmountNextDue; private DirtyValue<string?>? _cityPropertyTaxCity; private DirtyValue<string?>? _cityPropertyTaxContactName; private DirtyValue<DateTime?>? _cityPropertyTaxDatePaid; private DirtyValue<DateTime?>? _cityPropertyTaxDelinquentDate; private DirtyValue<string?>? _cityPropertyTaxEmail; private DirtyValue<string?>? _cityPropertyTaxFax; private DirtyValue<string?>? _cityPropertyTaxName; private DirtyValue<DateTime?>? _cityPropertyTaxNextDueDate; private DirtyValue<string?>? _cityPropertyTaxPaymentSchedule; private DirtyValue<string?>? _cityPropertyTaxPhone; private DirtyValue<string?>? _cityPropertyTaxPostalCode; private DirtyValue<StringEnumValue<State>>? _cityPropertyTaxState; private DirtyValue<decimal?>? _endingBalance; private DirtyValue<DateTime?>? _escrowFirstPaymentDate; private DirtyValue<StringEnumValue<EscrowFirstPaymentDateType>>? _escrowFirstPaymentDateType; private DirtyValue<decimal?>? _escrowPayment; private DirtyValue<decimal?>? _escrowPaymentYearly; private DirtyValue<int?>? _floodInsDisbCushion; private DirtyValue<int?>? _hazInsDisbCushion; private DirtyList<Hud1EsDate>? _hud1EsDates; private DirtyList<Hud1EsDueDate>? _hud1EsDueDates; private DirtyList<Hud1EsItemize>? _hud1EsItemizes; private DirtyValue<int?>? _hud1EsItemizesTotalLines; private DirtyValue<bool?>? _hud1EsItemizesUseItemizeEscrowIndicator; private DirtyList<Hud1EsPayTo>? _hud1EsPayTos; private DirtyList<Hud1EsSetup>? _hud1EsSetups; private DirtyValue<string?>? _id; private DirtyValue<bool?>? _mtgInsCushionTerminationIndicator; private DirtyValue<int?>? _mtgInsDisbCushion; private DirtyValue<decimal?>? _nonEscrowCostsYearly; private DirtyValue<string?>? _realEstateTaxAddress; private DirtyValue<decimal?>? _realEstateTaxAmountLastPay; private DirtyValue<decimal?>? _realEstateTaxAmountNextDue; private DirtyValue<string?>? _realEstateTaxCity; private DirtyValue<string?>? _realEstateTaxContactName; private DirtyValue<DateTime?>? _realEstateTaxDatePaid; private DirtyValue<DateTime?>? _realEstateTaxDelinquentDate; private DirtyValue<string?>? _realEstateTaxEmail; private DirtyValue<string?>? _realEstateTaxFax; private DirtyValue<string?>? _realEstateTaxName; private DirtyValue<DateTime?>? _realEstateTaxNextDueDate; private DirtyValue<string?>? _realEstateTaxPaymentSchedule; private DirtyValue<string?>? _realEstateTaxPhone; private DirtyValue<string?>? _realEstateTaxPostalCode; private DirtyValue<StringEnumValue<State>>? _realEstateTaxState; private DirtyValue<int?>? _schoolTaxesCushion; private DirtyValue<string?>? _servicerAddress; private DirtyValue<string?>? _servicerCity; private DirtyValue<string?>? _servicerContactName; private DirtyValue<string?>? _servicerPhone; private DirtyValue<string?>? _servicerPostalCode; private DirtyValue<StringEnumValue<State>>? _servicerState; private DirtyValue<decimal?>? _singleLineAnalysis; private DirtyValue<decimal?>? _startingBalance; private DirtyValue<int?>? _taxDisbCushion; private DirtyValue<decimal?>? _totalEscrowReserves; private DirtyValue<decimal?>? _usdaAnnualFee; private DirtyValue<int?>? _userDefinedCushion1; private DirtyValue<int?>? _userDefinedCushion2; private DirtyValue<int?>? _userDefinedCushion3; private DirtyValue<decimal?>? _yearlyMortgageInsurance; private DirtyValue<decimal?>? _yearlyUsdaFee; /// <summary> /// HUD Annual City Tax Payment [HUD45] /// </summary> public decimal? AnnualCityTax { get => _annualCityTax; set => SetField(ref _annualCityTax, value); } /// <summary> /// No. Annual Fee Pymts for Cushion [HUD38] /// </summary> public int? AnnualFeeCushion { get => _annualFeeCushion; set => SetField(ref _annualFeeCushion, value); } /// <summary> /// HUD Annual Flood Insurance Payment [HUD44] /// </summary> public decimal? AnnualFloodInsurance { get => _annualFloodInsurance; set => SetField(ref _annualFloodInsurance, value); } /// <summary> /// HUD Annual Hazard Insurance Payment [HUD42] /// </summary> public decimal? AnnualHazardInsurance { get => _annualHazardInsurance; set => SetField(ref _annualHazardInsurance, value); } /// <summary> /// HUD Annual Mortgage Insurance Payment [HUD43] /// </summary> public decimal? AnnualMortgageInsurance { get => _annualMortgageInsurance; set => SetField(ref _annualMortgageInsurance, value); } /// <summary> /// HUD Annual Tax Payment [HUD41] /// </summary> public decimal? AnnualTax { get => _annualTax; set => SetField(ref _annualTax, value); } /// <summary> /// HUD Annual User Escrow Payment 1 [HUD46] /// </summary> public decimal? AnnualUserEscrow1 { get => _annualUserEscrow1; set => SetField(ref _annualUserEscrow1, value); } /// <summary> /// HUD Annual User Escrow Payment 2 [HUD47] /// </summary> public decimal? AnnualUserEscrow2 { get => _annualUserEscrow2; set => SetField(ref _annualUserEscrow2, value); } /// <summary> /// HUD Annual User Escrow Payment 3 [HUD48] /// </summary> public decimal? AnnualUserEscrow3 { get => _annualUserEscrow3; set => SetField(ref _annualUserEscrow3, value); } /// <summary> /// HUD Biweekly Escrow Payment - City Property Taxes [HUD56] /// </summary> public decimal? BiweeklyCityPropertyTaxes { get => _biweeklyCityPropertyTaxes; set => SetField(ref _biweeklyCityPropertyTaxes, value); } /// <summary> /// HUD Biweekly Escrow Payment - County Taxes [HUD52] /// </summary> public decimal? BiweeklyCountyTaxes { get => _biweeklyCountyTaxes; set => SetField(ref _biweeklyCountyTaxes, value); } /// <summary> /// HUD Biweekly Escrow Payment - Flood Insurance [HUD55] /// </summary> public decimal? BiweeklyFloodInsurance { get => _biweeklyFloodInsurance; set => SetField(ref _biweeklyFloodInsurance, value); } /// <summary> /// HUD Biweekly Escrow Payment - Hazard Insurance [HUD53] /// </summary> public decimal? BiweeklyHazardInsurance { get => _biweeklyHazardInsurance; set => SetField(ref _biweeklyHazardInsurance, value); } /// <summary> /// HUD Biweekly Escrow Payment - Mortgage Insurance [HUD54] /// </summary> public decimal? BiweeklyMortgageInsurance { get => _biweeklyMortgageInsurance; set => SetField(ref _biweeklyMortgageInsurance, value); } /// <summary> /// HUD Biweekly Escrow Payment - PITI [HUD51] /// </summary> public decimal? BiweeklyPITI { get => _biweeklyPITI; set => SetField(ref _biweeklyPITI, value); } /// <summary> /// HUD Biweekly Escrow Payment - Total Biweekly Payment Amount [HUD64] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? BiweeklyTotalBiweeklyPayment { get => _biweeklyTotalBiweeklyPayment; set => SetField(ref _biweeklyTotalBiweeklyPayment, value); } /// <summary> /// HUD Biweekly Escrow Payment - Total Biweekly Payment to Escrow [HUD65] /// </summary> public decimal? BiweeklyTotalBiweeklyPaymentToEscrow { get => _biweeklyTotalBiweeklyPaymentToEscrow; set => SetField(ref _biweeklyTotalBiweeklyPaymentToEscrow, value); } /// <summary> /// HUD Biweekly Escrow Payment - USDA Annual Fee [HUD63] /// </summary> public decimal? BiweeklyUSDAFee { get => _biweeklyUSDAFee; set => SetField(ref _biweeklyUSDAFee, value); } /// <summary> /// HUD Biweekly Escrow Payment - User Defined Escrow Fee 1 [HUD58] /// </summary> public decimal? BiweeklyUserDefinedEscrowFee1 { get => _biweeklyUserDefinedEscrowFee1; set => SetField(ref _biweeklyUserDefinedEscrowFee1, value); } /// <summary> /// HUD Biweekly Escrow Payment - User Defined Escrow Fee 2 [HUD60] /// </summary> public decimal? BiweeklyUserDefinedEscrowFee2 { get => _biweeklyUserDefinedEscrowFee2; set => SetField(ref _biweeklyUserDefinedEscrowFee2, value); } /// <summary> /// HUD Biweekly Escrow Payment - User Defined Escrow Fee 3 [HUD62] /// </summary> public decimal? BiweeklyUserDefinedEscrowFee3 { get => _biweeklyUserDefinedEscrowFee3; set => SetField(ref _biweeklyUserDefinedEscrowFee3, value); } /// <summary> /// HUD1ES City Property Tax Pay To Address [VEND.X333] /// </summary> public string? CityPropertyTaxAddress { get => _cityPropertyTaxAddress; set => SetField(ref _cityPropertyTaxAddress, value); } /// <summary> /// HUD1ES City Property Tax Pay To Amount Last Paid [VEND.X450] /// </summary> public decimal? CityPropertyTaxAmountLastPay { get => _cityPropertyTaxAmountLastPay; set => SetField(ref _cityPropertyTaxAmountLastPay, value); } /// <summary> /// HUD1ES City Property Tax Pay To Amount Next Due [VEND.X452] /// </summary> public decimal? CityPropertyTaxAmountNextDue { get => _cityPropertyTaxAmountNextDue; set => SetField(ref _cityPropertyTaxAmountNextDue, value); } /// <summary> /// HUD1ES City Property Tax Pay To City [VEND.X334] /// </summary> public string? CityPropertyTaxCity { get => _cityPropertyTaxCity; set => SetField(ref _cityPropertyTaxCity, value); } /// <summary> /// HUD1ES City Property Tax Pay To Contact [VEND.X337] /// </summary> public string? CityPropertyTaxContactName { get => _cityPropertyTaxContactName; set => SetField(ref _cityPropertyTaxContactName, value); } /// <summary> /// HUD1ES City Property Tax Pay To Date Paid [VEND.X451] /// </summary> public DateTime? CityPropertyTaxDatePaid { get => _cityPropertyTaxDatePaid; set => SetField(ref _cityPropertyTaxDatePaid, value); } /// <summary> /// HUD1ES City Property Tax Pay To Delinquent Date [VEND.X454] /// </summary> public DateTime? CityPropertyTaxDelinquentDate { get => _cityPropertyTaxDelinquentDate; set => SetField(ref _cityPropertyTaxDelinquentDate, value); } /// <summary> /// HUD1ES City Property Tax Pay To Email [VEND.X339] /// </summary> public string? CityPropertyTaxEmail { get => _cityPropertyTaxEmail; set => SetField(ref _cityPropertyTaxEmail, value); } /// <summary> /// Fees City Property Tax Pay To Fax [VEND.X340] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? CityPropertyTaxFax { get => _cityPropertyTaxFax; set => SetField(ref _cityPropertyTaxFax, value); } /// <summary> /// HUD1ES City Property Tax Pay To Name [VEND.X332] /// </summary> public string? CityPropertyTaxName { get => _cityPropertyTaxName; set => SetField(ref _cityPropertyTaxName, value); } /// <summary> /// HUD1ES City Property Tax Pay To Next Due Date [VEND.X453] /// </summary> public DateTime? CityPropertyTaxNextDueDate { get => _cityPropertyTaxNextDueDate; set => SetField(ref _cityPropertyTaxNextDueDate, value); } /// <summary> /// HUD1ES City Property Tax Pay To Payment Schedule [VEND.X449] /// </summary> public string? CityPropertyTaxPaymentSchedule { get => _cityPropertyTaxPaymentSchedule; set => SetField(ref _cityPropertyTaxPaymentSchedule, value); } /// <summary> /// HUD1ES City Property Tax Pay To Phone [VEND.X338] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? CityPropertyTaxPhone { get => _cityPropertyTaxPhone; set => SetField(ref _cityPropertyTaxPhone, value); } /// <summary> /// HUD1ES City Property Tax Pay To Zip [VEND.X336] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? CityPropertyTaxPostalCode { get => _cityPropertyTaxPostalCode; set => SetField(ref _cityPropertyTaxPostalCode, value); } /// <summary> /// HUD1ES City Property Tax Pay To State [VEND.X335] /// </summary> public StringEnumValue<State> CityPropertyTaxState { get => _cityPropertyTaxState; set => SetField(ref _cityPropertyTaxState, value); } /// <summary> /// HUD Ending Balance [HUD25] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? EndingBalance { get => _endingBalance; set => SetField(ref _endingBalance, value); } /// <summary> /// Escrow First Payment Date [HUD68] /// </summary> public DateTime? EscrowFirstPaymentDate { get => _escrowFirstPaymentDate; set => SetField(ref _escrowFirstPaymentDate, value); } /// <summary> /// Escrow First Payment Date Type [HUD69] /// </summary> public StringEnumValue<EscrowFirstPaymentDateType> EscrowFirstPaymentDateType { get => _escrowFirstPaymentDateType; set => SetField(ref _escrowFirstPaymentDateType, value); } /// <summary> /// HUD Escrow Monthly Payment [HUD24] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? EscrowPayment { get => _escrowPayment; set => SetField(ref _escrowPayment, value); } /// <summary> /// HUD Escrow Yearly Payment [HUD66] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? EscrowPaymentYearly { get => _escrowPaymentYearly; set => SetField(ref _escrowPaymentYearly, value); } /// <summary> /// No. Flood Ins Pymts for Cushion [HUD33] /// </summary> public int? FloodInsDisbCushion { get => _floodInsDisbCushion; set => SetField(ref _floodInsDisbCushion, value); } /// <summary> /// No. Hazard Ins Pymts for Cushion [HUD31] /// </summary> public int? HazInsDisbCushion { get => _hazInsDisbCushion; set => SetField(ref _hazInsDisbCushion, value); } /// <summary> /// Hud1Es Hud1EsDates /// </summary> [AllowNull] public IList<Hud1EsDate> Hud1EsDates { get => GetField(ref _hud1EsDates); set => SetField(ref _hud1EsDates, value); } /// <summary> /// Hud1Es Hud1EsDueDates /// </summary> [AllowNull] public IList<Hud1EsDueDate> Hud1EsDueDates { get => GetField(ref _hud1EsDueDates); set => SetField(ref _hud1EsDueDates, value); } /// <summary> /// Hud1Es Hud1EsItemizes /// </summary> [AllowNull] public IList<Hud1EsItemize> Hud1EsItemizes { get => GetField(ref _hud1EsItemizes); set => SetField(ref _hud1EsItemizes, value); } /// <summary> /// Itemize Escrow Number of Lines in Escrow Output [AEA.X1] /// </summary> public int? Hud1EsItemizesTotalLines { get => _hud1EsItemizesTotalLines; set => SetField(ref _hud1EsItemizesTotalLines, value); } /// <summary> /// Itemize Escrow Use Itemize Escrow Output Format [AEA.X2] /// </summary> public bool? Hud1EsItemizesUseItemizeEscrowIndicator { get => _hud1EsItemizesUseItemizeEscrowIndicator; set => SetField(ref _hud1EsItemizesUseItemizeEscrowIndicator, value); } /// <summary> /// Hud1Es Hud1EsPayTos /// </summary> [AllowNull] public IList<Hud1EsPayTo> Hud1EsPayTos { get => GetField(ref _hud1EsPayTos); set => SetField(ref _hud1EsPayTos, value); } /// <summary> /// Hud1Es Hud1EsSetups /// </summary> [AllowNull] public IList<Hud1EsSetup> Hud1EsSetups { get => GetField(ref _hud1EsSetups); set => SetField(ref _hud1EsSetups, value); } /// <summary> /// Hud1Es Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// Servicer to refund Mtg Ins Cushion upon termination [HUD49] /// </summary> public bool? MtgInsCushionTerminationIndicator { get => _mtgInsCushionTerminationIndicator; set => SetField(ref _mtgInsCushionTerminationIndicator, value); } /// <summary> /// No. Mtg Ins Pymts for Cushion [HUD32] /// </summary> public int? MtgInsDisbCushion { get => _mtgInsDisbCushion; set => SetField(ref _mtgInsDisbCushion, value); } /// <summary> /// HUD Non Escrow Yearly Costs [HUD67] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NonEscrowCostsYearly { get => _nonEscrowCostsYearly; set => SetField(ref _nonEscrowCostsYearly, value); } /// <summary> /// HUD1ES Tax Pay To Address [VEND.X324] /// </summary> public string? RealEstateTaxAddress { get => _realEstateTaxAddress; set => SetField(ref _realEstateTaxAddress, value); } /// <summary> /// HUD1ES Tax Pay To Amount Last Paid [VEND.X438] /// </summary> public decimal? RealEstateTaxAmountLastPay { get => _realEstateTaxAmountLastPay; set => SetField(ref _realEstateTaxAmountLastPay, value); } /// <summary> /// HUD1ES Tax Pay To Amount Next Due [VEND.X440] /// </summary> public decimal? RealEstateTaxAmountNextDue { get => _realEstateTaxAmountNextDue; set => SetField(ref _realEstateTaxAmountNextDue, value); } /// <summary> /// HUD1ES Tax Pay To City [VEND.X325] /// </summary> public string? RealEstateTaxCity { get => _realEstateTaxCity; set => SetField(ref _realEstateTaxCity, value); } /// <summary> /// HUD1ES Tax Pay To Contact Name [VEND.X328] /// </summary> public string? RealEstateTaxContactName { get => _realEstateTaxContactName; set => SetField(ref _realEstateTaxContactName, value); } /// <summary> /// HUD1ES Tax Pay To Date Paid [VEND.X439] /// </summary> public DateTime? RealEstateTaxDatePaid { get => _realEstateTaxDatePaid; set => SetField(ref _realEstateTaxDatePaid, value); } /// <summary> /// HUD1ES Tax Pay To Delinquent Date [VEND.X442] /// </summary> public DateTime? RealEstateTaxDelinquentDate { get => _realEstateTaxDelinquentDate; set => SetField(ref _realEstateTaxDelinquentDate, value); } /// <summary> /// HUD1ES Tax Pay To Email [VEND.X330] /// </summary> public string? RealEstateTaxEmail { get => _realEstateTaxEmail; set => SetField(ref _realEstateTaxEmail, value); } /// <summary> /// HUD1ES Tax Pay To Fax [VEND.X331] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? RealEstateTaxFax { get => _realEstateTaxFax; set => SetField(ref _realEstateTaxFax, value); } /// <summary> /// HUD1ES Tax Pay To Name [VEND.X323] /// </summary> public string? RealEstateTaxName { get => _realEstateTaxName; set => SetField(ref _realEstateTaxName, value); } /// <summary> /// HUD1ES Tax Pay To Next Due Date [VEND.X441] /// </summary> public DateTime? RealEstateTaxNextDueDate { get => _realEstateTaxNextDueDate; set => SetField(ref _realEstateTaxNextDueDate, value); } /// <summary> /// HUD1ES Tax Pay To Payment Schedule [VEND.X437] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? RealEstateTaxPaymentSchedule { get => _realEstateTaxPaymentSchedule; set => SetField(ref _realEstateTaxPaymentSchedule, value); } /// <summary> /// HUD1ES Tax Pay To Phone [VEND.X329] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? RealEstateTaxPhone { get => _realEstateTaxPhone; set => SetField(ref _realEstateTaxPhone, value); } /// <summary> /// HUD1ES Tax Pay To Zip [VEND.X327] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? RealEstateTaxPostalCode { get => _realEstateTaxPostalCode; set => SetField(ref _realEstateTaxPostalCode, value); } /// <summary> /// HUD1ES Tax Pay To State [VEND.X326] /// </summary> public StringEnumValue<State> RealEstateTaxState { get => _realEstateTaxState; set => SetField(ref _realEstateTaxState, value); } /// <summary> /// No. City Tax Pymts for Cushion [HUD34] /// </summary> public int? SchoolTaxesCushion { get => _schoolTaxesCushion; set => SetField(ref _schoolTaxesCushion, value); } /// <summary> /// Escrow Servicer Address [L631] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? ServicerAddress { get => _servicerAddress; set => SetField(ref _servicerAddress, value); } /// <summary> /// Escrow Servicer City [L632] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? ServicerCity { get => _servicerCity; set => SetField(ref _servicerCity, value); } /// <summary> /// Escrow Servicer Name [L611] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? ServicerContactName { get => _servicerContactName; set => SetField(ref _servicerContactName, value); } /// <summary> /// Escrow Servicer Phone [L635] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE, ReadOnly = true)] public string? ServicerPhone { get => _servicerPhone; set => SetField(ref _servicerPhone, value); } /// <summary> /// Escrow Servicer Zipcode [L634] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE, ReadOnly = true)] public string? ServicerPostalCode { get => _servicerPostalCode; set => SetField(ref _servicerPostalCode, value); } /// <summary> /// Escrow Servicer State [L633] /// </summary> [LoanFieldProperty(ReadOnly = true)] public StringEnumValue<State> ServicerState { get => _servicerState; set => SetField(ref _servicerState, value); } /// <summary> /// HUD Single Line Analysis [HUD40] /// </summary> public decimal? SingleLineAnalysis { get => _singleLineAnalysis; set => SetField(ref _singleLineAnalysis, value); } /// <summary> /// HUD Starting Balance [HUD23] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? StartingBalance { get => _startingBalance; set => SetField(ref _startingBalance, value); } /// <summary> /// No. Tax Pymts for Cushion [HUD30] /// </summary> public int? TaxDisbCushion { get => _taxDisbCushion; set => SetField(ref _taxDisbCushion, value); } /// <summary> /// HUD Total Escrow Reserves [HUD26] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalEscrowReserves { get => _totalEscrowReserves; set => SetField(ref _totalEscrowReserves, value); } /// <summary> /// HUD USDA Annual Fee [HUD50] /// </summary> public decimal? UsdaAnnualFee { get => _usdaAnnualFee; set => SetField(ref _usdaAnnualFee, value); } /// <summary> /// No. User Defined 1 Pymts for Cushion [HUD35] /// </summary> public int? UserDefinedCushion1 { get => _userDefinedCushion1; set => SetField(ref _userDefinedCushion1, value); } /// <summary> /// No. User Defined 2 Pymts for Cushion [HUD36] /// </summary> public int? UserDefinedCushion2 { get => _userDefinedCushion2; set => SetField(ref _userDefinedCushion2, value); } /// <summary> /// No. User Defined 3 Pymts for Cushion [HUD37] /// </summary> public int? UserDefinedCushion3 { get => _userDefinedCushion3; set => SetField(ref _userDefinedCushion3, value); } /// <summary> /// HUD Yearly Mortgage Insurance Before Rounding [HUD.YearlyMIFee] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? YearlyMortgageInsurance { get => _yearlyMortgageInsurance; set => SetField(ref _yearlyMortgageInsurance, value); } /// <summary> /// HUD Yearly USDA Fee Before Monthly Payment Rounding [HUD.YearlyUSDAFee] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? YearlyUsdaFee { get => _yearlyUsdaFee; set => SetField(ref _yearlyUsdaFee, value); } } }
//--------------------------------------------------------------------------- // // Copyright (c) 2008-2010 AlazarTech, Inc. // // AlazarTech, Inc. licenses this software under specific terms and // conditions. Use of any of the software or derviatives thereof in any // product without an AlazarTech digitizer board is strictly prohibited. // // AlazarTech, Inc. provides this software AS IS, WITHOUT ANY WARRANTY, // EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. AlazarTech makes no // guarantee or representations regarding the use of, or the results of the // use of, the software and documentation in terms of correctness, accuracy, // reliability, currentness, or otherwise; and you rely on the software, // documentation and results solely at your own risk. // // IN NO EVENT SHALL ALAZARTECH BE LIABLE FOR ANY LOSS OF USE, LOSS OF // BUSINESS, LOSS OF PROFITS, INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL // DAMAGES OF ANY KIND. IN NO EVENT SHALL ALAZARTECH'S TOTAL LIABILITY EXCEED // THE SUM PAID TO ALAZARTECH FOR THE PRODUCT LICENSED HEREUNDER. // //--------------------------------------------------------------------------- // ------------------------------------------------------------------------- // Title: AlazarAPI.cs // Date: 2010/03/30 // Version: 5.7.8 // -------------------------------------------------------------------------- using System; using System.Runtime.InteropServices; namespace AlazarTech { class AlazarAPI { #region - Constants ------------------------------------------------- #region - Return Codes ---------------------------------------- public const UInt32 ApiSuccess = 512; public const UInt32 ApiFailed = 513; public const UInt32 ApiAccessDenied = 514; public const UInt32 ApiDmaChannelUnavailable = 515; public const UInt32 ApiDmaChannelInvalid = 516; public const UInt32 ApiDmaChannelTypeError = 517; public const UInt32 ApiDmaInProgress = 518; public const UInt32 ApiDmaDone = 519; public const UInt32 ApiDmaPaused = 520; public const UInt32 ApiDmaNotPaused = 521; public const UInt32 ApiDmaCommandInvalid = 522; public const UInt32 ApiDmaManReady = 523; public const UInt32 ApiDmaManNotReady = 524; public const UInt32 ApiDmaInvalidChannelPriority = 525; public const UInt32 ApiDmaManCorrupted = 526; public const UInt32 ApiDmaInvalidElementIndex = 527; public const UInt32 ApiDmaNoMoreElements = 528; public const UInt32 ApiDmaSglInvalid = 529; public const UInt32 ApiDmaSglQueueFull = 530; public const UInt32 ApiNullParam = 531; public const UInt32 ApiInvalidBusIndex = 532; public const UInt32 ApiUnsupportedFunction = 533; public const UInt32 ApiInvalidPciSpace = 534; public const UInt32 ApiInvalidIopSpace = 535; public const UInt32 ApiInvalidSize = 536; public const UInt32 ApiInvalidAddress = 537; public const UInt32 ApiInvalidAccessType = 538; public const UInt32 ApiInvalidIndex = 539; public const UInt32 ApiMuNotReady = 540; public const UInt32 ApiMuFifoEmpty = 541; public const UInt32 ApiMuFifoFull = 542; public const UInt32 ApiInvalidRegister = 543; public const UInt32 ApiDoorbellClearFailed = 544; public const UInt32 ApiInvalidUserPin = 545; public const UInt32 ApiInvalidUserState = 546; public const UInt32 ApiEepromNotPresent = 547; public const UInt32 ApiEepromTypeNotSupported = 548; public const UInt32 ApiEepromBlank = 549; public const UInt32 ApiConfigAccessFailed = 550; public const UInt32 ApiInvalidDeviceInfo = 551; public const UInt32 ApiNoActiveDriver = 552; public const UInt32 ApiInsufficientResources = 553; public const UInt32 ApiObjectAlreadyAllocated = 554; public const UInt32 ApiAlreadyInitialized = 555; public const UInt32 ApiNotInitialized = 556; public const UInt32 ApiBadConfigRegEndianMode = 557; public const UInt32 ApiInvalidPowerState = 558; public const UInt32 ApiPowerDown = 559; public const UInt32 ApiFlybyNotSupported = 560; public const UInt32 ApiNotSupportThisChannel = 561; public const UInt32 ApiNoAction = 562; public const UInt32 ApiHSNotSupported = 563; public const UInt32 ApiVPDNotSupported = 564; public const UInt32 ApiVpdNotEnabled = 565; public const UInt32 ApiNoMoreCap = 566; public const UInt32 ApiInvalidOffset = 567; public const UInt32 ApiBadPinDirection = 568; public const UInt32 ApiPciTimeout = 569; public const UInt32 ApiDmaChannelClosed = 570; public const UInt32 ApiDmaChannelError = 571; public const UInt32 ApiInvalidHandle = 572; public const UInt32 ApiBufferNotReady = 573; public const UInt32 ApiInvalidData = 574; public const UInt32 ApiDoNothing = 575; public const UInt32 ApiDmaSglBuildFailed = 576; public const UInt32 ApiPMNotSupported = 577; public const UInt32 ApiInvalidDriverVersion = 578; public const UInt32 ApiWaitTimeout = 579; public const UInt32 ApiWaitCanceled = 580; public const UInt32 ApiBufferTooSmall = 581; public const UInt32 ApiBufferOverflow = 582; public const UInt32 ApiInvalidBuffer = 583; public const UInt32 ApiInvalidRecordsPerBuffer = 584; public const UInt32 ApiDmaPending = 585; public const UInt32 ApiLockAndProbePagesFailed = 586; public const UInt32 ApiWaitAbandoned = 587; public const UInt32 ApiWaitFailed = 588; public const UInt32 ApiTransferComplete = 589; public const UInt32 ApiPllNotLocked = 590; public const UInt32 ApiNotSupportedInDualChannelMode = 591; public const UInt32 ApiFileIoError = 592; public const UInt32 ApiLastError = 593; #endregion #region - Board Types ----------------------------------------- public const UInt32 ATS_NONE = 0; public const UInt32 ATS850 = 1; public const UInt32 ATS310 = 2; public const UInt32 ATS330 = 3; public const UInt32 ATS855 = 4; public const UInt32 ATS315 = 5; public const UInt32 ATS335 = 6; public const UInt32 ATS460 = 7; public const UInt32 ATS860 = 8; public const UInt32 ATS660 = 9; public const UInt32 ATS665 = 10; public const UInt32 ATS9462 = 11; public const UInt32 ATS9434 = 12; public const UInt32 ATS9870 = 13; public const UInt32 ATS9350 = 14; public const UInt32 ATS_LAST = 15; #endregion #region - Memory Sizes ---------------------------------------- public const int MEM8K = 0; public const int MEM64K = 1; public const int MEM128K = 2; public const int MEM256K = 3; public const int MEM512K = 4; public const int MEM1M = 5; public const int MEM2M = 6; public const int MEM4M = 7; public const int MEM8M = 8; public const int MEM16M = 9; public const int MEM32M = 10; public const int MEM64M = 11; public const int MEM128M = 12; public const int MEM256M = 13; public const int MEM512M = 14; public const int MEM1G = 15; public const int MEM2G = 16; public const int MEM4G = 17; public const int MEM8G = 18; public const int MEM16G = 19; #endregion #region - Clock control --------------------------------------- // Clock Sources public const UInt32 INTERNAL_CLOCK = 0x00000001; public const UInt32 EXTERNAL_CLOCK = 0x00000002; public const UInt32 FAST_EXTERNAL_CLOCK = 0x00000002; public const UInt32 MEDIUM_EXTERNAL_CLOCK = 0x00000003; public const UInt32 SLOW_EXTERNAL_CLOCK = 0x00000004; public const UInt32 EXTERNAL_CLOCK_AC = 0x00000005; public const UInt32 EXTERNAL_CLOCK_DC = 0x00000006; public const UInt32 EXTERNAL_CLOCK_10MHz_REF = 0x00000007; public const UInt32 INTERNAL_CLOCK_DIV_5 = 0x000000010; // Internal Sample Rates public const UInt32 SAMPLE_RATE_1KSPS = 0x00000001; public const UInt32 SAMPLE_RATE_2KSPS = 0x00000002; public const UInt32 SAMPLE_RATE_5KSPS = 0x00000004; public const UInt32 SAMPLE_RATE_10KSPS = 0x00000008; public const UInt32 SAMPLE_RATE_20KSPS = 0x0000000A; public const UInt32 SAMPLE_RATE_50KSPS = 0x0000000C; public const UInt32 SAMPLE_RATE_100KSPS = 0x0000000E; public const UInt32 SAMPLE_RATE_200KSPS = 0x00000010; public const UInt32 SAMPLE_RATE_500KSPS = 0x00000012; public const UInt32 SAMPLE_RATE_1MSPS = 0x00000014; public const UInt32 SAMPLE_RATE_2MSPS = 0x00000018; public const UInt32 SAMPLE_RATE_5MSPS = 0x0000001A; public const UInt32 SAMPLE_RATE_10MSPS = 0x0000001C; public const UInt32 SAMPLE_RATE_20MSPS = 0x0000001E; public const UInt32 SAMPLE_RATE_25MSPS = 0x00000021; public const UInt32 SAMPLE_RATE_50MSPS = 0x00000022; public const UInt32 SAMPLE_RATE_100MSPS = 0x00000024; public const UInt32 SAMPLE_RATE_125MSPS = 0x00000025; public const UInt32 SAMPLE_RATE_200MSPS = 0x00000028; public const UInt32 SAMPLE_RATE_250MSPS = 0x0000002B; public const UInt32 SAMPLE_RATE_500MSPS = 0x00000030; public const UInt32 SAMPLE_RATE_1GSPS = 0x00000035; public const UInt32 SAMPLE_RATE_2GSPS = 0x0000003A; public const UInt32 SAMPLE_RATE_USER_DEF = 0x00000040; public const UInt32 PLL_10MHZ_REF_100MSPS_BASE = 0x05F5E100; // Clock Edges public const UInt32 CLOCK_EDGE_RISING = 0x00000000; public const UInt32 CLOCK_EDGE_FALLING = 0x00000001; // Decimation public const UInt32 DECIMATE_BY_8 = 0x00000008; public const UInt32 DECIMATE_BY_64 = 0x00000040; #endregion #region - Input Control --------------------------------------- // Input Channels public const UInt32 CHANNEL_ALL = 0x00000000; public const UInt32 CHANNEL_A = 0x00000001; public const UInt32 CHANNEL_B = 0x00000002; public const UInt32 CHANNEL_C = 0x00000003; public const UInt32 CHANNEL_D = 0x00000004; public const UInt32 CHANNEL_E = 0x00000005; public const UInt32 CHANNEL_F = 0x00000006; public const UInt32 CHANNEL_G = 0x00000007; public const UInt32 CHANNEL_H = 0x00000008; // Input Ranges public const UInt32 INPUT_RANGE_PM_20_MV = 0x00000001; public const UInt32 INPUT_RANGE_PM_40_MV = 0x00000002; public const UInt32 INPUT_RANGE_PM_50_MV = 0x00000003; public const UInt32 INPUT_RANGE_PM_80_MV = 0x00000004; public const UInt32 INPUT_RANGE_PM_100_MV = 0x00000005; public const UInt32 INPUT_RANGE_PM_200_MV = 0x00000006; public const UInt32 INPUT_RANGE_PM_400_MV = 0x00000007; public const UInt32 INPUT_RANGE_PM_500_MV = 0x00000008; public const UInt32 INPUT_RANGE_PM_800_MV = 0x00000009; public const UInt32 INPUT_RANGE_PM_1_V = 0x0000000A; public const UInt32 INPUT_RANGE_PM_2_V = 0x0000000B; public const UInt32 INPUT_RANGE_PM_4_V = 0x0000000C; public const UInt32 INPUT_RANGE_PM_5_V = 0x0000000D; public const UInt32 INPUT_RANGE_PM_8_V = 0x0000000E; public const UInt32 INPUT_RANGE_PM_10_V = 0x0000000F; public const UInt32 INPUT_RANGE_PM_20_V = 0x00000010; public const UInt32 INPUT_RANGE_PM_40_V = 0x00000011; public const UInt32 INPUT_RANGE_PM_16_V = 0x00000012; public const UInt32 INPUT_RANGE_HIFI = 0x00000020; // Input Impedances public const UInt32 IMPEDANCE_1M_OHM = 0x00000001; public const UInt32 IMPEDANCE_50_OHM = 0x00000002; public const UInt32 IMPEDANCE_75_OHM = 0x00000004; public const UInt32 IMPEDANCE_300_OHM = 0x00000008; // Input Couplings public const UInt32 AC_COUPLING = 0x00000001; public const UInt32 DC_COUPLING = 0x00000002; #endregion #region - Trigger Control ------------------------------------ // Trigger Engines public const UInt32 TRIG_ENGINE_J = 0x00000000; public const UInt32 TRIG_ENGINE_K = 0x00000001; // Trigger Engine Operations public const UInt32 TRIG_ENGINE_OP_J = 0x00000000; public const UInt32 TRIG_ENGINE_OP_K = 0x00000001; public const UInt32 TRIG_ENGINE_OP_J_OR_K = 0x00000002; public const UInt32 TRIG_ENGINE_OP_J_AND_K = 0x00000003; public const UInt32 TRIG_ENGINE_OP_J_XOR_K = 0x00000004; public const UInt32 TRIG_ENGINE_OP_J_AND_NOT_K = 0x00000005; public const UInt32 TRIG_ENGINE_OP_NOT_J_AND_K = 0x00000006; // Trigger Engine Sources public const UInt32 TRIG_CHAN_A = 0x00000000; public const UInt32 TRIG_CHAN_B = 0x00000001; public const UInt32 TRIG_EXTERNAL = 0x00000002; public const UInt32 TRIG_DISABLE = 0x00000003; // Trigger Slopes public const UInt32 TRIGGER_SLOPE_POSITIVE = 0x00000001; public const UInt32 TRIGGER_SLOPE_NEGATIVE = 0x00000002; // External Trigger Ranges public const UInt32 ETR_DIV5 = 0x00000000; public const UInt32 ETR_X1 = 0x00000001; public const UInt32 ETR_5V = 0x00000000; public const UInt32 ETR_1V = 0x00000001; #endregion #region - AUX_IO and LED Control ------------------------------ // Inputs public const UInt32 AUX_OUT_TRIGGER = 0; public const UInt32 AUX_OUT_PACER = 2; public const UInt32 AUX_OUT_BUSY = 4; public const UInt32 AUX_OUT_CLOCK = 6; public const UInt32 AUX_OUT_RESERVED = 8; public const UInt32 AUX_OUT_CAPTURE_ALMOST_DONE = 10; public const UInt32 AUX_OUT_AUXILIARY = 12; public const UInt32 AUX_OUT_SERIAL_DATA = 14; public const UInt32 AUX_OUT_TRIGGER_ENABLE = 20; // Outputs public const UInt32 AUX_IN_TRIGGER_ENABLE = 1; public const UInt32 AUX_IN_DIGITAL_TRIGGER = 3; public const UInt32 AUX_IN_GATE = 5; public const UInt32 AUX_IN_CAPTURE_ON_DEMAND = 7; public const UInt32 AUX_IN_RESET_TIMESTAMP = 9; public const UInt32 AUX_IN_SLOW_EXTERNAL_CLOCK = 11; public const UInt32 AUX_INPUT_AUXILIARY = 13; public const UInt32 AUX_INPUT_SERIAL_DATA = 15; // LED states public const UInt32 LED_OFF = 0x00000000; public const UInt32 LED_ON = 0x00000001; #endregion #region - Set / Get Parameters -------------------------------- public const UInt32 NUMBER_OF_RECORDS = 0x10000001; public const UInt32 PRETRIGGER_AMOUNT = 0x10000002; public const UInt32 RECORD_LENGTH = 0x10000003; public const UInt32 TRIGGER_ENGINE = 0x10000004; public const UInt32 TRIGGER_DELAY = 0x10000005; public const UInt32 TRIGGER_TIMEOUT = 0x10000006; public const UInt32 SAMPLE_RATE = 0x10000007; public const UInt32 CONFIGURATION_MODE = 0x10000008; //Independent, Master/Slave, Last Slave public const UInt32 DATA_WIDTH = 0x10000009; //8,16,32 bits - Digital IO boards public const UInt32 SAMPLE_SIZE = DATA_WIDTH; //8,12,16 - Analog Input boards public const UInt32 AUTO_CALIBRATE = 0x1000000A; public const UInt32 TRIGGER_XXXXX = 0x1000000B; public const UInt32 CLOCK_SOURCE = 0x1000000C; public const UInt32 CLOCK_SLOPE = 0x1000000D; public const UInt32 IMPEDANCE = 0x1000000E; public const UInt32 INPUT_RANGE = 0x1000000F; public const UInt32 COUPLING = 0x10000010; public const UInt32 MAX_TIMEOUTS_ALLOWED = 0x10000011; public const UInt32 ATS_OPERATING_MODE = 0x10000012; //Single, Dual, Quad etc... public const UInt32 CLOCK_DECIMATION_EXTERNAL = 0x10000013; public const UInt32 LED_CONTROL = 0x10000014; public const UInt32 ATTENUATOR_RELAY = 0x10000018; public const UInt32 EXT_TRIGGER_COUPLING = 0x1000001A; public const UInt32 EXT_TRIGGER_ATTENUATOR_RELAY = 0x1000001C; public const UInt32 TRIGGER_ENGINE_SOURCE = 0x1000001E; public const UInt32 TRIGGER_ENGINE_SLOPE = 0x10000020; public const UInt32 SEND_DAC_VALUE = 0x10000021; public const UInt32 SLEEP_DEVICE = 0x10000022; public const UInt32 GET_DAC_VALUE = 0x10000023; public const UInt32 GET_SERIAL_NUMBER = 0x10000024; public const UInt32 GET_FIRST_CAL_DATE = 0x10000025; public const UInt32 GET_LATEST_CAL_DATE = 0x10000026; public const UInt32 GET_LATEST_TEST_DATE = 0x10000027; public const UInt32 GET_LATEST_CAL_DATE_MONTH = 0x1000002D; public const UInt32 GET_LATEST_CAL_DATE_DAY = 0x1000002E; public const UInt32 GET_LATEST_CAL_DATE_YEAR = 0x1000002F; public const UInt32 GET_PCIE_LINK_SPEED = 0x10000030; public const UInt32 GET_PCIE_LINK_WIDTH = 0x10000031; public const UInt32 SETGET_ASYNC_BUFFCOUNT = 0x10000040; public const UInt32 SET_DATA_FORMAT = 0x10000041; public const UInt32 GET_DATA_FORMAT = 0x10000042; public const UInt32 DATA_FORMAT_UNSIGNED = 0; public const UInt32 DATA_FORMAT_SIGNED = 1; public const UInt32 SET_SINGLE_CHANNEL_MODE = 0x10000043; public const UInt32 MEMORY_SIZE = 0x1000002A; public const UInt32 BOARD_TYPE = 0x1000002B; public const UInt32 ASOPC_TYPE = 0x1000002C; public const UInt32 GET_BOARD_OPTIONS_LOW = 0x10000037; public const UInt32 GET_BOARD_OPTIONS_HIGH = 0x10000038; public const UInt32 OPTION_STREAMING_DMA = (1U << 0); public const UInt32 OPTION_AVERAGE_INPUT = (1U << 1); public const UInt32 OPTION_EXTERNAL_CLOCK = (1U << 1); public const UInt32 OPTION_DUAL_PORT_MEMORY = (1U << 2); public const UInt32 OPTION_180MHZ_OSCILLATOR = (1U << 3); public const UInt32 OPTION_LVTTL_EXT_CLOCK = (1U << 4); public const UInt32 OPTION_OEM_FPGA = (1U << 47); public const UInt32 TRANSFER_OFFET = 0x10000030; public const UInt32 TRANSFER_LENGTH = 0x10000031; public const UInt32 TRANSFER_RECORD_OFFSET = 0x10000032; public const UInt32 TRANSFER_NUM_OF_RECORDS = 0x10000033; public const UInt32 TRANSFER_MAPPING_RATIO = 0x10000034; public const UInt32 TRIGGER_ADDRESS_AND_TIMESTAMP = 0x10000035; public const UInt32 MASTER_SLAVE_INDEPENDENT = 0x10000036; public const UInt32 TRIGGERED = 0x10000040; public const UInt32 BUSY = 0x10000041; public const UInt32 WHO_TRIGGERED = 0x10000042; public const UInt32 GET_ASYNC_BUFFERS_PENDING = 0x10000050; public const UInt32 GET_ASYNC_BUFFERS_PENDING_FULL = 0x10000051; public const UInt32 GET_ASYNC_BUFFERS_PENDING_EMPTY = 0x10000052; public const UInt32 ACF_SAMPLES_PER_RECORD = 0x10000060; public const UInt32 ACF_RECORDS_TO_AVERAGE = 0x10000061; // Master/Slave Configuration public const UInt32 BOARD_IS_INDEPENDENT = 0x00000000; public const UInt32 BOARD_IS_MASTER = 0x00000001; public const UInt32 BOARD_IS_SLAVE = 0x00000002; public const UInt32 BOARD_IS_LAST_SLAVE = 0x00000003; // Attenuator Relay public const UInt32 AR_X1 = 0x00000000; public const UInt32 AR_DIV40 = 0x00000001; // Device Sleep state public const UInt32 POWER_OFF = 0x00000000; public const UInt32 POWER_ON = 0x00000001; // Software Events control public const UInt32 SW_EVENTS_OFF = 0x00000000; public const UInt32 SW_EVENTS_ON = 0x00000001; // TimeStamp Value Reset Control public const UInt32 TIMESTAMP_RESET_FIRSTTIME_ONLY = 0x00000000; public const UInt32 TIMESTAMP_RESET_ALWAYS = 0x00000001; // DAC Names used by API AlazarDACSettingAdjust public const UInt32 ATS460_DAC_A_GAIN = 0x00000001; public const UInt32 ATS460_DAC_A_OFFSET = 0x00000002; public const UInt32 ATS460_DAC_A_POSITION = 0x00000003; public const UInt32 ATS460_DAC_B_GAIN = 0x00000009; public const UInt32 ATS460_DAC_B_OFFSET = 0x0000000A; public const UInt32 ATS460_DAC_B_POSITION = 0x0000000B; // Error return values public const UInt32 SETDAC_INVALID_SETGET = 660; public const UInt32 SETDAC_INVALID_CHANNEL = 661; public const UInt32 SETDAC_INVALID_DACNAME = 662; public const UInt32 SETDAC_INVALID_COUPLING = 663; public const UInt32 SETDAC_INVALID_RANGE = 664; public const UInt32 SETDAC_INVALID_IMPEDANCE = 665; public const UInt32 SETDAC_BAD_GET_PTR = 667; public const UInt32 SETDAC_INVALID_BOARDTYPE = 668; // Constants to be used in the Application when dealing with Custom FPGAs public const UInt32 FPGA_GETFIRST = 0xFFFFFFFF; public const UInt32 FPGA_GETNEXT = 0xFFFFFFFE; public const UInt32 FPGA_GETLAST = 0xFFFFFFFC; // Global API Functions public const int KINDEPENDENT = 0; public const int KSLAVE = 1; public const int KMASTER = 2; public const int KLASTSLAVE = 3; #endregion #region - AutoDMA Control ------------------------------------- // AutoDMA flags public const UInt32 ADMA_EXTERNAL_STARTCAPTURE = 0x00000001; public const UInt32 ADMA_ENABLE_RECORD_HEADERS = 0x00000008; public const UInt32 ADMA_SINGLE_DMA_CHANNEL = 0x00000010; public const UInt32 ADMA_ALLOC_BUFFERS = 0x00000020; public const UInt32 ADMA_TRADITIONAL_MODE = 0x00000000; public const UInt32 ADMA_CONTINUOUS_MODE = 0x00000100; public const UInt32 ADMA_NPT = 0x00000200; public const UInt32 ADMA_TRIGGERED_STREAMING = 0x00000400; public const UInt32 ADMA_FIFO_ONLY_STREAMING = 0x00000800; public const UInt32 ADMA_INTERLEAVE_SAMPLES = 0x00001000; public const UInt32 ADMA_GET_PROCESSED_DATA = 0x00002000; public const UInt32 ADMA_STREAM_TO_DISK = 0x00004000; // AutoDMA header constants public const UInt32 ADMA_CLOCKSOURCE = 0x00000001; public const UInt32 ADMA_CLOCKEDGE = 0x00000002; public const UInt32 ADMA_SAMPLERATE = 0x00000003; public const UInt32 ADMA_INPUTRANGE = 0x00000004; public const UInt32 ADMA_INPUTCOUPLING = 0x00000005; public const UInt32 ADMA_IMPUTIMPEDENCE = 0x00000006; public const UInt32 ADMA_EXTTRIGGERED = 0x00000007; public const UInt32 ADMA_CHA_TRIGGERED = 0x00000008; public const UInt32 ADMA_CHB_TRIGGERED = 0x00000009; public const UInt32 ADMA_TIMEOUT = 0x0000000A; public const UInt32 ADMA_THISCHANTRIGGERED = 0x0000000B; public const UInt32 ADMA_SERIALNUMBER = 0x0000000C; public const UInt32 ADMA_SYSTEMNUMBER = 0x0000000D; public const UInt32 ADMA_BOARDNUMBER = 0x0000000E; public const UInt32 ADMA_WHICHCHANNEL = 0x0000000F; public const UInt32 ADMA_SAMPLERESOLUTION = 0x00000010; public const UInt32 ADMA_DATAFORMAT = 0x00000011; // _HEADER0 - UInt32 type with the following format // SerialNumber size 18 bits // SystemNumber size 4 bits // WhichChannel size 1 bits // BoardNumber size 4 bits // SampleResolution size 3 bits // DataFormat size 2 bits // struct _HEADER0 { public UInt32 u;} // _HEADER1 - UInt32 type with the following format // RecordNumber size 24 bits // BoardType size 8 bits // struct _HEADER1 { public UInt32 u;} // _HEADER2 - UInt32 type with the following format // TimeStampLowPart all 32 bits // struct _HEADER2 { public UInt32 u;} // _HEADER3 - UInt32 type with the following format // TimeStampHighPart size 8 bits // ClockSource size 2 bits // ClockEdge size 1 bits // SampleRate size 7 bits // InputRange size 5 bits // InputCoupling size 2 bits // InputImpedence size 2 bits // ExternalTriggered size 1 bits // ChannelBTriggered size 1 bits // ChannelATriggered size 1 bits // TimeOutOccurred size 1 bits // ThisChannelTriggered size 1 bits // public struct _HEADER3 { public UInt32 u;} // struct ALAZAR_HEADER { // public _HEADER0 hdr0; // public _HEADER1 hdr1; // public _HEADER2 hdr2; // public _HEADER3 hdr3; // } public enum AUTODMA_STATUS { ADMA_Completed = 0, ADMA_Success = 0, ADMA_Buffer1Invalid, ADMA_Buffer2Invalid, ADMA_BoardHandleInvalid, ADMA_InternalBuffer1Invalid, ADMA_InternalBuffer2Invalid, ADMA_OverFlow, ADMA_InvalidChannel, ADMA_DMAInProgress, ADMA_UseHeaderNotSet, ADMA_HeaderNotValid, ADMA_InvalidRecsPerBuffer, ADMA_InvalidTransferOffset } //public const UInt32 ADMA_Success = AUTODMA_STATUS.ADMA_Completed; #endregion #endregion #region - Functions ------------------------------------------------- #region - Status and Information ------------------------------ [DllImport("ATSApi.dll")] public static extern UInt32 AlazarBoardsFound(); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarGetBoardKind(IntPtr h); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetCPLDVersion(IntPtr h, byte* Major, byte* Minor); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetChannelInfo(IntPtr h, UInt32* MemSize, byte* SampleSize); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetSDKVersion(byte* Major, byte* Minor, byte* Revision); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetDriverVersion(byte* Major, byte* Minor, byte* Revision); [DllImport("ATSApi.dll")] public static extern IntPtr AlazarGetSystemHandle(UInt32 sid); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarNumOfSystems(); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarBoardsInSystemBySystemID(UInt32 sid); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarBoardsInSystemBySystemHandle(IntPtr systemHandle); [DllImport("ATSApi.dll")] public static extern IntPtr AlazarGetBoardBySystemID(UInt32 sid, UInt32 brdNum); [DllImport("ATSApi.dll")] public static extern IntPtr AlazarGetBoardBySystemHandle(IntPtr systemHandle, UInt32 brdNum); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarQueryCapability(IntPtr h, UInt32 request, UInt32 value, UInt32* retValue); [DllImport("AtsApi.dll")] [return: MarshalAs(UnmanagedType.LPStr)] public static extern string AlazarErrorToText(UInt32 retCode); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetParameter(IntPtr h, byte channel, UInt32 parameter, Int32* retValue); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetParameterUL(IntPtr h, byte channel, UInt32 parameter, UInt32* retValue); #endregion #region - Board Configuration --------------------------------- [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetCaptureClock(IntPtr h, UInt32 Source, UInt32 Rate, UInt32 Edge, UInt32 Decimation); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetExternalClockLevel(IntPtr h, float level_percent); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarInputControl(IntPtr h, System.UInt32 Channel, UInt32 Coupling, UInt32 InputRange, UInt32 Impedance); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetPosition(IntPtr h, UInt32 Channel, int PMPercent, UInt32 InputRange); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetExternalTrigger(IntPtr h, UInt32 Coupling, UInt32 Range); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetTriggerDelay(IntPtr h, UInt32 Delay); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetTriggerTimeOut(IntPtr h, UInt32 to_ns); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarTriggerTimedOut(IntPtr h); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetTriggerOperation(IntPtr h, UInt32 TriggerOperation , UInt32 TriggerEngine1/*j,K*/, UInt32 Source1, UInt32 Slope1, UInt32 Level1 , UInt32 TriggerEngine2/*j,K*/, UInt32 Source2, UInt32 Slope2, UInt32 Level2); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetBWLimit(IntPtr h, UInt32 Channel, UInt32 enable); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSleepDevice(IntPtr h, UInt32 state); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetLED(IntPtr h, UInt32 state); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarConfigureAuxIO(IntPtr board, UInt32 mode, UInt32 parameter); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetParameter(IntPtr hDevice, byte channel, UInt32 parameter, Int32 value); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetParameterUL(IntPtr hDevice, byte channel, UInt32 parameter, UInt32 value); #endregion #region - General Acquisition --------------------------------- [DllImport("ATSApi.dll")] public static extern UInt32 AlazarStartCapture(IntPtr handle); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarBusy(IntPtr h); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarTriggered(IntPtr h); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetRecordSize(IntPtr h, UInt32 PreSize, UInt32 PostSize); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarForceTrigger(IntPtr handle); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarForceTriggerEnable(IntPtr handle); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarResetTimeStamp(IntPtr h, UInt32 resetFlag); #endregion #region - Single-Port DMA ------------------------------------- [DllImport("ATSApi.dll")] public unsafe static extern UInt32 AlazarRead(IntPtr h, UInt32 Channel, void* Buf, Int32 ElementSize, Int32 Record, Int32 TransferOffset, UInt32 TransferLength); [DllImport("ATSApi.dll")] public unsafe static extern UInt32 AlazarHyperDisp(IntPtr h, void* Buffer, UInt32 BufferSize, byte* ViewBuffer, UInt32 ViewBufferSize, UInt32 NumOfPixels, UInt32 Option, UInt32 ChannelSelect, UInt32 Record, int TransferOffset, UInt32 * error); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarDetectMultipleRecord(IntPtr h); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarSetRecordCount(IntPtr h, UInt32 Count); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarGetStatus(IntPtr h); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarAbortCapture(IntPtr handle); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarMaxSglTransfer(UInt32 bt); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetMaxRecordsCapable(IntPtr h, UInt32 RecordLength, UInt32* num); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarGetWhoTriggeredBySystemHandle(IntPtr systemHandle, UInt32 brdNum, UInt32 recNum); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarGetWhoTriggeredBySystemID(UInt32 sid, UInt32 brdNum, UInt32 recNum); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetTriggerAddress(IntPtr h, UInt32 Record, UInt32* TriggerAddress, UInt32* TimeStampHighPart, UInt32* TimeStampLowPart); #endregion #region - Dual-Port Asynchronous AutoDMA ---------------------- [DllImport("ATSApi.dll")] public static extern UInt32 AlazarBeforeAsyncRead(IntPtr BoardHandle, UInt32 ChannelSelect, Int32 TransferOffset, UInt32 SamplesPerRecord, UInt32 RecordsPerBuffer, UInt32 RecordsPerAcquisition, UInt32 AutoDmaFlags); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarAbortAsyncRead(IntPtr BoardHandle); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarPostAsyncBuffer(IntPtr BoardHandle, void* Buffer, UInt32 BufferSize); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarWaitAsyncBufferComplete(IntPtr BoardHandle, void* Buffer, UInt32 Timeout_ms); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarWaitNextAsyncBufferComplete(IntPtr BoardHandle, void* Buffer, UInt32 BufferLength_bytes, UInt32 Timeout_ms); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarCreateStreamFileA(IntPtr BoardHandle, [MarshalAs(UnmanagedType.LPStr)] string Path); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarCreateStreamFileW(IntPtr BoardHandle, [MarshalAs(UnmanagedType.LPWStr)] string Path); #endregion #region - Dual-Port Synchronous AutoDMA ----------------------- [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarStartAutoDMA has been deprecated.")] public static extern unsafe UInt32 AlazarStartAutoDMA(IntPtr h, void* Buffer1, UInt32 UseHeader, UInt32 ChannelSelect, Int32 TransferOffset, UInt32 TransferLength, Int32 RecordsPerBuffer, Int32 RecordCount, AUTODMA_STATUS* error, UInt32 r1, UInt32 r2, UInt32* r3, UInt32* r4); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarGetNextAutoDMABuffer has been deprecated.")] public static extern unsafe UInt32 AlazarGetNextAutoDMABuffer(IntPtr h, void* Buffer1, void* Buffer2, Int32* WhichOne, Int32* RecordsTransfered, AUTODMA_STATUS* error, UInt32 r1, UInt32 r2, Int32* TriggersOccurred, UInt32* r4); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarGetNextBuffer has been deprecated.")] public static extern unsafe UInt32 AlazarGetNextBuffer(IntPtr h, void* Buffer1, void* Buffer2, Int32* WhichOne, Int32* RecordsTransfered, AUTODMA_STATUS* error, UInt32 r1, UInt32 r2, Int32* TriggersOccurred, UInt32* r4); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarCloseAUTODma has been deprecated.")] public static extern UInt32 AlazarCloseAUTODma(IntPtr h); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarAbortAutoDMA has been deprecated.")] public static extern unsafe UInt32 AlazarAbortAutoDMA(IntPtr h, void* Buffer, AUTODMA_STATUS* error, UInt32 r1, UInt32 r2, UInt32* r3, UInt32* r4); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetAutoDMAHeaderValue(IntPtr h, UInt32 Channel, void* DataBuffer, UInt32 Record, UInt32 Parameter, AUTODMA_STATUS* error); [DllImport("ATSApi.dll")] public static extern unsafe float AlazarGetAutoDMAHeaderTimeStamp(IntPtr h, UInt32 Channel, void* DataBuffer, UInt32 Record, AUTODMA_STATUS* error); [DllImport("ATSApi.dll")] public static extern unsafe void* AlazarGetAutoDMAPtr(IntPtr h, UInt32 DataOrHeader, UInt32 Channel, void* DataBuffer, UInt32 Record, AUTODMA_STATUS* error); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarWaitForBufferReady has been deprecated.")] public static extern UInt32 AlazarWaitForBufferReady(IntPtr h, Int32 tms); [DllImport("ATSApi.dll")] [ObsoleteAttribute("AlazarEvents has been deprecated.")] public static extern UInt32 AlazarEvents(IntPtr h, UInt32 enable); #endregion #region - Other ----------------------------------------------- [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarGetOEMFPGAName(int opcodeID, [MarshalAs(UnmanagedType.LPStr)] string FullPath, UInt32* error); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarOEMSetWorkingDirectory([MarshalAs(UnmanagedType.LPStr)] string wDir, UInt32* error); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarOEMGetWorkingDirectory([MarshalAs(UnmanagedType.LPStr)] string wDir, UInt32* error); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarParseFPGAName([MarshalAs(UnmanagedType.LPStr)] string FullName, byte* Name, UInt32* Type1, UInt32* MemSize, UInt32* MajVer, UInt32* MinVer, UInt32* MajRev, UInt32* MinRev, UInt32* error); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarOEMDownLoadFPGA(IntPtr h, [MarshalAs(UnmanagedType.LPStr)] string FileName, UInt32* RetValue); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarDownLoadFPGA(IntPtr h, [MarshalAs(UnmanagedType.LPStr)] string FileName, UInt32* RetValue); [DllImport("ATSApi.dll")] public static extern UInt32 AlazarWriteRegister(IntPtr hDevice, UInt32 offset, UInt32 Val, UInt32 pswrd); [DllImport("ATSApi.dll")] public static extern unsafe UInt32 AlazarReadRegister(IntPtr hDevice, UInt32 offset, UInt32* retVal, UInt32 pswrd); #endregion #endregion } }
#if !NETSTANDARD using System; using System.Collections.Generic; using System.Text; using FileHelpers.Dynamic; using System.IO; namespace FileHelpers.Detection { /// <summary> /// Utility class used to auto detect the record format, /// the number of fields, the type, etc. /// </summary> public sealed class SmartFormatDetector { /// <summary> /// Initializes a new instance of the <see cref="SmartFormatDetector"/> class. /// </summary> public SmartFormatDetector() { QuotedChar = '"'; } #region " Constants " private const int MinSampleData = 10; private const double MinDelimitedDeviation = 0.30001; #endregion #region " Properties " private FormatHint mFormatHint; /// <summary> /// Provides a suggestion to the <see cref="SmartFormatDetector"/> /// about the records in the file /// </summary> public FormatHint FormatHint { get { return mFormatHint; } set { mFormatHint = value; } } private int mMaxSampleLines = 300; /// <summary> /// The number of lines of each file to be used as sample data. /// </summary> public int MaxSampleLines { get { return mMaxSampleLines; } set { mMaxSampleLines = value; } } private Encoding mEncoding = Encoding.GetEncoding(0); /// <summary>The encoding to Read and Write the streams.</summary> /// <remarks>Default is the system's current ANSI code page.</remarks> public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } private double mFixedLengthDeviationTolerance = 0.01; ///<summary> ///Indicates if the sample file has headers ///</summary> public bool? FileHasHeaders { get; set; } /// <summary> /// Used to calculate when a file has fixed length records. /// Between 0.0 - 1.0 (Default 0.01) /// </summary> public double FixedLengthDeviationTolerance { get { return mFixedLengthDeviationTolerance; } set { mFixedLengthDeviationTolerance = value; } } #endregion #region " Public Methods " /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="file">The file to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(string file) { return DetectFileFormat(new string[] {file}); } /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="files">The files to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(IEnumerable<string> files) { var readers = new List<TextReader>(); foreach (var file in files) { readers.Add(new StreamReader(file, Encoding)); } var res = DetectFileFormat(readers); foreach (var reader in readers) { reader.Close(); } return res; } /// <summary> /// Tries to detect the possible formats of the file using the <see cref="FormatHint"/> /// </summary> /// <param name="files">The files to be used as sample data</param> /// <returns>The possible <see cref="RecordFormatInfo"/> of the file.</returns> public RecordFormatInfo[] DetectFileFormat(IEnumerable<TextReader> files) { var res = new List<RecordFormatInfo>(); string[][] sampleData = GetSampleLines(files, MaxSampleLines); switch (mFormatHint) { case FormatHint.Unknown: CreateMixedOptions(sampleData, res); break; case FormatHint.FixedLength: CreateFixedLengthOptions(sampleData, res); break; case FormatHint.Delimited: CreateDelimiterOptions(sampleData, res); break; case FormatHint.DelimitedByTab: CreateDelimiterOptions(sampleData, res, '\t'); break; case FormatHint.DelimitedByComma: CreateDelimiterOptions(sampleData, res, ','); break; case FormatHint.DelimitedBySemicolon: CreateDelimiterOptions(sampleData, res, ';'); break; default: throw new InvalidOperationException("Unsuported FormatHint value."); } foreach (var option in res) { DetectOptionals(option, sampleData); DetectTypes(option, sampleData); DetectQuoted(option, sampleData); } // Sort by confidence res.Sort( delegate(RecordFormatInfo x, RecordFormatInfo y) { return -1*x.Confidence.CompareTo(y.Confidence); }); return res.ToArray(); } #endregion #region " Fields Properties Methods " private void DetectQuoted(RecordFormatInfo format, string[][] data) { if (format.ClassBuilder is FixedLengthClassBuilder) return; // TODO: Add FieldQuoted } private void DetectTypes(RecordFormatInfo format, string[][] data) { // TODO: Try to detect posible formats (mostly numbers or dates) } private void DetectOptionals(RecordFormatInfo option, string[][] data) { // TODO: Try to detect optional fields } #endregion #region " Create Options Methods " // UNKNOWN private void CreateMixedOptions(string[][] data, List<RecordFormatInfo> res) { var stats = Indicators.CalculateAsFixedSize (data); if (stats.Deviation / stats.Avg <= FixedLengthDeviationTolerance * Math.Min (1, NumberOfLines (data) / MinSampleData)) CreateFixedLengthOptions(data, res); CreateDelimiterOptions(data, res); //if (deviation > average * 0.01 && // deviation < average * 0.05) // CreateFixedLengthOptions(data, res); } // FIXED LENGTH private void CreateFixedLengthOptions(string[][] data, List<RecordFormatInfo> res) { var format = new RecordFormatInfo(); var stats = Indicators.CalculateAsFixedSize (data); format.mConfidence = (int)(Math.Max (0, 1 - stats.Deviation / stats.Avg) * 100); var builder = new FixedLengthClassBuilder("AutoDetectedClass"); CreateFixedLengthFields(data, builder); format.mClassBuilder = builder; res.Add(format); } /// <summary> /// start and length of fixed length column /// </summary> private class FixedColumnInfo { /// <summary> /// start position of column /// </summary> public int Start; /// <summary> /// Length of column /// </summary> public int Length; } private void CreateFixedLengthFields(string[][] data, FixedLengthClassBuilder builder) { List<FixedColumnInfo> res = null; foreach (var dataFile in data) { List<FixedColumnInfo> candidates = CreateFixedLengthCandidates(dataFile); res = JoinFixedColCandidates(res, candidates); } for (int i = 0; i < res.Count; i++) { FixedColumnInfo col = res[i]; builder.AddField("Field" + i.ToString().PadLeft(4, '0'), col.Length, typeof (string)); } } private List<FixedColumnInfo> CreateFixedLengthCandidates(string[] lines) { List<FixedColumnInfo> res = null; foreach (var line in lines) { var candidates = new List<FixedColumnInfo>(); int blanks = 0; FixedColumnInfo col = null; for (int i = 1; i < line.Length; i++) { if (char.IsWhiteSpace(line[i])) blanks += 1; else { if (blanks > 2) { if (col == null) { col = new FixedColumnInfo { Start = 0, Length = i }; } else { FixedColumnInfo prevCol = col; col = new FixedColumnInfo { Start = prevCol.Start + prevCol.Length }; col.Length = i - col.Start; } candidates.Add(col); blanks = 0; } } } if (col == null) { col = new FixedColumnInfo { Start = 0, Length = line.Length }; } else { FixedColumnInfo prevCol = col; col = new FixedColumnInfo { Start = prevCol.Start + prevCol.Length }; col.Length = line.Length - col.Start; } candidates.Add(col); res = JoinFixedColCandidates(res, candidates); } return res; } private List<FixedColumnInfo> JoinFixedColCandidates(List<FixedColumnInfo> cand1, List<FixedColumnInfo> cand2) { if (cand1 == null) return cand2; if (cand2 == null) return cand1; // Merge the result based on confidence return cand1; } bool HeadersInData (DelimiterInfo info, string[] headerValues, string[] rows) { var duplicate = 0; var first = true; foreach (var row in rows) { if (first) { first = false; continue; } var values = row.Split (new char[]{ info.Delimiter }); if (values.Length != headerValues.Length) continue; for (int i = 0; i < values.Length; i++) { if (values [i] == headerValues [i]) duplicate++; } } return duplicate >= rows.Length * 0.25; } bool DetectIfContainsHeaders (DelimiterInfo info, string[][] sampleData) { if (sampleData.Length >= 2) { return SameFirstLine (info, sampleData); } if (sampleData.Length >= 1) { var firstLine = sampleData [0] [0].Split (new char[]{ info.Delimiter }); var res = AreAllHeaders (firstLine); if (res == false) return false; // if has headers that starts with numbers so near sure are data and no header is present if (HeadersInData(info, firstLine, sampleData[0])) return false; return true; } return false; } bool SameFirstLine (DelimiterInfo info, string[][] sampleData) { for (int i = 1; i < sampleData.Length; i++) { if (!SameHeaders (info, sampleData [0][0], sampleData [i][0])) return false; } return true; } bool SameHeaders (DelimiterInfo info, string line1, string line2) { return line1.Replace (info.Delimiter.ToString (), "").Trim () == line2.Replace (info.Delimiter.ToString (), "").Trim (); } bool AreAllHeaders ( string[] rowData) { foreach (var item in rowData) { var fieldData = item.Trim (); if (fieldData.Length == 0) return false; if (char.IsDigit (fieldData [0])) return false; } return true; } // DELIMITED private void CreateDelimiterOptions(string[][] sampleData, List<RecordFormatInfo> res, char delimiter = '\0') { var delimiters = new List<DelimiterInfo>(); if (delimiter == '\0') delimiters = GetDelimiters(sampleData); else delimiters.Add(GetDelimiterInfo(sampleData, delimiter)); foreach (var info in delimiters) { var format = new RecordFormatInfo { mConfidence = (int) ((1 - info.Deviation)*100) }; AdjustConfidence(format, info); var fileHasHeaders = false; if (FileHasHeaders.HasValue) fileHasHeaders = FileHasHeaders.Value; else { fileHasHeaders = DetectIfContainsHeaders (info, sampleData) ; } var builder = new DelimitedClassBuilder("AutoDetectedClass", info.Delimiter.ToString()) { IgnoreFirstLines = fileHasHeaders ? 1 : 0 }; var firstLineSplitted = sampleData[0][0].Split(info.Delimiter); for (int i = 0; i < info.Max + 1; i++) { string name = "Field " + (i + 1).ToString().PadLeft(3, '0'); if (fileHasHeaders && i < firstLineSplitted.Length) name = firstLineSplitted[i]; var f = builder.AddField(StringHelper.ToValidIdentifier(name)); if (i > info.Min) f.FieldOptional = true; } format.mClassBuilder = builder; res.Add(format); } } private void AdjustConfidence(RecordFormatInfo format, DelimiterInfo info) { switch (info.Delimiter) { case '"': // Avoid the quote identifier case '\'': // Avoid the quote identifier format.mConfidence = (int) (format.Confidence*0.2); break; case '/': // Avoid the date delimiters and url to be selected case '.': // Avoid the decimal separator to be selected format.mConfidence = (int) (format.Confidence*0.4); break; case '@': // Avoid the mails separator to be selected case '&': // Avoid this is near a letter and URLS case '=': // Avoid because URLS contains it case ':': // Avoid because URLS contains it format.mConfidence = (int) (format.Confidence*0.6); break; case '-': // Avoid this other date separator format.mConfidence = (int) (format.Confidence*0.7); break; case ',': // Help the , ; tab | to be confident case ';': case '\t': case '|': format.mConfidence = (int) Math.Min(100, format.Confidence*1.15); break; } } #endregion #region " Helper & Utility Methods " private string[][] GetSampleLines(IEnumerable<string> files, int nroOfLines) { var res = new List<string[]>(); foreach (var file in files) res.Add(RawReadFirstLinesArray(file, nroOfLines, mEncoding)); return res.ToArray(); } private static string[][] GetSampleLines(IEnumerable<TextReader> files, int nroOfLines) { var res = new List<string[]>(); foreach (var file in files) res.Add(RawReadFirstLinesArray(file, nroOfLines)); return res.ToArray(); } private static int NumberOfLines(string[][] data) { int lines = 0; foreach (var fileData in data) lines += fileData.Length; return lines; } /// <summary> /// Shortcut method to read the first n lines of a text file as array. /// </summary> /// <param name="file">The file name</param> /// <param name="lines">The number of lines to read.</param> /// <param name="encoding">The Encoding used to read the file</param> /// <returns>The first n lines of the file.</returns> private static string[] RawReadFirstLinesArray(string file, int lines, Encoding encoding) { var res = new List<string>(lines); using (var reader = new StreamReader(file, encoding)) { for (int i = 0; i < lines; i++) { string line = reader.ReadLine(); if (line == null) break; else res.Add(line); } } return res.ToArray(); } /// <summary> /// Shortcut method to read the first n lines of a text file as array. /// </summary> /// <param name="stream">The text reader name</param> /// <param name="lines">The number of lines to read.</param> /// <returns>The first n lines of the file.</returns> private static string[] RawReadFirstLinesArray(TextReader stream, int lines) { var res = new List<string>(lines); for (int i = 0; i < lines; i++) { string line = stream.ReadLine(); if (line == null) break; else res.Add(line); } return res.ToArray(); } /// <summary> /// Calculate statistics based on sample data for the delimitter supplied /// </summary> /// <param name="data"></param> /// <param name="delimiter"></param> /// <returns></returns> private DelimiterInfo GetDelimiterInfo(string[][] data, char delimiter) { var indicators = Indicators.CalculateByDelimiter (delimiter, data, QuotedChar); return new DelimiterInfo (delimiter, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation); } private List<DelimiterInfo> GetDelimiters(string[][] data) { var frequency = new Dictionary<char, int>(); int lines = 0; for (int i = 0; i < data.Length; i++) { for (int j = 0; j < data[i].Length; j++) { // Ignore Header Line (if any) if (j == 0) continue; // ignore empty lines string line = data[i][j]; if (string.IsNullOrEmpty (line)) continue; // analyse line lines++; for (int ci = 0; ci < line.Length; ci++) { char c = line[ci]; if (char.IsLetterOrDigit(c) || c == ' ') continue; int count; if (frequency.TryGetValue(c, out count)) { count++; frequency[c] = count; } else frequency.Add(c, 1); } } } var candidates = new List<DelimiterInfo>(); // sanity check if (lines == 0) return candidates; // remove delimiters with low occurrence count var delimiters = new List<char> (frequency.Count); foreach (var pair in frequency) { if (pair.Value >= lines) delimiters.Add (pair.Key); } // calculate foreach (var key in delimiters) { var indicators = Indicators.CalculateByDelimiter (key, data, QuotedChar); // Adjust based on the number of lines if (lines < MinSampleData) indicators.Deviation = indicators.Deviation * Math.Min (1, ((double)lines) / MinSampleData); if (indicators.Avg > 1 && indicators.Deviation < MinDelimitedDeviation) candidates.Add (new DelimiterInfo (key, indicators.Avg, indicators.Max, indicators.Min, indicators.Deviation)); } return candidates; } #endregion /// <summary> /// Gets or sets the quoted char. /// </summary> /// <value>The quoted char.</value> private char QuotedChar { get; set; } #region " Statistics Functions " /// <summary> /// Collection of statistics about fields found /// </summary> private class Indicators { /// <summary> /// Maximum number of fields found /// </summary> public int Max = int.MinValue; /// <summary> /// Mimumim number of fields found /// </summary> public int Min = int.MaxValue; /// <summary> /// Average number of delimiters foudn per line /// </summary> public double Avg = 0; /// <summary> /// Calculated deviation /// </summary> public double Deviation = 0; /// <summary> /// Total analysed lines /// </summary> public int Lines = 0; private static double CalculateDeviation (IList<int> values, double avg) { double sum = 0; for (int i = 0; i < values.Count; i++) { sum += Math.Pow (values[i] - avg, 2); } return Math.Sqrt (sum / values.Count); } private static int CountNumberOfDelimiters (string line, char delimiter) { int count = 0; char c; for (int i = 0; i < line.Length; i++) { c = line[i]; if (c == ' ' || char.IsLetterOrDigit (c)) continue; count++; } return count; } public static Indicators CalculateByDelimiter (char delimiter, string[][] data, char? quotedChar) { var res = new Indicators (); int totalDelimiters = 0; int lines = 0; List<int> delimiterPerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; var delimiterInLine = 0; if (quotedChar.HasValue) delimiterInLine = QuoteHelper.CountNumberOfDelimiters (line, delimiter, quotedChar.Value); else delimiterInLine = CountNumberOfDelimiters (line, delimiter); // add count for deviation analysis delimiterPerLine.Add (delimiterInLine); if (delimiterInLine > res.Max) res.Max = delimiterInLine; if (delimiterInLine < res.Min) res.Min = delimiterInLine; totalDelimiters += delimiterInLine; } } res.Avg = totalDelimiters / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (delimiterPerLine, res.Avg); return res; } public static Indicators CalculateAsFixedSize (string[][] data) { var res = new Indicators (); double sum = 0; int lines = 0; List<int> sizePerLine = new List<int> (100); foreach (var fileData in data) { foreach (var line in fileData) { if (string.IsNullOrEmpty (line)) continue; lines++; sum += line.Length; sizePerLine.Add (line.Length); if (line.Length > res.Max) res.Max = line.Length; if (line.Length < res.Min) res.Min = line.Length; } } res.Avg = sum / (double)lines; // calculate deviation res.Deviation = CalculateDeviation (sizePerLine, res.Avg); return res; } } #endregion } } #endif
using Eflat.Util; using System; using System.Collections.Generic; namespace Eflat { /// <summary> /// The typer performs two main functions: /// 1. It performs type-checking and checks for non-parsing errors. /// 2. It infers unknown or incomplete types. /// </summary> public sealed class Typer { /// <summary> /// The typers reference to the syntax tree. We will modify this syntax tree /// in order to infer unknown types. /// </summary> private readonly SyntaxTree Ast; /// <summary> /// The list of errors found during the Typer stage. /// </summary> private readonly List<EFlatErrorException> Errors; /// <summary> /// The list of warnings found during the Typer stage. /// </summary> private readonly List<EFlatErrorException> Warnings; public Typer(SyntaxTree ast) { Ast = ast; Errors = new List<EFlatErrorException>(); Warnings = new List<EFlatErrorException>(); } /// <summary> /// Perform the typer operations as described in the documentation for the class. /// </summary> public void Typecheck() { CheckStructDeclarations(); CheckGlobalStatements(); CheckFunctionDeclarations(); } /// <summary> /// Check each function declaration. /// </summary> private void CheckFunctionDeclarations() { foreach (FuncDecl function in Ast.Functions) { CheckFuncDecl(function); } } /// <summary> /// Check this function declaration. /// </summary> /// <param name="function"></param> private void CheckFuncDecl(FuncDecl function) { Scope scope = function.Scope; foreach (Statement statement in scope.Statements) { CheckStatement(statement, scope); } } /// <summary> /// Check all the struct declarations. /// </summary> private void CheckStructDeclarations() { foreach (StructDecl decl in Ast.Structs) { CheckStructDeclaration(decl); } } private void CheckStructDeclaration(StructDecl decl) { foreach (Statement field in decl.Scope.Statements) { CheckStructField(decl, field); } } private void CheckStructField(StructDecl decl, Statement _field) { if (!(_field is DefineStatement)) { Error(_field, "Only Define Statements are supported as struct members."); return; } DefineStatement field = _field as DefineStatement; if (field.Define.Type is Types.Unknown) { throw new InternalCompilerError("We should not be able to not know this type in this circumstance."); } if (field.Define.Type is Types.Struct s) { // If we don't know the struct declaration, try and find it. if (s.Decl.IsNone) { Option<Types.StructDecl> origStruct = TryFindStructDecl(s.Name, decl.Scope); if (origStruct.IsNone) { return; } s.Decl = origStruct; } // By the time we get here, we should know this struct. Types.StructDecl fieldDecl = s.Decl.Value; // TODO(zac, 23/08/2017): We don't let a type directly include itself in itself (we need a determined size for every data structure). Warn(decl, "We currently don't check to see if the struct contains itself (directly or indirectly)."); } } /// <summary> /// Try to find a struct declaration, giving an error if we can't find one. /// </summary> private Option<Types.StructDecl> TryFindStructDecl(Token identifier, Scope scope) { // Check it exists: Option<DefineNode> possibleNode = scope.FindDefineNode(identifier.String); if (possibleNode.IsSome) { DefineNode node = possibleNode.Value; // Check it is a struct: if (node.Type is Types.StructDecl decl) { return Option<Types.StructDecl>.Some(decl); } else { Error(identifier, $"'{identifier.String}' is not a Struct Definition."); } } else { Error(identifier, $"Unable to find Struct '{identifier.String}' in current scope."); } return Option<Types.StructDecl>.None; } /// <summary> /// Check all the global statement at the global level, leaving checking the details of function and struct declarations to other steps. /// </summary> private void CheckGlobalStatements() { foreach (Statement statement in Ast.Global.Statements) { /// Check to see if this statement is allowed at global scope. if (statement.AllowedAtGlobal) { CheckStatement(statement, Ast.Global); } else { Error(statement, "This statement not allowed at the global scope."); } } } /// <summary> /// Perform typer checks on the specified statement. /// </summary> private void CheckStatement(Statement statement, Scope scope) { switch (statement) { case DefineStatement defStmt: CheckDefineStatement(defStmt, scope); break; case AssignmentStatement assignStmt: CheckAssignmentStatement(assignStmt, scope); break; case WhileStatement whileStmt: CheckWhileStatement(whileStmt, scope); break; case StatementList list: CheckStmtList(list); break; case IfStatement ifStmt: CheckIfStatement(ifStmt, scope); break; default: throw new InternalCompilerError($"Statement checking not implemented: '{statement}'."); } } private void CheckIfStatement(IfStatement ifStmt, Scope scope) { /// Check the condition. if (!CheckExpression(ifStmt.Condition, scope)) { return; } ExpectType(ifStmt.Condition, new Types.Boolean()); Scope innerScope = ifStmt.IfTrue.Scope; Statement innerStmt = ifStmt.IfTrue.Statement; CheckStatement(innerStmt, innerScope); ifStmt.IfFalse.IfSome((ifFalse) => { innerScope = ifFalse.Scope; innerStmt = ifFalse.Statement; CheckStatement(innerStmt, innerScope); }); } /// <summary> /// Check a statement list. /// </summary> private void CheckStmtList(StatementList list) { Scope scope = list.Scope; foreach (Statement stmt in scope.Statements) { CheckStatement(stmt, scope); } } /// <summary> /// Checks a While statement. /// </summary> private void CheckWhileStatement(WhileStatement whileStmt, Scope scope) { /// Check the condition. if (!CheckExpression(whileStmt.Condition, scope)) { return; } ExpectType(whileStmt.Condition, new Types.Boolean()); Scope innerScope = whileStmt.WhileTrue.Scope; Statement innerStmt = whileStmt.WhileTrue.Statement; CheckStatement(innerStmt, innerScope); } /// <summary> /// Checks that the type of the expression is of the expected type, adding an error if not. /// </summary> private void ExpectType(Expression expr, Type expected) { Type got = expr.Type; if (!expected.IsSameAs(got)) { Error(expr, $"Expected expression of type '{expected}', but got an expression of type '{got}'."); } } /// <summary> /// Checks an assignment statement. /// </summary> private void CheckAssignmentStatement(AssignmentStatement assignStmt, Scope scope) { // Check Def for the statement exists. Option<DefineNode> possibleDef = scope.FindDefineNode(assignStmt.Identifier.String); if (possibleDef.IsNone) { IdentifierNotDefined(assignStmt.Identifier); return; } DefineNode def = possibleDef.Value; // Check that we have already parsed a define statement for this def. if (!def.TyperFlags.HasFlag(TyperFlags.Declared)) { Error(assignStmt, $"Attempted to assign to binding '{assignStmt.Identifier.String}' before it was declared."); return; } // Check if the expression type is the same as the binding type. if (!CheckExpression(assignStmt.Value, scope)) { return; } Type exprType = assignStmt.Value.Type; Type defType = def.Type; if (!defType.IsSameAs(exprType)) { bool ok = TryMorphExprTypeIntoDefType(exprType, defType); if (!ok) { AssignedWrongType(assignStmt, exprType, defType); } } // Check if def is constant. if (def.Mutability == Mutability.Constant) { AssignmentToConstantAttempted(assignStmt); } } /// <summary> /// Attempts to morph the expression type into the defType. Returns false if not possible. /// Currently /// </summary> /// <param name="exprType"></param> /// <param name="defType"></param> /// <returns></returns> private bool TryMorphExprTypeIntoDefType(Type exprType, Type defType) { bool isSuccess = false; if (exprType is Types.Float exprf && defType is Types.Float deff && exprf.Size == Types.Float.FloatSize.UnspecifiedSize) { exprf.Size = deff.Size; isSuccess = true; } else if (exprType is Types.Integer expri && defType is Types.Integer defi && expri.Size == Types.Integer.IntegerSize.UnspecifiedSize) { expri.Size = defi.Size; isSuccess = true; } return isSuccess; } private void AssignedWrongType(AssignmentStatement assignStmt, Type exprType, Type defType) { Error(assignStmt, $"Assigned a value of type '{exprType}' to a binding of type '{defType}'."); } /// <summary> /// Add an error that describes when an assignment was attempted to a constant binding. /// </summary> /// <param name="assignStmt">The offending assignment statement.</param> private void AssignmentToConstantAttempted(AssignmentStatement assignStmt) { Error(assignStmt, $"Attempted to assign a value to constant binding '{assignStmt.Identifier.String}'."); } /// <summary> /// Ensure everything within a DefineStatement is properly typechecked, and type-inferred. /// </summary> /// <param name="defstmt">The statement that makes a definition.</param> /// <param name="scope"></param> private void CheckDefineStatement(DefineStatement defstmt, Scope scope) { // Check to see that we're the only def with this identifier in scope. if (!OneInScope(defstmt.Define.Identifier, scope)) return; if (defstmt.InitialValue.IsNone) { Warn(defstmt, "We don't actually check defines with no initial expression."); } else { Expression expr = defstmt.InitialValue.Value; CheckExpression(expr, scope); // If the defnode doesn't know it's type yet, if (defstmt.Define.Type is Types.Unknown) { // The defnode's type must be equal to the type of the expression // assigned to it. defstmt.Define.Type = expr.Type; } else { Type bindingType = defstmt.Define.Type; Type exprType = expr.Type; // Check to see if the expression is of the expected type for this defnode. if (!bindingType.IsSameAs(exprType)) { bool ok = TryMorphOneIntoOther(bindingType, exprType); if (!ok) { Error(defstmt, $"Binding type and expression type do not match. (Binding is type {bindingType}, but expression is type {exprType}."); } } } } // Inform the defnode that we have parsed a declaration. defstmt.Define.TyperFlags |= TyperFlags.Declared; } /// <summary> /// Adds an "identifier not defined" error. /// </summary> /// <param name="identifier"></param> private void IdentifierNotDefined(Token identifier) { Error(identifier, $"Identifier '{identifier.String}' not defined in current scope."); } /// <summary> /// Attempts to morph one type into the other. /// Assumes that one type is of Unspecified size. /// </summary> private bool TryMorphOneIntoOther(Type a, Type b) { // TODO(zac, 19/07/2017): This method needs a cleanup. if (a is Types.Float af && b is Types.Float bf) { if (af.Size == Types.Float.FloatSize.UnspecifiedSize) { af.Size = bf.Size; } else if (bf.Size == Types.Float.FloatSize.UnspecifiedSize) { bf.Size = af.Size; } else { return false; } } else if (a is Types.Integer ai && b is Types.Integer bi) { if (ai.Size == Types.Integer.IntegerSize.UnspecifiedSize) { ai.Size = bi.Size; } else if (bi.Size == Types.Integer.IntegerSize.UnspecifiedSize) { bi.Size = ai.Size; } else { return false; } } else { return false; } return true; } /// <summary> /// Expect to find only one version of this identifier in scope, adding an error and returning false if that is /// not the case. /// </summary> private bool OneInScope(Token identifier, Scope scope) { List<DefineNode> definesInScope = scope.FindAllDefineNodes(identifier.String); if (definesInScope.Count > 1) { // TODO(zac, 23/08/2017): This doesn't work correctly. Sometimes it selects a different binding. DefineNode origDef = definesInScope[definesInScope.Count - 1]; if (origDef.Location != identifier.Location) { Error(identifier, $"Redefinition of binding: '{identifier.String}'. Initial definition at {origDef.Location}."); return false; } } else if (definesInScope.Count == 0) throw new InternalCompilerError("Expected to find a binding in scope, and failed to find one."); return true; } /// <summary> /// Perform type-checking on an expression, returning false if the checking fails. /// </summary> private bool CheckExpression(Expression expr, Scope scope) { switch (expr) { case FuncDecl fn: // NOTE(zac, 19/07/2017): We should know the type of the expression by now. expr.Type = fn.Type; return true; case BindingExpression binding: return CheckBindingExpression(binding, scope); case FloatLiteral _: case BooleanLiteral _: case IntegerLiteral _: // We can ignore these ones, their types are trivial. return true; case StructDecl _: if (!scope.IsGlobal) { Error(expr, "Struct declarations are not supported in non-global scope at the moment."); return false; } // We can skip struct decls, as we check them earlier. return true; default: Warn(expr, $"We don't actually check the expression '{expr}' yet."); return true; } } private bool CheckBindingExpression(BindingExpression binding, Scope scope) { // If we haven't got the defnode, Try to find it again in global scope, // (as we should have found it otherwise). if (binding.DefineNode.IsNone) { Ast.Global.FindDefineNode(binding.Token.String) .IfSome((node) => { binding.SetDefineNode(node); }); } // If we still haven't found it, if (binding.DefineNode.IsNone) { IdentifierNotDefined(binding.Token); return false; } // NOTE(zac, 19/07/2017): I was going to check the Typer flags for TyperFlags.Declared, but because of the way we currently // reference binding.DefineNode, the situation where a binding is referred to before it is declared will be picked up by the above // error check. This behavior was deemed acceptable at the time. DefineNode def = binding.DefineNode.Value; // If we've found the node, we can find the type of this expression. binding.Type = def.Type; return true; } /// <summary> /// Add an error to the list of errors. /// </summary> /// <param name="node"></param> /// <param name="message"></param> private void Error(IHasLocation node, string message) => Errors.Add(new EFlatErrorException(node, message)); /// <summary> /// Add a warning to the list of warnings. /// </summary> /// <param name="node"></param> /// <param name="message"></param> private void Warn(IHasLocation node, string message) => Warnings.Add(new EFlatErrorException(node, message)); /// <summary> /// Whether the typer has errors. /// </summary> public bool HasErrors => Errors.Count != 0; public void PrintErrors() { foreach (EFlatErrorException e in Errors) { Console.WriteLine($"Error: {e}"); } } public void PrintWarnings() { foreach (EFlatErrorException e in Warnings) { Console.WriteLine($"Warning: {e}"); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Common { using System; public static class Logger { public static bool HasError { get; private set; } private static readonly object _sync = new object(); private static CompositeLogListener _syncListener = new CompositeLogListener(); private static AsyncLogListener _asyncListener = new AsyncLogListener(); public volatile static LogLevel LogLevelThreshold = LogLevel.Info; public static void RegisterListener(ILoggerListener listener) { if (listener == null) { throw new ArgumentNullException(nameof(listener)); } _syncListener.AddListener(listener); } public static ILoggerListener FindListener(Predicate<ILoggerListener> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } return _syncListener.FindListener(predicate); } public static void UnregisterListener(ILoggerListener listener) { if (listener == null) { throw new ArgumentNullException(nameof(listener)); } _syncListener.RemoveListener(listener); } public static void RegisterAsyncListener(ILoggerListener listener) { if (listener == null) { throw new ArgumentNullException(nameof(listener)); } _asyncListener.AddListener(listener); } public static ILoggerListener FindAsyncListener(Predicate<ILoggerListener> predicate) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } return _asyncListener.FindListener(predicate); } public static void UnregisterAsyncListener(ILoggerListener listener) { if (listener == null) { throw new ArgumentNullException(nameof(listener)); } _asyncListener.RemoveListener(listener); } public static void UnregisterAllListeners() { _syncListener.RemoveAllListeners(); _asyncListener.RemoveAllListeners(); } public static void Log(ILogItem item) { if (item.LogLevel < LogLevelThreshold) { return; } if (item.LogLevel == LogLevel.Error) { HasError = true; } _syncListener.WriteLine(item); _asyncListener.WriteLine(item); } [Obsolete] public static void Log(LogLevel level, string message, string phase, string file, string line) { Log(level, message, phase, file, line, null); } public static void Log(LogLevel level, string message, string phase = null, string file = null, string line = null, string code = null) { Log(new LogItem { #if NetCore File = file, #else File = file ?? LoggerFileScope.GetFileName(), #endif Line = line, LogLevel = level, Message = message, Code = code, #if NetCore Phase = phase, #else Phase = phase ?? LoggerPhaseScope.GetPhaseName(), #endif }); } [Obsolete] public static void LogDiagnostic(string message, string phase, string file, string line) { LogDiagnostic(message, phase, file, line, null); } public static void LogDiagnostic(string message, string phase = null, string file = null, string line = null, string code = null) { Log(LogLevel.Diagnostic, message, phase, file, line, code); } [Obsolete] public static void LogVerbose(string message, string phase, string file, string line) { LogVerbose(message, phase, file, line, null); } public static void LogVerbose(string message, string phase = null, string file = null, string line = null, string code = null) { Log(LogLevel.Verbose, message, phase, file, line, code); } [Obsolete] public static void LogInfo(string message, string phase, string file, string line) { LogInfo(message, phase, file, line, null); } public static void LogInfo(string message, string phase = null, string file = null, string line = null, string code = null) { Log(LogLevel.Info, message, phase, file, line, code); } [Obsolete] public static void LogWarning(string message, string phase, string file, string line) { LogWarning(message, phase, file, line, null); } public static void LogWarning(string message, string phase = null, string file = null, string line = null, string code = null) { Log(LogLevel.Warning, message, phase, file, line, code); } [Obsolete] public static void LogError(string message, string phase, string file, string line) { LogError(message, phase, file, line, null); } public static void LogError(string message, string phase = null, string file = null, string line = null, string code = null) { Log(LogLevel.Error, message, phase, file, line, code); } public static void Log(object result) { if (result == null) { throw new ArgumentNullException(nameof(result)); } Log(LogLevel.Info, result.ToString()); } public static void Flush() { _syncListener.Flush(); _asyncListener.Flush(); } #if !NetCore [Serializable] #endif private class LogItem : ILogItem { public string File { get; set; } public string Line { get; set; } public LogLevel LogLevel { get; set; } public string Message { get; set; } public string Phase { get; set; } public string Code { get; set; } public string CorrelationId { get; } public LogItem() { CorrelationId = AmbientContext.CurrentContext?.GenerateNextCorrelationId(); } } } }
// <copyright company="Simply Code Ltd."> // Copyright (c) Simply Code Ltd. All rights reserved. // Licensed under the MIT License. // See LICENSE file in the project root for full license information. // </copyright> namespace PackIt.DTO.DtoPlan { using System.Collections.Generic; using PackIt.Helpers.Enums; /// <summary> A dto stage. </summary> public class DtoStage { /// <summary> /// Initialises a new instance of the <see cref="DtoStage" /> class. /// </summary> public DtoStage() { this.Limits = new List<DtoLimit>(); } /// <summary> Gets or sets the identifier of the Plan that owns this item. </summary> /// /// <value> The identifier of the Plan. </value> public string PlanId { get; set; } /// <summary> Gets or sets the Stage level. </summary> /// /// <value> The Stage level. </value> public StageLevel StageLevel { get; set; } /// <summary> Gets or sets the collation. </summary> /// /// <value> The collation. </value> public long Collation { get; set; } /// <summary> Gets or sets the draw offset. </summary> /// /// <value> The draw offset. </value> public long DrawOffset { get; set; } /// <summary> Gets or sets the shape. </summary> /// /// <value> The shape. </value> public ShapeType Shape { get; set; } /// <summary> Gets or sets the form. </summary> /// /// <value> The form. </value> public FormType Form { get; set; } /// <summary> Gets or sets the shape parameter 0. </summary> /// /// <value> The shape parameter 0. </value> public double ShapeParameter0 { get; set; } /// <summary> Gets or sets the shape parameter 1. </summary> /// /// <value> The shape parameter 1. </value> public double ShapeParameter1 { get; set; } /// <summary> Gets or sets the shape parameter 2. </summary> /// /// <value> The shape parameter 2. </value> public double ShapeParameter2 { get; set; } /// <summary> Gets or sets the shape parameter 3. </summary> /// /// <value> The shape parameter 3. </value> public double ShapeParameter3 { get; set; } /// <summary> Gets or sets the shape parameter 4. </summary> /// /// <value> The shape parameter 4. </value> public double ShapeParameter4 { get; set; } /// <summary> Gets or sets the shape parameter 5. </summary> /// /// <value> The shape parameter 5. </value> public double ShapeParameter5 { get; set; } /// <summary> Gets or sets the shape parameter 6. </summary> /// /// <value> The shape parameter 6. </value> public double ShapeParameter6 { get; set; } /// <summary> Gets or sets the shape parameter 7. </summary> /// /// <value> The shape parameter 7. </value> public double ShapeParameter7 { get; set; } /// <summary> Gets or sets the form parameter 0. </summary> /// /// <value> The form parameter 0. </value> public double FormParameter0 { get; set; } /// <summary> Gets or sets the form parameter 1. </summary> /// /// <value> The form parameter 1. </value> public double FormParameter1 { get; set; } /// <summary> Gets or sets the form parameter 2. </summary> /// /// <value> The form parameter 2. </value> public double FormParameter2 { get; set; } /// <summary> Gets or sets the form parameter 3. </summary> /// /// <value> The form parameter 3. </value> public double FormParameter3 { get; set; } /// <summary> Gets or sets the form parameter 4. </summary> /// /// <value> The form parameter 4. </value> public double FormParameter4 { get; set; } /// <summary> Gets or sets the form parameter 5. </summary> /// /// <value> The form parameter 5. </value> public double FormParameter5 { get; set; } /// <summary> Gets or sets the form parameter 6. </summary> /// /// <value> The form parameter 6. </value> public double FormParameter6 { get; set; } /// <summary> Gets or sets the form parameter 7. </summary> /// /// <value> The form parameter 7. </value> public double FormParameter7 { get; set; } /// <summary> Gets or sets the density. </summary> /// /// <value> The density. </value> public double Density { get; set; } /// <summary> Gets or sets the generator. </summary> /// /// <value> The generator. </value> public long Generator { get; set; } /// <summary> Gets or sets the rotation. </summary> /// /// <value> The rotation. </value> public long Rotation { get; set; } /// <summary> Gets or sets a value indicating whether the materials should be computed. </summary> /// /// <value> True if compute materials, false if not. </value> public bool ComputeMaterials { get; set; } /// <summary> Gets or sets the sort. </summary> /// /// <value> The sort. </value> public long Sort { get; set; } /// <summary> Gets or sets the breathing space x coordinate. </summary> /// /// <value> The breathing space x coordinate. </value> public double BreathingSpaceX { get; set; } /// <summary> Gets or sets the breathing space y coordinate. </summary> /// /// <value> The breathing space y coordinate. </value> public double BreathingSpaceY { get; set; } /// <summary> Gets or sets the breathing space z coordinate. </summary> /// /// <value> The breathing space z coordinate. </value> public double BreathingSpaceZ { get; set; } /// <summary> Gets or sets the bulging x coordinate. </summary> /// /// <value> The bulging x coordinate. </value> public double BulgingX { get; set; } /// <summary> Gets or sets the bulging y coordinate. </summary> /// /// <value> The bulging y coordinate. </value> public double BulgingY { get; set; } /// <summary> Gets or sets the bulging z coordinate. </summary> /// /// <value> The bulging z coordinate. </value> public double BulgingZ { get; set; } /// <summary> Gets or sets the percent minimum. </summary> /// /// <value> The percent minimum. </value> public double PercentMin { get; set; } /// <summary> Gets or sets the percent maximum. </summary> /// /// <value> The percent maximum. </value> public double PercentMax { get; set; } /// <summary> Gets or sets the load minimum. </summary> /// /// <value> The load minimum. </value> public long LoadMin { get; set; } /// <summary> Gets or sets the load maximum. </summary> /// /// <value> The load maximum. </value> public long LoadMax { get; set; } /// <summary> Gets or sets the load step. </summary> /// /// <value> The load step. </value> public long LoadStep { get; set; } /// <summary> Gets or sets the tiers minimum. </summary> /// /// <value> The tiers minimum. </value> public long TiersMin { get; set; } /// <summary> Gets or sets the tiers maximum. </summary> /// /// <value> The tiers maximum. </value> public long TiersMax { get; set; } /// <summary> Gets or sets the tiers step. </summary> /// /// <value> The tiers step. </value> public long TiersStep { get; set; } /// <summary> Gets or sets the per tier minimum. </summary> /// /// <value> The per tier minimum. </value> public long PerTierMin { get; set; } /// <summary> Gets or sets the per tier maximum. </summary> /// /// <value> The per tier maximum. </value> public long PerTierMax { get; set; } /// <summary> Gets or sets the per tier step. </summary> /// /// <value> The per tier step. </value> public long PerTierStep { get; set; } /// <summary> Gets or sets the along side minimum. </summary> /// /// <value> The along side minimum. </value> public long AlongSideMin { get; set; } /// <summary> Gets or sets the along side maximum. </summary> /// /// <value> The along side maximum. </value> public long AlongSideMax { get; set; } /// <summary> Gets or sets the along side step. </summary> /// /// <value> The along side step. </value> public long AlongSideStep { get; set; } /// <summary> Gets or sets the product minimum. </summary> /// /// <value> The product minimum. </value> public long ProductMin { get; set; } /// <summary> Gets or sets the product maximum. </summary> /// /// <value> The product maximum. </value> public long ProductMax { get; set; } /// <summary> Gets or sets the product step. </summary> /// /// <value> The product step. </value> public long ProductStep { get; set; } /// <summary> Gets or sets the length of the external. </summary> /// /// <value> The length of the external. </value> public double ExternalLength { get; set; } /// <summary> Gets or sets the external length minimum. </summary> /// /// <value> The external length minimum. </value> public double ExternalLengthMin { get; set; } /// <summary> Gets or sets the external length maximum. </summary> /// /// <value> The external length maximum. </value> public double ExternalLengthMax { get; set; } /// <summary> Gets or sets the external length step. </summary> /// /// <value> The external length step. </value> public double ExternalLengthStep { get; set; } /// <summary> Gets or sets the external breadth. </summary> /// /// <value> The external breadth. </value> public double ExternalBreadth { get; set; } /// <summary> Gets or sets the external breadth minimum. </summary> /// /// <value> The external breadth minimum. </value> public double ExternalBreadthMin { get; set; } /// <summary> Gets or sets the external breadth maximum. </summary> /// /// <value> The external breadth maximum. </value> public double ExternalBreadthMax { get; set; } /// <summary> Gets or sets the external breadth step. </summary> /// /// <value> The external breadth step. </value> public double ExternalBreadthStep { get; set; } /// <summary> Gets or sets the height of the external. </summary> /// /// <value> The height of the external. </value> public double ExternalHeight { get; set; } /// <summary> Gets or sets the external height minimum. </summary> /// /// <value> The external height minimum. </value> public double ExternalHeightMin { get; set; } /// <summary> Gets or sets the external height maximum. </summary> /// /// <value> The external height maximum. </value> public double ExternalHeightMax { get; set; } /// <summary> Gets or sets the external height step. </summary> /// /// <value> The external height step. </value> public double ExternalHeightStep { get; set; } /// <summary> Gets or sets the external volume. </summary> /// /// <value> The external volume. </value> public double ExternalVolume { get; set; } /// <summary> Gets or sets the external volume minimum. </summary> /// /// <value> The external volume minimum. </value> public double ExternalVolumeMin { get; set; } /// <summary> Gets or sets the external volume maximum. </summary> /// /// <value> The external volume maximum. </value> public double ExternalVolumeMax { get; set; } /// <summary> Gets or sets the external volume step. </summary> /// /// <value> The external volume step. </value> public double ExternalVolumeStep { get; set; } /// <summary> Gets or sets the external length to breadth ratio. </summary> /// /// <value> The external length to breadth ratio. </value> public double ExternalLengthToBreadthRatio { get; set; } /// <summary> Gets or sets the external length to breadth ratio minimum. </summary> /// /// <value> The external length to breadth ratio minimum. </value> public double ExternalLengthToBreadthRatioMin { get; set; } /// <summary> Gets or sets the external length to breadth ratio maximum. </summary> /// /// <value> The external length to breadth ratio maximum. </value> public double ExternalLengthToBreadthRatioMax { get; set; } /// <summary> Gets or sets the external length to breadth ratio step. </summary> /// /// <value> The external length to breadth ratio step. </value> public double ExternalLengthToBreadthRatioStep { get; set; } /// <summary> Gets or sets the external length to height ratio. </summary> /// /// <value> The external length to height ratio. </value> public double ExternalLengthToHeightRatio { get; set; } /// <summary> Gets or sets the external length to height ratio minimum. </summary> /// /// <value> The external length to height ratio minimum. </value> public double ExternalLengthToHeightRatioMin { get; set; } /// <summary> Gets or sets the external length to height ratio maximum. </summary> /// /// <value> The external length to height ratio maximum. </value> public double ExternalLengthToHeightRatioMax { get; set; } /// <summary> Gets or sets the external length to height ratio step. </summary> /// /// <value> The external length to height ratio step. </value> public double ExternalLengthToHeightRatioStep { get; set; } /// <summary> Gets or sets the external angle. </summary> /// /// <value> The external angle. </value> public double ExternalAngle { get; set; } /// <summary> Gets or sets the external angle minimum. </summary> /// /// <value> The external angle minimum. </value> public double ExternalAngleMin { get; set; } /// <summary> Gets or sets the external angle maximum. </summary> /// /// <value> The external angle maximum. </value> public double ExternalAngleMax { get; set; } /// <summary> Gets or sets the external angle step. </summary> /// /// <value> The external angle step. </value> public double ExternalAngleStep { get; set; } /// <summary> Gets or sets the gross weight. </summary> /// /// <value> The gross weight. </value> public double GrossWeight { get; set; } /// <summary> Gets or sets the gross weight minimum. </summary> /// /// <value> The gross weight minimum. </value> public double GrossWeightMin { get; set; } /// <summary> Gets or sets the gross weight maximum. </summary> /// /// <value> The gross weight maximum. </value> public double GrossWeightMax { get; set; } /// <summary> Gets or sets the gross weight step. </summary> /// /// <value> The gross weight step. </value> public double GrossWeightStep { get; set; } /// <summary> Gets or sets the length of the internal. </summary> /// /// <value> The length of the internal. </value> public double InternalLength { get; set; } /// <summary> Gets or sets the internal length minimum. </summary> /// /// <value> The internal length minimum. </value> public double InternalLengthMin { get; set; } /// <summary> Gets or sets the internal length maximum. </summary> /// /// <value> The internal length maximum. </value> public double InternalLengthMax { get; set; } /// <summary> Gets or sets the internal length step. </summary> /// /// <value> The internal length step. </value> public double InternalLengthStep { get; set; } /// <summary> Gets or sets the internal breadth. </summary> /// /// <value> The internal breadth. </value> public double InternalBreadth { get; set; } /// <summary> Gets or sets the internal breadth minimum. </summary> /// /// <value> The internal breadth minimum. </value> public double InternalBreadthMin { get; set; } /// <summary> Gets or sets the internal breadth maximum. </summary> /// /// <value> The internal breadth maximum. </value> public double InternalBreadthMax { get; set; } /// <summary> Gets or sets the internal breadth step. </summary> /// /// <value> The internal breadth step. </value> public double InternalBreadthStep { get; set; } /// <summary> Gets or sets the height of the internal. </summary> /// /// <value> The height of the internal. </value> public double InternalHeight { get; set; } /// <summary> Gets or sets the internal height minimum. </summary> /// /// <value> The internal height minimum. </value> public double InternalHeightMin { get; set; } /// <summary> Gets or sets the internal height maximum. </summary> /// /// <value> The internal height maximum. </value> public double InternalHeightMax { get; set; } /// <summary> Gets or sets the internal height step. </summary> /// /// <value> The internal height step. </value> public double InternalHeightStep { get; set; } /// <summary> Gets or sets the internal volume. </summary> /// /// <value> The internal volume. </value> public double InternalVolume { get; set; } /// <summary> Gets or sets the internal volume minimum. </summary> /// /// <value> The internal volume minimum. </value> public double InternalVolumeMin { get; set; } /// <summary> Gets or sets the internal volume maximum. </summary> /// /// <value> The internal volume maximum. </value> public double InternalVolumeMax { get; set; } /// <summary> Gets or sets the internal volume step. </summary> /// /// <value> The internal volume step. </value> public double InternalVolumeStep { get; set; } /// <summary> Gets or sets the internal length to breadth ratio. </summary> /// /// <value> The internal length to breadth ratio. </value> public double InternalLengthToBreadthRatio { get; set; } /// <summary> Gets or sets the internal length to breadth ratio minimum. </summary> /// /// <value> The internal length to breadth ratio minimum. </value> public double InternalLengthToBreadthRatioMin { get; set; } /// <summary> Gets or sets the internal length to breadth ratio maximum. </summary> /// /// <value> The internal length to breadth ratio maximum. </value> public double InternalLengthToBreadthRatioMax { get; set; } /// <summary> Gets or sets the internal length to breadth ratio step. </summary> /// /// <value> The internal length to breadth ratio step. </value> public double InternalLengthToBreadthRatioStep { get; set; } /// <summary> Gets or sets the internal length to height ratio. </summary> /// /// <value> The internal length to height ratio. </value> public double InternalLengthToHeightRatio { get; set; } /// <summary> Gets or sets the internal length to height ratio minimum. </summary> /// /// <value> The internal length to height ratio minimum. </value> public double InternalLengthToHeightRatioMin { get; set; } /// <summary> Gets or sets the internal length to height ratio maximum. </summary> /// /// <value> The internal length to height ratio maximum. </value> public double InternalLengthToHeightRatioMax { get; set; } /// <summary> Gets or sets the internal length to height ratio step. </summary> /// /// <value> The internal length to height ratio step. </value> public double InternalLengthToHeightRatioStep { get; set; } /// <summary> Gets or sets the internal angle. </summary> /// /// <value> The internal angle. </value> public double InternalAngle { get; set; } /// <summary> Gets or sets the internal angle minimum. </summary> /// /// <value> The internal angle minimum. </value> public double InternalAngleMin { get; set; } /// <summary> Gets or sets the internal angle maximum. </summary> /// /// <value> The internal angle maximum. </value> public double InternalAngleMax { get; set; } /// <summary> Gets or sets the internal angle step. </summary> /// /// <value> The internal angle step. </value> public double InternalAngleStep { get; set; } /// <summary> Gets or sets the nett weight. </summary> /// /// <value> The nett weight. </value> public double NettWeight { get; set; } /// <summary> Gets or sets the nett weight minimum. </summary> /// /// <value> The nett weight minimum. </value> public double NettWeightMin { get; set; } /// <summary> Gets or sets the nett weight maximum. </summary> /// /// <value> The nett weight maximum. </value> public double NettWeightMax { get; set; } /// <summary> Gets or sets the nett weight step. </summary> /// /// <value> The nett weight step. </value> public double NettWeightStep { get; set; } /// <summary> Gets or sets the area utilisation minimum. </summary> /// /// <value> The area utilisation minimum. </value> public double AreaUtilisationMin { get; set; } /// <summary> Gets or sets the area utilisation maximum. </summary> /// /// <value> The area utilisation maximum. </value> public double AreaUtilisationMax { get; set; } /// <summary> Gets or sets the volume utilisation minimum. </summary> /// /// <value> The volume utilisation minimum. </value> public double VolumeUtilisationMin { get; set; } /// <summary> Gets or sets the volume utilisation maximum. </summary> /// /// <value> The volume utilisation maximum. </value> public double VolumeUtilisationMax { get; set; } /// <summary> Gets or sets the outer. </summary> /// /// <value> The outer. </value> public long Outer { get; set; } /// <summary> Gets or sets the draw detail. </summary> /// /// <value> The draw detail. </value> public Detail DrawDetail { get; set; } /// <summary> Gets or sets the length of the minimum block. </summary> /// /// <value> The length of the minimum block. </value> public long MinBlockLength { get; set; } /// <summary> Gets or sets the minimum block breadth. </summary> /// /// <value> The minimum block breadth. </value> public long MinBlockBreadth { get; set; } /// <summary> Gets or sets a value indicating whether the hands should be drawn. </summary> /// /// <value> True if draw hands, false if not. </value> public bool DrawHands { get; set; } /// <summary> Gets or sets the collection of limits. </summary> /// /// <value> Collection of limits. </value> public IList<DtoLimit> Limits { get; set; } } }
//------------------------------------------------------------------------------ // iniParser.cs // Originally written for T2BoL mod back in the day, now is being rewritten // for the original implementation was pretty crappy. // Requires: Array.cs // Copyright (c) 2012 Robert MacGregor //============================================================================== //------------------------------------------------------------------------------ // Name: INIParser.load // Argument %file: The file to parse and load into memory. // Description: This function is the main function of everything; it loads // %file into memory. // Return: True if the function succeeded, false if otherwise failed. //============================================================================== function INIParser::load(%this, %file) { // Make sure we have our values initialised (math doesn't work right on nonexistent variables!) if (%this.filesLoaded == "") %this.filesLoaded = 0; if (%this.blockEntryCount == "") %this.blockEntryCount = 0; if (%this.blockInstances == "") %this.blockInstances = 0; %currentSeconds = formatTimeString("ss"); // Check to see if the data is valid (returns false if we tried to load a nonexistent file) if (!isFile(%file)) { error("basicDataStorage.cs: Attempted to load non-existent file " @ %file @ "!"); return false; } // Check to see if this file is already loaded if (%this.isLoaded(%file)) { error("basicDataStorage.cs: Attempted to reload data file " @ %file SPC "while it's already in memory! (try unloading or emptying)"); return false; } // Add the file entry to memory (for the file check above) %this.files[%this.filesLoaded] = %file; %this.fileIndex[%file] = %this.filesLoaded; %this.filesLoaded++; // Load the file into memory (function is from fileProcessing.cs) %fileData = strReplace(stripChars(getFileBuffer(%file),"\t"),"\n","\t"); %lineCount = getFieldCount(%fileData); %isProcessingBlock = false; // Used to set processing mode %currentBlock = 0; %hadError = false; // Iterate through all lines for (%i = 0; %i < %lineCount; %i++) { %currentLine = getField(%fileData,%i); // Check to see if this line contains a block definition or not %openingBlock = strStr(%currentLine, "["); %closingBlock = strStr(%currentLine, "]"); // If we have a block definition, it should be against left margin if (%openingBlock == 0 && %closingBlock > 0 && !%isProcessingBlock) { %isProcessingBlock = true; %blockName = getSubStr(%currentLine,%openingBlock+1,%closingBlock-1); if (%this.blockInstances[%blockName] == "") { %this.blockInstances[%blockName] = 0; %this.blockEntry[%this.blockEntryCount] = %blockName; %this.blockEntryCount++; } // Create the array to store our block data %currentBlock = Array.create(); %currentBlock.Name = %blockName; %currentBlock.File = %file; %this.blocks[%blockName,%this.blockInstances] = %currentBlock; %this.blockInstances[%blockName]++; %this.blockInstances++; continue; } // Results in an error else if (%openingBlock == 0 && %closingBlock > 0 && %isProcessingBlock) { error("basicDataStorage.cs: Error loading file "@ %file @ ", block spacing error."); return false; } // If we're processing the actual block if (%isProcessingBlock) { if (%currentLine $="" || %i == %lineCount) { %isProcessingBlock = false; continue; } else { %eqPos = strStr(%currentLine,"="); // This is safe since the equals sign should be first. if (%eqPos == -1) { error("basicDataStorage.cs: Unable to read entry for block" SPC %currentBlock.Name @ " in file" SPC %file @ "!"); %isProcessingBlock = false; %hadError = true; continue; } // Note: I got lazy here, just don't have semicolons in your data entries.. %semiPos = strStr(%currentLine,";"); if (%semiPos == -1 || getSubStrOccurance(%currentLine,";") > 1) { error("basicDataStorage.cs: Unable to read entry for block" SPC %currentBlock.Name @ " in file" SPC %file @ "!"); %isProcessingBlock = false; %hadError = true; continue; } %entryName = trim(getSubStr(%currentLine,0,%eqPos-1)); %entryValue = trim(getSubStr(%currentLine,%eqPos+1, mAbs(%eqPos-%semiPos)-1 )); %currentBlock.setElement(%entryName,%entryValue); } } } if (!%hadError) warn("basicDataStorage.cs: Successfully loaded file" SPC %file SPC "in " @ formatTimeString("ss") - %currentSeconds SPC "seconds."); return !%hadError; } //------------------------------------------------------------------------------ // Name: INIParser.unload // Argument %file: The file of who's entries should be unloaded. // Description: This function is used to unload data by filename -- useful for // reloading data from specific files. // Return: True if the function was successful, false if otherwise failed. //============================================================================== function INIParser::unload(%this, %file) { if (!%this.isLoaded(%file)) { error("basicDataStorage.cs: Attempted to unload non-loaded data file " @ %file @ "!"); return false; } // Unload any data associated with this file now %removed = ""; for (%i = 0; %i < %this.blockEntryCount; %i++) { %name = %this.blockEntry[%i]; for (%h = 0; %h < %this.blockInstances[%name]; %h++) if (%this.blocks[%name, %h].File $= %file) { %this.blocks[%name, %h].delete(); %this.blocks[%name, %h] = ""; %this.blockEntry[%i] = ""; %removed = trim(%removed SPC %i); if (%this.blockInstances[%name] == 1) %this.blockInstances[%name] = ""; else %this.blockInstances[%name]--; } } // Iterate through our block entries and correct the imbalance for (%i = 0; %i < getWordCount(%removed); %i++) { for (%h = i; %h < %this.blockEntryCount; %h++) %this.blockEntry[%h-%i] = %this.blockEntry[%h+1]; %this.blockEntryCount--; } // Now remove the file entry for (%i = %this.fileIndex[%file]; %i < %this.filesLoaded; %i++) if (%i != %this.filesLoaded-1) { %this.files[%i] = %this.files[%i+1]; %this.fileIndex[%this.files[%i+1]] = %i; } else { %this.fileIndex[%file] = ""; %this.files[%i] = ""; } // Decrement the files loaded count and return true %this.filesLoaded--; return true; } //------------------------------------------------------------------------------ // Name: INIParser.count // Argument %block: The bloick entry to count the occurances of // Return: The occurances of %block in this parser object. If there is no // such entry of %block anywhere, false (0) is returned. //============================================================================== function INIParser::count(%this, %block) { // Return zero if the block has no entries even registered if (%this.blockInstances[%block] == "") return false; else // Return the block Instances otherwise return %this.blockInstances[%block]; return false; // Shouldn't happen } //------------------------------------------------------------------------------ // Name: INIParser.empty // Description: Empties the entire object of any information it may have // loaded anytime. // Return: True is always returned from this function. //============================================================================== function INIParser::empty(%this) { // Iterate through our block entries and destroy them for (%i = 0; %i < %this.blockEntryCount; %i++) { %name = %this.blockEntry[%i]; for (%h = 0; %h < %this.blockInstances[%name]; %h++) { %this.blocks[%name, %h].delete(); %this.blocks[%name, %h] = ""; } %this.blockInstances[%name] = ""; %this.blockEntry[%i] = ""; } // Remove the files loaded entries now for (%i = 0; %i < %this.filesLoaded; %i++) { %this.fileIndex[%this.files[%i]] = ""; %this.files[%i] = ""; } // Reset some variables to 0 and return true %this.filesLoaded = 0; %this.blockInstances = 0; %this.blockEntryCount = 0; return true; } //------------------------------------------------------------------------------ // Name: INIParser.isLoaded // Argument %file: The file to check the loaded status of. // Description: Returns if %file is loaded into memory of this object or not. // Return: A boolean representing the loaded status. //============================================================================== function INIParser::isLoaded(%this, %file) { // Check to see if this file is already loaded for (%i = 0; %i < %this.filesLoaded; %i++) if (%this.files[%i] $= %file) return true; return false; } //------------------------------------------------------------------------------ // Name: INIParser.get // Argument %block: The name of the block to return. // Argument %occurance: The block index we need to return -- if there's // multiple entries of %block. // Description: This function is used to retrieve block entries loaded from // within any of the files this object has parsed. // Return: An Array (array.cs) containing relevent information to the requested // block. If there is no such entry of %block, false is returned. //============================================================================== function INIParser::get(%this, %block, %occurance) { // Check ti see uf thus block has only once entry -- in which case %occurance is ignored if (%this.count(%block) == 1) return %this.blocks[%block, 0]; // Otherwise we use %occurance to return the specific index else if (%occurance >= 0 && %occurance <= %this.count(%block)) return %this.blocks[%block, %occurance]; return false; }
#region license // Copyright (C) 2017 Mikael Egevig ([email protected]). All Rights Reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following // conditions are met: // // * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. // * 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 Mikael Egevig 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. #endregion /** \file * Walker that computes the FOLLOW set of all relevant nodes. */ using System.Collections.Generic; using Org.Oakie.Gardener.Diction; namespace Org.Oakie.Gardener.Walkers { /** \note This pass has been programatically disabled until such a time that the enabled passes actually work. */ #if WORKING /** * Computes and assigns the \c .Follow property of all relevant nodes in the tree. * * \note Due to my laziness, this pass only supports Standard grammars. */ public class ComputeFollowWalker: Walker { public string Name { get { return "ComputeFollowWalker"; } } public string Description { get { return "Computes the FOLLOW set for all relevant nodes."; } } public object Visit(AlternationNode that) { throw new System.Exception("This tree walker only supports standard grammars"); } public object Visit(ClosureNode that) { throw new System.Exception("This tree walker only supports standard grammars"); } public object Visit(EndOfFileNode that) { if (that.First != null) return; that.First = CreateFirstSet(that); // Always identical to itself that.First.Set(that.Ordinal); return null; } public object Visit(GrammarNode that) { // I'm currently too lazy to try to make this work for extended grammars (and there's no need for it anyway) System.Diagnostics.Debug.Assert(that.GrammarKind == GrammarKind.Standard); if (that.First != null) return; that.First = CreateFirstSet(that); // Visit children. foreach (Node below in that.Below) below.Visit(this); // FIRST(grammar) = FIRST(grammar.Start) that.First.Set(that.GetNonterminal(that.Start).First); return that; } public object Visit(LambdaNode that) { throw new System.Exception("ComputeFollowWalker requires lambda to have been eliminated"); } public object Visit(NonterminalNode that) { if (that.First != null) return; that.First = CreateFirstSet(that); foreach (Node below in that.Below) below.Visit(this); foreach (Node below in that.Below) { that.First.Ior(below.First); } return null; } public object Visit(OptionNode that) { throw new System.Exception("This tree walker only supports standard grammars"); } public object Visit(ProductionNode that) { if (that.First != null) return; that.First = CreateFirstSet(that); if (that.Below.Length == 0) { that.First.Set(0); // 0 = lambda return; } foreach (Node below in that.Below) below.Visit(this); foreach (Node below in that.Below) { that.First.Ior(below.First); if (!below.Nullable) break; } return null; } public object Visit(ReferenceNode that) { System.Diagnostics.Debug.Assert(that.Below.Length == 0); if (that.First != null) return; that.First = CreateFirstSet(that); NonterminalNode nonterminal = that.Grammar.GetNonterminal(that.Name); nonterminal.Visit(this); that.First.Set(nonterminal.First); return null; } public object Visit(RepetitionNode that) { throw new System.Exception("This tree walker only supports standard grammars"); } public object Visit(SequenceNode that) { if (that.First != null) return; that.First = CreateFirstSet(that); // If the left-hand-side is the lambda/epsilon symbol, return the empty set. if (that.Below.Length == 0) return; // visit each child node foreach (Node below in that.Below) below.Visit(this); foreach (Node below in that.Below) { that.First.Ior(below.First); if (!below.Nullable) break; } return null; } public object Visit(TerminalNode that) { if (that.First != null) return; that.First = CreateFirstSet(that); // Always identical to itself that.First.Set(that.Ordinal); return null; } } #endif }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using MindTouch.Dream; using MindTouch.Dream.Test; using MindTouch.Tasking; using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Deki.Tests { public static class Utils { public static string ToErrorString(this DreamMessage response) { if(response == null || response.IsSuccessful) { return null; } var responseText = response.HasDocument ? response.ToDocument().ToPrettyString() : response.ToString(); return string.Format("Status: {0}\r\nMessage:\r\n{1}", response.Status, responseText); } public class TestSettings { public static readonly TestSettings Instance = new TestSettings(); private readonly object padlock = new object(); private XDoc _dekiConfig; private DreamHostInfo _hostInfo; private readonly XDoc _xdoc = null; public readonly XUri LuceneMockUri = new XUri("mock://mock/testlucene"); private TestSettings() { MockPlug.DeregisterAll(); string configfile = "mindtouch.deki.tests.xml"; if(System.IO.File.Exists(configfile)) { _xdoc = XDocFactory.LoadFrom(configfile, MimeType.XML); } else { _xdoc = new XDoc("config"); } } public Plug Server { get { return HostInfo.LocalHost.At("deki"); } } public DreamHostInfo HostInfo { get { if(_hostInfo == null) { lock(padlock) { if(_hostInfo == null) { _hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("apikey", Settings.ApiKey).Elem("storage-dir", Settings.StorageDir)); _hostInfo.Host.Self.At("load").With("name", "mindtouch.deki").Post(DreamMessage.Ok()); _hostInfo.Host.Self.At("load").With("name", "mindtouch.deki.services").Post(DreamMessage.Ok()); _hostInfo.Host.Self.At("load").With("name", "mindtouch.indexservice").Post(DreamMessage.Ok()); DreamServiceInfo deki = DreamTestHelper.CreateService(_hostInfo, DekiConfig); } } } return _hostInfo; } } public void ShutdownHost() { lock(padlock) { if(_hostInfo != null) { _hostInfo.Dispose(); _hostInfo = null; } } } public string ApiKey { get { return GetString("/config/apikey", "123"); } } public string ProductKey { get { return GetString("/config/productkey", "badkey"); } } public string AssetsPath { get { return GetString("/config/assets-path", @"C:\mindtouch\assets"); } } public string DekiPath { get { return GetString("/config/deki-path", @"C:\mindtouch\public\dekiwiki\trunk\web"); } } public string DekiResourcesPath { get { return GetString("/config/deki-resources-path", @"C:\mindtouch\public\dekiwiki\trunk\web\resources"); } } public string ImageMagickConvertPath { get { return GetString("/config/imagemagick-convert-path", @"C:\mindtouch\public\dekiwiki\trunk\src\tools\mindtouch.dekihost.setup\convert.exe"); } } public string ImageMagickIdentifyPath { get { return GetString("/config/imagemagick-identify-path", @"C:\mindtouch\public\dekiwiki\trunk\src\tools\mindtouch.dekihost.setup\identify.exe"); } } public string PrinceXmlPath { get { return GetString("/config/princexml-path", @"C:\Program Files\Prince\Engine\bin\prince.exe"); } } public string HostAddress { get { return GetString("/config/host-address", "testdb.mindtouch.com"); } } public string DbServer { get { return GetString("/config/db-server", "testdb.mindtouch.com"); } } public string DbCatalog { get { return GetString("/config/db-catalog", "wikidb"); } } public string DbUser { get { return GetString("/config/db-user", "wikiuser"); } } public string DbPassword { get { return GetString("/config/db-password", "password"); } } public string UserName { get { return GetString("/config/UserName", "Admin"); } } public string Password { get { return GetString("/config/Password", "password"); } } public string StorageDir { get { return GetString("/config/storage-dir", null); } } public int CountOfRepeats { get { return GetInt("/config/CountOfRepeats", 5); } } public int SizeOfBigContent { get { return GetInt("/config/SizeOfBigContent", 4096); } } public int SizeOfSmallContent { get { return GetInt("/config/SizeOfSmallContent", 256); } } public XDoc DekiConfig { get { if(_dekiConfig == null) { lock(padlock) { _dekiConfig = new XDoc("config") .Elem("apikey", ApiKey) .Elem("path", "deki") .Elem("sid", "http://services.mindtouch.com/deki/draft/2006/11/dekiwiki") .Elem("deki-path", DekiPath) .Elem("deki-resources-path", DekiResourcesPath) .Elem("imagemagick-convert-path", ImageMagickConvertPath) .Elem("imagemagick-identify-path", ImageMagickIdentifyPath) .Elem("princexml-path", PrinceXmlPath) .Start("page-subscription") .Elem("accumulation-time", "0") .End() .Start("packageupdater") .Attr("uri", "mock://mock/packageupdater") .End() .Start("wikis") .Start("config") .Attr("id", "default") .Elem("host", "*") .Start("page-subscription") .Elem("from-address", "[email protected]") .End() .Elem("db-server", DbServer) .Elem("db-port", "3306") .Elem("db-catalog", DbCatalog) .Elem("db-user", DbUser) .Start("db-password").Attr("hidden", "true").Value(DbPassword).End() .Elem("db-options", "pooling=true; Connection Timeout=5; Protocol=socket; Min Pool Size=2; Max Pool Size=50; Connection Reset=false;character set=utf8;ProcedureCacheSize=25;Use Procedure Bodies=true;") .End() .End() .Start("indexer").Attr("src", LuceneMockUri).End(); } } return _dekiConfig; } } private int GetInt(string path, int defaultValue) { return _xdoc[path].AsInt != null ? _xdoc[path].AsInt.Value : defaultValue; } private string GetString(string path, string defaultValue) { return _xdoc[path].AsText ?? defaultValue; } } public static readonly TestSettings Settings = TestSettings.Instance; public static Plug BuildPlugForAnonymous() { return BuildPlugForUser(null, null); } public static Plug BuildPlugForAdmin() { return BuildPlugForUser(Settings.UserName, Settings.Password); } public static Plug BuildPlugForUser(string username) { return BuildPlugForUser(username, UserUtils.DefaultUserPsw); } public static Plug BuildPlugForUser(string username, string password) { Plug.GlobalCookies.Clear(); Plug p = Settings.Server; if(!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { DreamMessage msg = p.WithCredentials(username, password).At("users", "authenticate").PostAsync().Wait(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Failed to authenticate."); } return p; } public static string GenerateUniqueName() { return Guid.NewGuid().ToString().Replace("-", string.Empty); } public static string GenerateUniqueName(string prefix) { return prefix + GenerateUniqueName(); } public static bool ByteArraysAreEqual(byte[] one, byte[] two) { if(one == null || two == null) throw new ArgumentException(); if(one.Length != two.Length) return false; for(int i = 0; i < one.Length; i++) if(one[i] != two[i]) return false; return true; } private static char[] _alphabet = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', (char)224, (char)225, (char)226, (char)227, (char)228, (char)229, (char)230, (char)231, (char)232, (char)233, (char)234, (char)235, (char)236, (char)237, (char)238, (char)239, (char)240, (char)241, (char)242 }; public static string GetRandomTextByAlphabet(int countOfSymbols) { System.Text.StringBuilder builder = new StringBuilder(countOfSymbols); Random rnd = new Random(); for(int i = 0; i < countOfSymbols; i++) builder.Append(_alphabet[rnd.Next(_alphabet.Length - 1)]); return builder.ToString(); } public static string GetRandomText(int countOfSymbols) { System.Text.StringBuilder builder = new StringBuilder(countOfSymbols); Random rnd = new Random(); for(int i = 0; i < countOfSymbols; i++) { try { int symbolAsInt = rnd.Next(0x10ffff); while(0xD800 <= symbolAsInt && symbolAsInt <= 0xDFFF) symbolAsInt = rnd.Next(0x10ffff); char symbol = char.ConvertFromUtf32(symbolAsInt)[0]; if(char.IsDigit(symbol) || char.IsLetter(symbol) || char.IsPunctuation(symbol)) builder.Append(symbol); else i--; } catch(System.ArgumentOutOfRangeException) { i--; } } return builder.ToString(); } public static string GetBigRandomText() { return GetRandomTextByAlphabet(Utils.Settings.SizeOfBigContent); } public static string GetSmallRandomText() { return GetRandomTextByAlphabet(Utils.Settings.SizeOfSmallContent); } public static string DateToString(DateTime time) { return time == DateTime.MinValue ? null : time.ToUniversalTime().ToString("yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat); } public static Dictionary<string, string> GetDictionaryFromDoc(XDoc doc, string element, string key, string value) { Dictionary<string, string> result = new Dictionary<string, string>(); foreach(XDoc node in doc[element]) result[node[key].AsText] = node[value].AsText; return result; } public static void TestSortingOfDocByField(XDoc doc, string resourceName, string element, bool ascorder) { TestSortingOfDocByField(doc, resourceName, element, ascorder, null); } public static void TestSortingOfDocByField(XDoc doc, string resourceName, string element, bool ascorder, Dictionary<string, string> dictData) { string previousValue = string.Empty; foreach(XDoc node in doc[resourceName]) { string currentValue = dictData == null ? node[element].AsText : dictData[node[element].AsText]; if(!string.IsNullOrEmpty(previousValue) && !string.IsNullOrEmpty(currentValue)) { int x = StringUtil.CompareInvariantIgnoreCase(previousValue, currentValue) * (ascorder ? 1 : -1); Assert.IsTrue(x <= 0, string.Format("Sort assertion failed for '{0}': '{1}' and '{2}'", element, previousValue, currentValue)); } previousValue = currentValue; currentValue = string.Empty; } } public static void PingServer() { var host = Settings.HostInfo; } } // Note (arnec): this has to exist for nunit-console to pick up the log4net configuration [SetUpFixture] public class LogSetup { [SetUp] public void Setup() { log4net.Config.XmlConfigurator.Configure(); } } }
using System; using System.Collections.Generic; using System.Windows.Forms; using System.IO; using Microsoft.Win32; using ModelTools.ModelData.JMS; using ModelTools.ModelData.VWI; using Win32; namespace ModelTools.Interface { public partial class MainForm : Form { public MainForm() { InitializeComponent(); Output.NewMessage += new Output.OutputEventHandler(Output_NewMessage); } private string m_CommonFilePath; private void Output_NewMessage(string output) { OutputGroup_txtOutput.Text += output; // + OutputGroup_txtOutput.Text; OutputGroup_txtOutput.Select(OutputGroup_txtOutput.Text.Length, 0); //OutputGroup_txtOutput.Focus(); OutputGroup_txtOutput.ScrollToCaret(); } private void MainForm_Load(object sender, EventArgs e) { //Output.WriteLine("Checking registry for Halo CE directory."); try { RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft Games\Halo HEK"); m_CommonFilePath = key.GetValue("EXE Path").ToString() + @"\data"; //Output.WriteLine("Registry key found. Halo CE Data Directory:"); //Output.WriteLine(m_CommonFilePath); } catch { m_CommonFilePath = @"C:\Program Files\Microsoft Games\Halo Custom Edition\data"; //Output.WriteLine("Registry key not found. Defaulting Halo CE Data Directory to:\n"); //Output.WriteLine(m_CommonFilePath); } ModelData.Globals.DebugPath = Environment.CurrentDirectory + @"\debug.txt"; FileActive = false; FileModified = false; } private JMSFile m_JMSFile; private string m_FilePath; private bool m_FileModified = false; public bool FileModified { get { return m_FileModified; } set { m_FileModified = value; mnuFile_Save.Enabled = m_FileModified; if (m_FileModified) MainGroup.Text = Path.GetFileName(m_FilePath) + " *"; else MainGroup.Text = Path.GetFileName(m_FilePath); } } private bool m_FileActive = false; public bool FileActive { get { return m_FileActive; } set { m_FileActive = value; mnuFile_Open.Enabled = !m_FileActive; //mnuFile_Save.Enabled = m_FileActive; mnuFile_SaveAs.Enabled = m_FileActive; mnuFile_Close.Enabled = m_FileActive; // ----- mnuFile_Import.Enabled = m_FileActive; // ----- MainGroup_lblWelcome.Visible = !m_FileActive; // ----- MainGroup_lblNodeChecksum.Visible = m_FileActive; MainGroup_txtNodeChecksum.Visible = m_FileActive; MainGroup_btnUpdateNodeChecksum.Visible = m_FileActive; if (!m_FileActive) MainGroup.Text = ""; } } private void UpdateSigFigs() { try { ModelData.Globals.FigurePrecision = Convert.ToInt32(txtSigFigs.Text); } catch {} txtSigFigs.Text = ModelData.Globals.FigurePrecision.ToString(); } private void LoadModelData() { MainGroup_txtNodeChecksum.Text = m_JMSFile.NodeChecksum.ToString(); } private void SaveModelData() { bool changed = false; long nodeChecksum = Convert.ToInt64(MainGroup_txtNodeChecksum.Text); if (m_JMSFile.NodeChecksum != nodeChecksum) { m_JMSFile.NodeChecksum = Convert.ToInt64(MainGroup_txtNodeChecksum.Text); changed = true; } if (changed) FileModified = true; } private void mnuFile_Open_Click(object sender, EventArgs e) { if (FileActive) return; UpdateSigFigs(); HiPerfTimer timer = new HiPerfTimer(); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "JMS Files (*.jms)|*.jms"; dialog.Title = "Open JMS File"; dialog.InitialDirectory = m_CommonFilePath; DialogResult result = dialog.ShowDialog(); if (result != DialogResult.OK) return; Output.WriteLine("Opening " + dialog.FileName); StreamReader sr = new StreamReader(dialog.OpenFile()); m_FilePath = dialog.FileName; m_CommonFilePath = Path.GetDirectoryName(m_FilePath); string[] file = sr.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); sr.Close(); m_JMSFile = new JMSFile(); Output.Write("Reading JMS file... "); Application.DoEvents(); timer.Start(); m_JMSFile.ReadFromJMS(file); timer.Stop(); Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0} vertices found in JMS input file.", m_JMSFile.Vertices.Length)); Output.WriteLine("-------------------------"); Output.Write("Optimising JMS data... "); Application.DoEvents(); timer.Start(); m_JMSFile.Optimise(); timer.Stop(); Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0} unique vertices found.", m_JMSFile.UniqueVertices.Count)); Output.WriteLine("-------------------------"); FileActive = true; FileModified = false; LoadModelData(); } private void mnuFile_Import_Weights_Click(object sender, EventArgs e) { if (!FileActive) return; UpdateSigFigs(); HiPerfTimer timer = new HiPerfTimer(); OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Vertex Weight Files (*.txt)|*.txt"; dialog.Title = "Import Weight File"; dialog.InitialDirectory = m_CommonFilePath; DialogResult result = dialog.ShowDialog(); if (result != DialogResult.OK) return; Output.WriteLine("Opening " + dialog.FileName); StreamReader sr = new StreamReader(dialog.OpenFile()); string[] file = sr.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); sr.Close(); VWIFile vwi = new VWIFile(); Output.Write("Reading weight file... "); Application.DoEvents(); timer.Start(); vwi.ReadFromVWI(file); timer.Stop(); Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0} vertices found in the weight file.", vwi.Vertices.Length)); if (vwi.VerticesWithExcessBones != 0) { Output.WriteLine(String.Format("{0}/{1} vertices have excess bones.", vwi.VerticesWithExcessBones, vwi.Vertices.Length)); MessageBox.Show(String.Format("{0}/{1} vertices have more than 2 bones weighting them.\r\nOnly the first 2 bones per vertex will be merged.", vwi.VerticesWithExcessBones, vwi.Vertices.Length), "Vertices have excess bones"); } Output.WriteLine("-------------------------"); Output.Write("Optimising weight data... "); Application.DoEvents(); timer.Start(); vwi.Optimise(); timer.Stop(); Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0} unique vertices found.", vwi.UniqueVertices.Count)); Output.WriteLine("-------------------------"); Output.Write("Merging weight data... "); Application.DoEvents(); List<ModelTools.ModelData.JMS.Vertex> unmatched; timer.Start(); int matched = m_JMSFile.ImportWeights(vwi, null, out unmatched); timer.Stop(); Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0}/{1} vertices matched.", matched, m_JMSFile.UniqueVertices.Count)); Output.WriteLine("-------------------------"); if (matched != m_JMSFile.UniqueVertices.Count) { Output.WriteLine("A full search will be performed on the remaining " + (m_JMSFile.UniqueVertices.Count - matched) + " vertices."); Output.Write("Merging remaining weight data... "); Application.DoEvents(); ModelData.Globals.PerformHash = false; List<ModelTools.ModelData.JMS.Vertex> altUnmatched; timer.Start(); matched += m_JMSFile.ImportWeights(vwi, unmatched, out altUnmatched); timer.Stop(); unmatched = altUnmatched; ModelData.Globals.PerformHash = true; Output.WriteLine("Done. (" + timer.Duration.ToString("0.00000") + " seconds)"); Output.WriteLine(String.Format("{0}/{1} vertices now matched.", matched, m_JMSFile.UniqueVertices.Count)); Output.WriteLine("-------------------------"); } if (matched != m_JMSFile.UniqueVertices.Count) { StreamWriter sw = new StreamWriter(ModelData.Globals.DebugPath, true); sw.WriteLine("\r\n\r\n----------------------------------------------------\r\n"); sw.WriteLine(DateTime.Now.ToLongDateString()+" "+DateTime.Now.ToLongTimeString()); sw.WriteLine(String.Format("{0}/{1} vertices matched.", matched, m_JMSFile.UniqueVertices.Count)); sw.WriteLine(""); sw.WriteLine("JMS unmatched vertices -------------------------------------------"); sw.WriteLine(""); foreach (ModelTools.ModelData.JMS.Vertex v in unmatched) { sw.WriteLine(v.Location.ToString()); //sw.WriteLine("[" + v.Location.GetHashString() + " || " + v.Location.GetHashCode() + "]"); } sw.WriteLine(""); sw.WriteLine("VWI unmatched vertices -------------------------------------------"); sw.WriteLine(""); foreach (ModelTools.ModelData.VWI.Vertex v in vwi.UniqueVertices.Values) { sw.WriteLine(v.Location.ToString()); //sw.WriteLine("[" + v.Location.GetHashString() + " || " + v.Location.GetHashCode() + "]"); } sw.Close(); Output.WriteLine("Dumped vertex mismatch information to:"); Output.WriteLine(ModelData.Globals.DebugPath); } FileModified = true; } private void mnuFile_Close_Click(object sender, EventArgs e) { if (FileModified) { DialogResult result = MessageBox.Show("The file has been modified, save changes?", "Save Changes", MessageBoxButtons.YesNoCancel); switch (result) { case DialogResult.Yes: mnuFile_Save_Click(sender, e); break; case DialogResult.Cancel: return; } } m_FilePath = ""; FileModified = false; FileActive = false; m_JMSFile = null; OutputGroup_txtOutput.Clear(); } private void mnuFile_Save_Click(object sender, EventArgs e) { if (!FileActive) return; StreamWriter sw = new StreamWriter(new FileStream(m_FilePath, FileMode.Create)); string[] result = m_JMSFile.WriteToJMS(); foreach (string s in result) sw.WriteLine(s); sw.Close(); FileModified = false; } private void mnuFile_SaveAs_Click(object sender, EventArgs e) { if (!FileActive) return; SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "JMS Files (*.jms)|*.jms"; dialog.Title = "Save JMS File"; dialog.InitialDirectory = m_CommonFilePath; DialogResult result = dialog.ShowDialog(); if (result != DialogResult.OK) return; m_FilePath = dialog.FileName; m_CommonFilePath = Path.GetDirectoryName(m_FilePath); StreamWriter sw = new StreamWriter(dialog.OpenFile()); string[] file = m_JMSFile.WriteToJMS(); foreach (string s in file) sw.WriteLine(s); sw.Close(); FileModified = false; } private void MainGroup_btnUpdateNodeChecksum_Click(object sender, EventArgs e) { try { this.SaveModelData(); } catch { MessageBox.Show("Invalid Node Checksum"); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (FileModified) { DialogResult result = MessageBox.Show("The file has been modified, save changes?", "Save Changes", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) mnuFile_Save_Click(sender, e); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ComEventsMethod ** ** Purpose: part of ComEventHelpers APIs which allow binding ** managed delegates to COM's connection point based events. ** ** Date: April 2008 **/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; #if FEATURE_COMINTEROP namespace System.Runtime.InteropServices { // see code:ComEventsHelper#ComEventsArchitecture internal class ComEventsMethod { // This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's // existence is that under certain circumstances we need to coerce arguments to types expected by the // delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion // correctly but one known case is when the expected signature is 'ref Enum' - in this case // reflection by design does not do the coercion. Since we need to be compatible with COM interop // handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums' // and cache the types required for such coercion. internal class DelegateWrapper { private Delegate _d; private bool _once = false; private int _expectedParamsCount; private Type[] _cachedTargetTypes; public DelegateWrapper(Delegate d) { _d = d; } public Delegate Delegate { get { return _d; } set { _d = value; } } public object Invoke(object[] args) { if (_d == null) return null; if (_once == false) { PreProcessSignature(); _once = true; } if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) { for (int i = 0; i < _expectedParamsCount; i++) { if (_cachedTargetTypes[i] != null) { args[i] = Enum.ToObject(_cachedTargetTypes[i], args[i]); } } } return _d.DynamicInvoke(args); } private void PreProcessSignature() { ParameterInfo[] parameters = _d.Method.GetParameters(); _expectedParamsCount = parameters.Length; Type[] enumTypes = new Type[_expectedParamsCount]; bool needToHandleCoercion = false; for (int i = 0; i < _expectedParamsCount; i++) { ParameterInfo pi = parameters[i]; // recognize only 'ref Enum' signatures and cache // both enum type and the underlying type. if (pi.ParameterType.IsByRef && pi.ParameterType.HasElementType && pi.ParameterType.GetElementType().IsEnum) { needToHandleCoercion = true; enumTypes[i] = pi.ParameterType.GetElementType(); } } if (needToHandleCoercion == true) { _cachedTargetTypes = enumTypes; } } } #region private fields /// <summary> /// Invoking ComEventsMethod means invoking a multi-cast delegate attached to it. /// Since multicast delegate's built-in chaining supports only chaining instances of the same type, /// we need to complement this design by using an explicit linked list data structure. /// </summary> private DelegateWrapper [] _delegateWrappers; private int _dispid; private ComEventsMethod _next; #endregion #region ctor internal ComEventsMethod(int dispid) { _delegateWrappers = null; _dispid = dispid; } #endregion #region static internal methods internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) { while (methods != null && methods._dispid != dispid) { methods = methods._next; } return methods; } internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) { method._next = methods; return method; } internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) { if (methods == method) { methods = methods._next; } else { ComEventsMethod current = methods; while (current != null && current._next != method) current = current._next; if (current != null) current._next = method._next; } return methods; } #endregion #region public properties / methods internal int DispId { get { return _dispid; } } internal bool Empty { get { return _delegateWrappers == null || _delegateWrappers.Length == 0; } } internal void AddDelegate(Delegate d) { int count = 0; if (_delegateWrappers != null) { count = _delegateWrappers.Length; } for (int i = 0; i < count; i++) { if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { _delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d); return; } } DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1]; if (count > 0) { _delegateWrappers.CopyTo(newDelegateWrappers, 0); } DelegateWrapper wrapper = new DelegateWrapper(d); newDelegateWrappers[count] = wrapper; _delegateWrappers = newDelegateWrappers; } internal void RemoveDelegate(Delegate d) { int count = _delegateWrappers.Length; int removeIdx = -1; for (int i = 0; i < count; i++) { if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) { removeIdx = i; break; } } if (removeIdx < 0) return; Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d); if (newDelegate != null) { _delegateWrappers[removeIdx].Delegate = newDelegate; return; } // now remove the found entry from the _delegates array if (count == 1) { _delegateWrappers = null; return; } DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1]; int j = 0; while (j < removeIdx) { newDelegateWrappers[j] = _delegateWrappers[j]; j++; } while (j < count-1) { newDelegateWrappers[j] = _delegateWrappers[j + 1]; j++; } _delegateWrappers = newDelegateWrappers; } internal object Invoke(object[] args) { BCLDebug.Assert(Empty == false, "event sink is executed but delegates list is empty"); // Issue: see code:ComEventsHelper#ComEventsRetValIssue object result = null; DelegateWrapper[] invocationList = _delegateWrappers; foreach (DelegateWrapper wrapper in invocationList) { if (wrapper == null || wrapper.Delegate == null) continue; result = wrapper.Invoke(args); } return result; } #endregion } } #endif
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class LongKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* foo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOuterConst() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInnerConst() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IFoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = foo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = foo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() { await VerifyAbsenceAsync(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Foo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Foo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Foo(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Foo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Foo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Foo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Foo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Foo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Foo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() { await VerifyKeywordAsync(@"class c { async $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() { await VerifyAbsenceAsync(@"class c { async async $$ }"); } [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(int x) { } } ", matchPriority: SymbolMatchPriority.Keyword); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Serialization; namespace SharedCache.WinServiceTestClient.Common { [Serializable] public class Report { public List<Reporting> List = new List<Reporting>(); } [Serializable] public class Reporting { #region Property: runDateTime private DateTime runDateTime; /// <summary> /// Gets/sets the RunId /// </summary> [XmlAttribute("RunDateTime")] public DateTime RunDateTime { [System.Diagnostics.DebuggerStepThrough] get { return this.runDateTime; } [System.Diagnostics.DebuggerStepThrough] set { this.runDateTime = value; } } #endregion #region Property: ReportingOption private List<ReportingOption> reportingOption; /// <summary> /// Gets/sets the ReportingOption /// </summary> public List<ReportingOption> ReportingOption { [System.Diagnostics.DebuggerStepThrough] get { return this.reportingOption; } [System.Diagnostics.DebuggerStepThrough] set { this.reportingOption = value; } } #endregion #region Property: VersionNumber private string versionNumber; /// <summary> /// Gets/sets the VersionNumber /// </summary> public string VersionNumber { [System.Diagnostics.DebuggerStepThrough] get { return this.versionNumber; } [System.Diagnostics.DebuggerStepThrough] set { this.versionNumber = value; } } #endregion } [Serializable] public class ReportingOption { #region Property: runDateTime private DateTime runDateTime; /// <summary> /// Gets/sets the RunId /// </summary> [XmlAttribute("RunDateTime")] public DateTime RunDateTime { [System.Diagnostics.DebuggerStepThrough] get { return this.runDateTime; } [System.Diagnostics.DebuggerStepThrough] set { this.runDateTime = value; } } #endregion #region Property: LoggingEnabled private bool loggingEnabled ; /// <summary> /// Gets/sets the LoggingEnabled /// </summary> public bool LoggingEnabled { [System.Diagnostics.DebuggerStepThrough] get { return this.loggingEnabled ; } [System.Diagnostics.DebuggerStepThrough] set { this.loggingEnabled = value; } } #endregion #region Property: OneThread private bool oneThread; /// <summary> /// Gets/sets the OneThread /// </summary> public bool OneThread { [System.Diagnostics.DebuggerStepThrough] get { return this.oneThread; } [System.Diagnostics.DebuggerStepThrough] set { this.oneThread = value; } } #endregion #region Property: ZipEnabled private bool zipEnabled; /// <summary> /// Gets/sets the ZipEnabled /// </summary> public bool ZipEnabled { [System.Diagnostics.DebuggerStepThrough] get { return this.zipEnabled; } [System.Diagnostics.DebuggerStepThrough] set { this.zipEnabled = value; } } #endregion #region Property: Option private string option; /// <summary> /// Gets/sets the Option /// </summary> public string Option { [System.Diagnostics.DebuggerStepThrough] get { return this.option; } [System.Diagnostics.DebuggerStepThrough] set { this.option = value; } } #endregion #region Property: HashingAlgorithm private string hashingAlgorithm; /// <summary> /// Gets/sets the HashingAlgorithm /// </summary> public string HashingAlgorithm { [System.Diagnostics.DebuggerStepThrough] get { return this.hashingAlgorithm; } [System.Diagnostics.DebuggerStepThrough] set { this.hashingAlgorithm = value; } } #endregion #region Property: NeededAddTime private long neededAddTime; /// <summary> /// Gets/sets the NeededAddTime /// </summary> public long NeededAddTime { [System.Diagnostics.DebuggerStepThrough] get { return this.neededAddTime; } [System.Diagnostics.DebuggerStepThrough] set { this.neededAddTime = value; } } #endregion #region Property: NeededGetTime private long neededGetTime; /// <summary> /// Gets/sets the NeededGetTime /// </summary> public long NeededGetTime { [System.Diagnostics.DebuggerStepThrough] get { return this.neededGetTime; } [System.Diagnostics.DebuggerStepThrough] set { this.neededGetTime = value; } } #endregion #region Property: NeededDelTime private long neededDelTime; /// <summary> /// Gets/sets the NeededDelTime /// </summary> public long NeededDelTime { [System.Diagnostics.DebuggerStepThrough] get { return this.neededDelTime ; } [System.Diagnostics.DebuggerStepThrough] set { this.neededDelTime = value; } } #endregion #region Property: CompressionMinSize private int compressionMinSize; /// <summary> /// Gets/sets the CompressionMinSize /// </summary> public int CompressionMinSize { [System.Diagnostics.DebuggerStepThrough] get { return this.compressionMinSize; } [System.Diagnostics.DebuggerStepThrough] set { this.compressionMinSize = value; } } #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Text; namespace SIL.IO { public class SFMReader { #region ParseMode enum public enum ParseMode { Default, Shoebox, Usfm } #endregion private readonly TextReader buffer; private ParseMode _parseMode; private State _parseState = State.Init; private string _currentTag = string.Empty; private int _offset = 0; /// <summary> /// Construct a new SFMReader with filename /// </summary> /// <param name="fname"></param> public SFMReader(string fname) { buffer = new StreamReader(fname); } /// <summary> /// Construct a new SFMReader with stream /// </summary> /// <param name="stream"></param> public SFMReader(Stream stream) { buffer = new StreamReader(stream); } public SFMReader(TextReader reader) { buffer = reader; } public ParseMode Mode { get { return _parseMode; } set { _parseMode = value; } } public int Offset { get { return _offset; } } /// <summary> /// Read next tag and return the name only (exclude backslash /// and space). /// </summary> /// <returns>next tag name</returns> public string ReadNextTag() { switch (_parseState) { case State.Init: ReadInitialText(); break; case State.Text: ReadNextText(); break; } if (_parseState == State.Finished) { return null; } Debug.Assert(_parseState == State.Tag); int c = buffer.Read(); // advance input stream over the initial \ Debug.Assert(c == '\\' || c == -1); _offset++; return AlterStateAndReturnNextTag(); } private string AlterStateAndReturnNextTag() { bool hasReadNextChar = false; _currentTag = ProcessNextTokenAccordingToMode(ref hasReadNextChar); if (_currentTag == null) { _parseState = State.Finished; return null; } if (buffer.Peek() != '\\' && !hasReadNextChar) { int c = buffer.Read(); if(c != -1) { _offset++; } Debug.Assert(c == -1 || char.IsWhiteSpace((char) c)); } _parseState = State.Text; return _currentTag; } private string ProcessNextTokenAccordingToMode(ref bool hasReadNextChar) { string tag; if (Mode == ParseMode.Usfm) { tag = GetNextToken(delegate(char ch) { return Char.IsWhiteSpace(ch) || ch == '\\' || ch == '*'; }); if (buffer.Peek() == '*') { tag += (char) buffer.Read(); _offset++; hasReadNextChar = true; } } else { tag = GetNextToken(delegate(char ch) { return Char.IsWhiteSpace(ch) || ch == '\\'; }); } return tag; } private string GetNextToken(Predicate<char> isTokenTerminator) { StringBuilder token = new StringBuilder(); for (;;) { int peekedChar = buffer.Peek(); if (peekedChar == -1) //end of stream { if (token.Length == 0) return null; break; } if (isTokenTerminator((char) peekedChar)) break; char read = (char)peekedChar; buffer.Read(); _offset++; if (read == '\n' || read == '\r') { if (read == '\r' && ((char)buffer.Peek()) == '\n') { buffer.Read(); // eat it _offset++; } } token.Append(read); } return token.ToString(); } /// <summary> /// Read next text block from stream /// </summary> /// <returns>Next text</returns> public string ReadNextText() { if (_parseState == State.Init) { ReadInitialText(); } if (_parseState == State.Tag) { ReadNextTag(); } return ReadText(); } public string ReadInitialText() { if (_parseState != State.Init) throw new InvalidOperationException("ReadInitialText must be called before ReadNextText or ReadNextTag"); return ReadText() ?? ""; } private string ReadText() { if (_parseState == State.Finished) return null; string text = ReadTextAccordingToMode(); if (text == null) { _parseState = State.Finished; return ""; } _parseState = State.Tag; return text; } private string ReadTextAccordingToMode() { string text = string.Empty; do { string token = GetNextToken(delegate(char c) { return c == '\\'; }); text += token; if (Mode == ParseMode.Shoebox) { if (token == null) break; if (text.Length > 0 && text[text.Length - 1] != '\n' && buffer.Peek() != -1) { text += (char) buffer.Read(); _offset++; } else break; } } while (Mode == ParseMode.Shoebox); return text; } #region Nested type: State private enum State { Init, Tag, Text, Finished } ; #endregion } }
using System; using System.Diagnostics; using System.Collections; using HtmlHelp.ChmDecoding; namespace HtmlHelp { /// <summary> /// The class <c>TableOfContents</c> holds the TOC of the htmlhelp system class. /// </summary> public class TableOfContents { private ArrayList _toc = new ArrayList(); /// <summary> /// Standard constructor /// </summary> public TableOfContents() { } /// <summary> /// Constructor of the class /// </summary> /// <param name="toc"></param> public TableOfContents(ArrayList toc) { _toc = toc; } /// <summary> /// Gets the internal stored table of contents /// </summary> public ArrayList TOC { get { return _toc; } } /// <summary> /// Clears the current toc /// </summary> public void Clear() { if(_toc!=null) _toc.Clear(); } /// <summary> /// Gets the number of topics in the toc /// </summary> /// <returns>Returns the number of topics in the toc</returns> public int Count() { if(_toc!=null) return _toc.Count; else return 0; } /// <summary> /// Merges the <c>arrToC</c> list to the one in this instance /// </summary> /// <param name="arrToC">the toc list which should be merged with the current one</param> internal void MergeToC( ArrayList arrToC ) { if(_toc==null) _toc = new ArrayList(); Debug.WriteLine("TableOfContents.MergeToC() "); Debug.Indent(); Debug.WriteLine("Start: " + DateTime.Now.ToString("HH:mm:ss.ffffff")); MergeToC(_toc, arrToC, null); Debug.WriteLine("End: " + DateTime.Now.ToString("HH:mm:ss.ffffff")); Debug.Unindent(); } /// <summary> /// Merges the <c>arrToC</c> list to the one in this instance (called if merged files /// were found in a CHM) /// </summary> /// <param name="arrToC">the toc list which should be merged with the current one</param> /// <param name="openFiles">An arraylist of CHMFile instances.</param> internal void MergeToC( ArrayList arrToC, ArrayList openFiles ) { if(_toc==null) _toc = new ArrayList(); Debug.WriteLine("TableOfContents.MergeToC() "); Debug.Indent(); Debug.WriteLine("Start: " + DateTime.Now.ToString("HH:mm:ss.ffffff")); MergeToC(_toc, arrToC, openFiles); Debug.WriteLine("End: " + DateTime.Now.ToString("HH:mm:ss.ffffff")); Debug.Unindent(); } /// <summary> /// Internal method for recursive toc merging /// </summary> /// <param name="globalLevel">level of global toc</param> /// <param name="localLevel">level of local toc</param> /// <param name="openFiles">An arraylist of CHMFile instances.</param> private void MergeToC( ArrayList globalLevel, ArrayList localLevel, ArrayList openFiles ) { foreach( TOCItem curItem in localLevel) { // if it is a part of the merged-links, we have to do nothing, // because the method HtmlHelpSystem.RecalculateMergeLinks() has already // placed this item at its correct position. if(!IsMergedItem(curItem.Name, curItem.Local, openFiles)) { TOCItem globalItem = ContainsToC(globalLevel, curItem.Name); if(globalItem == null) { // the global toc doesn't have a topic with this name // so we need to add the complete toc node to the global toc globalLevel.Add( curItem ); } else { // the global toc contains the current topic // advance to the next level if( (globalItem.Local.Length <= 0) && (curItem.Local.Length > 0) ) { // set the associated url globalItem.Local = curItem.Local; globalItem.ChmFile = curItem.ChmFile; } MergeToC(globalItem.Children, curItem.Children); } } } } /// <summary> /// Checks if the item is part of the merged-links /// </summary> /// <param name="name">name of the topic</param> /// <param name="local">local of the topic</param> /// <param name="openFiles">An arraylist of CHMFile instances.</param> /// <returns>Returns true if this item is part of the merged-links</returns> private bool IsMergedItem(string name, string local, ArrayList openFiles) { if(openFiles==null) return false; foreach(CHMFile curFile in openFiles) { foreach(TOCItem curItem in curFile.MergLinks) if( (curItem.Name == name) && (curItem.Local == local) ) return true; } return false; } /// <summary> /// Checks if a topicname exists in a SINGLE toc level /// </summary> /// <param name="arrToC">toc list</param> /// <param name="Topic">topic to search</param> /// <returns>Returns the topic item if found, otherwise null</returns> private TOCItem ContainsToC(ArrayList arrToC, string Topic) { foreach(TOCItem curItem in arrToC) { if(curItem.Name == Topic) return curItem; } return null; } /// <summary> /// Searches the table of contents for a special topic /// </summary> /// <param name="topic">topic to search</param> /// <returns>Returns an instance of TOCItem if found, otherwise null</returns> public TOCItem SearchTopic(string topic) { return SearchTopic(topic, _toc); } /// <summary> /// Internal recursive tree search /// </summary> /// <param name="topic">topic to search</param> /// <param name="searchIn">tree level list to look in</param> /// <returns>Returns an instance of TOCItem if found, otherwise null</returns> private TOCItem SearchTopic(string topic, ArrayList searchIn) { foreach(TOCItem curItem in searchIn) { if(curItem.Name.ToLower() == topic.ToLower() ) return curItem; if(curItem.Children.Count>0) { TOCItem nf = SearchTopic(topic, curItem.Children); if(nf != null) return nf; } } return null; } } }
// // 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 Microsoft.WindowsAzure.Management.Sql; using Microsoft.WindowsAzure.Management.Sql.Models; namespace Microsoft.WindowsAzure.Management.Sql.Models { /// <summary> /// Response containing the service objective for a given server and /// service objective Id. /// </summary> public partial class ServiceObjectiveGetResponse : OperationResponse { private string _description; /// <summary> /// Gets or sets the service objective description. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private IList<ServiceObjectiveGetResponse.DimensionSettingResponse> _dimensionSettings; /// <summary> /// Gets or sets the service objective dimension settings. /// </summary> public IList<ServiceObjectiveGetResponse.DimensionSettingResponse> DimensionSettings { get { return this._dimensionSettings; } set { this._dimensionSettings = value; } } private bool _enabled; /// <summary> /// Gets or sets a value indicating whether the service objective is /// enabled. /// </summary> public bool Enabled { get { return this._enabled; } set { this._enabled = value; } } private string _id; /// <summary> /// Gets or sets the service objective id. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private bool _isDefault; /// <summary> /// Gets or sets a value indicating whether the service objective is /// the default objective. /// </summary> public bool IsDefault { get { return this._isDefault; } set { this._isDefault = value; } } private bool _isSystem; /// <summary> /// Gets or sets a value indicating whether the service objective is a /// system objective. /// </summary> public bool IsSystem { get { return this._isSystem; } set { this._isSystem = value; } } private string _name; /// <summary> /// Gets or sets the name of the service objective. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _parentLink; /// <summary> /// Gets or sets the ParentLink of the service objective. /// </summary> public string ParentLink { get { return this._parentLink; } set { this._parentLink = value; } } private string _selfLink; /// <summary> /// Gets or sets the SelfLink of the service objective. /// </summary> public string SelfLink { get { return this._selfLink; } set { this._selfLink = value; } } private string _state; /// <summary> /// Gets or sets the state of the service objective. /// </summary> public string State { get { return this._state; } set { this._state = value; } } private string _type; /// <summary> /// Gets or sets the type of resource. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the ServiceObjectiveGetResponse class. /// </summary> public ServiceObjectiveGetResponse() { this._dimensionSettings = new List<ServiceObjectiveGetResponse.DimensionSettingResponse>(); } /// <summary> /// Dimension setting. /// </summary> public partial class DimensionSettingResponse { private string _description; /// <summary> /// Gets or sets the dimension setting description. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _id; /// <summary> /// Gets or sets the dimension setting id. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private bool _isDefault; /// <summary> /// Gets or sets a value indicating whether the dimension setting /// is the default setting. /// </summary> public bool IsDefault { get { return this._isDefault; } set { this._isDefault = value; } } private string _name; /// <summary> /// Gets or sets the name of the dimension setting. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private byte _ordinal; /// <summary> /// Gets or sets the dimension setting ordinal position. /// </summary> public byte Ordinal { get { return this._ordinal; } set { this._ordinal = value; } } private string _parentLink; /// <summary> /// Gets or sets the ParentLink of the dimension setting. /// </summary> public string ParentLink { get { return this._parentLink; } set { this._parentLink = value; } } private string _selfLink; /// <summary> /// Gets or sets the SelfLink of the dimension setting. /// </summary> public string SelfLink { get { return this._selfLink; } set { this._selfLink = value; } } private string _state; /// <summary> /// Gets or sets the state of the dimension setting. /// </summary> public string State { get { return this._state; } set { this._state = value; } } private string _type; /// <summary> /// Gets or sets the type of resource. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } /// <summary> /// Initializes a new instance of the DimensionSettingResponse /// class. /// </summary> public DimensionSettingResponse() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private const int IcmpHeaderLengthInBytes = 8; private const int MinIpHeaderLengthInBytes = 20; private const int MaxIpHeaderLengthInBytes = 60; [ThreadStatic] private static Random t_idGenerator; private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { PingReply reply = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ? SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options) : SendWithPingUtility(address, buffer, timeout, options); return reply; } private async Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { Task<PingReply> t = RawSocketPermissions.CanUseRawSockets(address.AddressFamily) ? SendIcmpEchoRequestOverRawSocketAsync(address, buffer, timeout, options) : SendWithPingUtilityAsync(address, buffer, timeout, options); PingReply reply = await t.ConfigureAwait(false); if (_canceled) { throw new OperationCanceledException(); } return reply; } private SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions options) { SocketConfig config = new SocketConfig(); config.EndPoint = new IPEndPoint(address, 0); config.Timeout = timeout; config.Options = options; config.IsIpv4 = address.AddressFamily == AddressFamily.InterNetwork; config.ProtocolType = config.IsIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6; // Use a random value as the identifier. This doesn't need to be perfectly random // or very unpredictable, rather just good enough to avoid unexpected conflicts. Random rand = t_idGenerator ?? (t_idGenerator = new Random()); config.Identifier = (ushort)rand.Next((int)ushort.MaxValue + 1); IcmpHeader header = new IcmpHeader() { Type = config.IsIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest, Code = 0, HeaderChecksum = 0, Identifier = config.Identifier, SequenceNumber = 0, }; config.SendBuffer = CreateSendMessageBuffer(header, buffer); return config; } private Socket GetRawSocket(SocketConfig socketConfig) { IPEndPoint ep = (IPEndPoint)socketConfig.EndPoint; // Setting Socket.DontFragment and .Ttl is not supported on Unix, so socketConfig.Options is ignored. AddressFamily addrFamily = ep.Address.AddressFamily; Socket socket = new Socket(addrFamily, SocketType.Raw, socketConfig.ProtocolType); socket.ReceiveTimeout = socketConfig.Timeout; socket.SendTimeout = socketConfig.Timeout; if (socketConfig.Options != null && socketConfig.Options.Ttl > 0) { socket.Ttl = (short)socketConfig.Options.Ttl; } if (socketConfig.Options != null && addrFamily == AddressFamily.InterNetwork) { socket.DontFragment = socketConfig.Options.DontFragment; } #pragma warning disable 618 // Disable warning about obsolete property. We could use GetAddressBytes but that allocates. // IPv4 multicast address starts with 1110 bits so mask rest and test if we get correct value e.g. 0xe0. if (!ep.Address.IsIPv6Multicast && !(addrFamily == AddressFamily.InterNetwork && (ep.Address.Address & 0xf0) == 0xe0)) { // If it is not multicast, use Connect to scope responses only to the target address. socket.Connect(socketConfig.EndPoint); } #pragma warning restore 618 return socket; } private bool TryGetPingReply(SocketConfig socketConfig, byte[] receiveBuffer, int bytesReceived, Stopwatch sw, ref int ipHeaderLength, out PingReply reply) { byte type, code; reply = null; if (socketConfig.IsIpv4) { // Determine actual size of IP header byte ihl = (byte)(receiveBuffer[0] & 0x0f); // Internet Header Length ipHeaderLength = 4 * ihl; if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { return false; // Not enough bytes to reconstruct actual IP header + ICMP header. } } int icmpHeaderOffset = ipHeaderLength; // Skip IP header. IcmpHeader receivedHeader = MemoryMarshal.Read<IcmpHeader>(receiveBuffer.AsSpan(icmpHeaderOffset)); type = receivedHeader.Type; code = receivedHeader.Code; if (socketConfig.Identifier != receivedHeader.Identifier || type == (byte)IcmpV4MessageType.EchoRequest || type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore { return false; } sw.Stop(); long roundTripTime = sw.ElapsedMilliseconds; int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes; // We want to return a buffer with the actual data we sent out, not including the header data. byte[] dataBuffer = new byte[bytesReceived - dataOffset]; Buffer.BlockCopy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length); IPStatus status = socketConfig.IsIpv4 ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code) : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code); IPAddress address = ((IPEndPoint)socketConfig.EndPoint).Address; reply = new PingReply(address, socketConfig.Options, status, roundTripTime, dataBuffer); return true; } private PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); using (Socket socket = GetRawSocket(socketConfig)) { int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0; try { socket.SendTo(socketConfig.SendBuffer, SocketFlags.None, socketConfig.EndPoint); } catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut) { return CreateTimedOutPingReply(); } byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length]; long elapsed; Stopwatch sw = Stopwatch.StartNew(); // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. while ((elapsed = sw.ElapsedMilliseconds) < timeout) { int bytesReceived; try { bytesReceived = socket.ReceiveFrom(receiveBuffer, SocketFlags.None, ref socketConfig.EndPoint); } catch (SocketException ex) when (ex.SocketErrorCode == SocketError.TimedOut) { return CreateTimedOutPingReply(); } if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { continue; // Not enough bytes to reconstruct IP header + ICMP header. } if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, sw, ref ipHeaderLength, out PingReply reply)) { return reply; } } // We have exceeded our timeout duration, and no reply has been received. return CreateTimedOutPingReply(); } } private async Task<PingReply> SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); using (Socket socket = GetRawSocket(socketConfig)) { int ipHeaderLength = socketConfig.IsIpv4 ? MinIpHeaderLengthInBytes : 0; await socket.SendToAsync( new ArraySegment<byte>(socketConfig.SendBuffer), SocketFlags.None, socketConfig.EndPoint) .ConfigureAwait(false); byte[] receiveBuffer = new byte[MaxIpHeaderLengthInBytes + IcmpHeaderLengthInBytes + buffer.Length]; long elapsed; Stopwatch sw = Stopwatch.StartNew(); // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout. // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads. while ((elapsed = sw.ElapsedMilliseconds) < timeout) { Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync( new ArraySegment<byte>(receiveBuffer), SocketFlags.None, socketConfig.EndPoint); var cts = new CancellationTokenSource(); Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false); cts.Cancel(); if (finished != receiveTask) { return CreateTimedOutPingReply(); } SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult(); int bytesReceived = receiveResult.ReceivedBytes; if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes) { continue; // Not enough bytes to reconstruct IP header + ICMP header. } if (TryGetPingReply(socketConfig, receiveBuffer, bytesReceived, sw, ref ipHeaderLength, out PingReply reply)) { return reply; } } // We have exceeded our timeout duration, and no reply has been received. return CreateTimedOutPingReply(); } } private Process GetPingProcess(IPAddress address, byte[] buffer, PingOptions options) { bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork; string pingExecutable = isIpv4 ? UnixCommandLinePing.Ping4UtilityPath : UnixCommandLinePing.Ping6UtilityPath; if (pingExecutable == null) { throw new PlatformNotSupportedException(SR.net_ping_utility_not_found); } UnixCommandLinePing.PingFragmentOptions fragmentOption = UnixCommandLinePing.PingFragmentOptions.Default; if (options != null && address.AddressFamily == AddressFamily.InterNetwork) { fragmentOption = options.DontFragment ? UnixCommandLinePing.PingFragmentOptions.Do : UnixCommandLinePing.PingFragmentOptions.Dont; } string processArgs = UnixCommandLinePing.ConstructCommandLine(buffer.Length, address.ToString(), isIpv4, options?.Ttl ?? 0, fragmentOption); ProcessStartInfo psi = new ProcessStartInfo(pingExecutable, processArgs); psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; return new Process() { StartInfo = psi }; } private PingReply SendWithPingUtility(IPAddress address, byte[] buffer, int timeout, PingOptions options) { using (Process p = GetPingProcess(address, buffer, options)) { p.Start(); if (!p.WaitForExit(timeout) || p.ExitCode == 1 || p.ExitCode == 2) { return CreateTimedOutPingReply(); } try { string output = p.StandardOutput.ReadToEnd(); return ParsePingUtilityOutput(address, output); } catch (Exception) { // If the standard output cannot be successfully parsed, throw a generic PingException. throw new PingException(SR.net_ping); } } } private async Task<PingReply> SendWithPingUtilityAsync(IPAddress address, byte[] buffer, int timeout, PingOptions options) { using (Process p = GetPingProcess(address, buffer, options)) { var processCompletion = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); p.EnableRaisingEvents = true; p.Exited += (s, e) => processCompletion.SetResult(true); p.Start(); var cts = new CancellationTokenSource(); Task timeoutTask = Task.Delay(timeout, cts.Token); Task finished = await Task.WhenAny(processCompletion.Task, timeoutTask).ConfigureAwait(false); if (finished == timeoutTask && !p.HasExited) { // Try to kill the ping process if it didn't return. If it is already in the process of exiting, // a Win32Exception will be thrown or we will get InvalidOperationException if it already exited. try { p.Kill(); } catch (Win32Exception) { } catch (InvalidOperationException) { } return CreateTimedOutPingReply(); } else { cts.Cancel(); if (p.ExitCode == 1 || p.ExitCode == 2) { // Throw timeout for known failure return codes from ping functions. return CreateTimedOutPingReply(); } try { string output = await p.StandardOutput.ReadToEndAsync().ConfigureAwait(false); return ParsePingUtilityOutput(address, output); } catch (Exception) { // If the standard output cannot be successfully parsed, throw a generic PingException. throw new PingException(SR.net_ping); } } } } private PingReply ParsePingUtilityOutput(IPAddress address, string output) { long rtt = UnixCommandLinePing.ParseRoundTripTime(output); return new PingReply( address, null, // Ping utility cannot accommodate these, return null to indicate they were ignored. IPStatus.Success, rtt, Array.Empty<byte>()); // Ping utility doesn't deliver this info. } private PingReply CreateTimedOutPingReply() { // Documentation indicates that you should only pay attention to the IPStatus value when // its value is not "Success", but the rest of these values match that of the Windows implementation. return new PingReply(new IPAddress(0), null, IPStatus.TimedOut, 0, Array.Empty<byte>()); } #if DEBUG static Ping() { Debug.Assert(Marshal.SizeOf<IcmpHeader>() == 8, "The size of an ICMP Header must be 8 bytes."); } #endif // Must be 8 bytes total. [StructLayout(LayoutKind.Sequential)] internal struct IcmpHeader { public byte Type; public byte Code; public ushort HeaderChecksum; public ushort Identifier; public ushort SequenceNumber; } // Since this is private should be safe to trust that the calling code // will behave. To get a little performance boost raw fields are exposed // and no validation is performed. private class SocketConfig { public EndPoint EndPoint; public PingOptions Options; public ushort Identifier; public bool IsIpv4; public ProtocolType ProtocolType; public int Timeout; public byte[] SendBuffer; } private static unsafe byte[] CreateSendMessageBuffer(IcmpHeader header, byte[] payload) { int headerSize = sizeof(IcmpHeader); byte[] result = new byte[headerSize + payload.Length]; Marshal.Copy(new IntPtr(&header), result, 0, headerSize); payload.CopyTo(result, headerSize); ushort checksum = ComputeBufferChecksum(result); // Jam the checksum into the buffer. result[2] = (byte)(checksum >> 8); result[3] = (byte)(checksum & (0xFF)); return result; } private static ushort ComputeBufferChecksum(byte[] buffer) { // This is using the "deferred carries" approach outlined in RFC 1071. uint sum = 0; for (int i = 0; i < buffer.Length; i += 2) { // Combine each pair of bytes into a 16-bit number and add it to the sum ushort element0 = (ushort)((buffer[i] << 8) & 0xFF00); ushort element1 = (i + 1 < buffer.Length) ? (ushort)(buffer[i + 1] & 0x00FF) : (ushort)0; // If there's an odd number of bytes, pad by one octet of zeros. ushort combined = (ushort)(element0 | element1); sum += (uint)combined; } // Add back the "carry bits" which have risen to the upper 16 bits of the sum. while ((sum >> 16) != 0) { var partialSum = sum & 0xFFFF; var carries = sum >> 16; sum = partialSum + carries; } return unchecked((ushort)~sum); } } }
namespace PSTaskDialog { partial class frmTaskDialog { /// <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(frmTaskDialog)); this.imgMain = new System.Windows.Forms.PictureBox(); this.lbContent = new System.Windows.Forms.Label(); this.pnlButtons = new System.Windows.Forms.Panel(); this.bt1 = new System.Windows.Forms.Button(); this.bt2 = new System.Windows.Forms.Button(); this.bt3 = new System.Windows.Forms.Button(); this.cbVerify = new System.Windows.Forms.CheckBox(); this.lbShowHideDetails = new System.Windows.Forms.Label(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.panel2 = new System.Windows.Forms.Panel(); this.pnlFooter = new System.Windows.Forms.Panel(); this.lbFooter = new System.Windows.Forms.Label(); this.imgFooter = new System.Windows.Forms.PictureBox(); this.panel5 = new System.Windows.Forms.Panel(); this.panel3 = new System.Windows.Forms.Panel(); this.pnlCommandButtons = new System.Windows.Forms.Panel(); this.pnlMainInstruction = new System.Windows.Forms.Panel(); this.pnlContent = new System.Windows.Forms.Panel(); this.pnlExpandedInfo = new System.Windows.Forms.Panel(); this.lbExpandedInfo = new System.Windows.Forms.Label(); this.pnlRadioButtons = new System.Windows.Forms.Panel(); ((System.ComponentModel.ISupportInitialize)(this.imgMain)).BeginInit(); this.pnlButtons.SuspendLayout(); this.pnlFooter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.imgFooter)).BeginInit(); this.pnlMainInstruction.SuspendLayout(); this.pnlContent.SuspendLayout(); this.pnlExpandedInfo.SuspendLayout(); this.SuspendLayout(); // // imgMain // this.imgMain.Location = new System.Drawing.Point(8, 8); this.imgMain.Name = "imgMain"; this.imgMain.Size = new System.Drawing.Size(32, 32); this.imgMain.TabIndex = 0; this.imgMain.TabStop = false; // // lbContent // this.lbContent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbContent.Location = new System.Drawing.Point(50, 0); this.lbContent.Name = "lbContent"; this.lbContent.Size = new System.Drawing.Size(389, 19); this.lbContent.TabIndex = 0; this.lbContent.Text = "lbContent"; // // pnlButtons // this.pnlButtons.BackColor = System.Drawing.Color.WhiteSmoke; this.pnlButtons.Controls.Add(this.bt1); this.pnlButtons.Controls.Add(this.bt2); this.pnlButtons.Controls.Add(this.bt3); this.pnlButtons.Controls.Add(this.cbVerify); this.pnlButtons.Controls.Add(this.lbShowHideDetails); this.pnlButtons.Controls.Add(this.panel2); this.pnlButtons.Dock = System.Windows.Forms.DockStyle.Top; this.pnlButtons.Location = new System.Drawing.Point(0, 301); this.pnlButtons.Name = "pnlButtons"; this.pnlButtons.Size = new System.Drawing.Size(444, 58); this.pnlButtons.TabIndex = 0; // // bt1 // this.bt1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bt1.Location = new System.Drawing.Point(198, 8); this.bt1.Name = "bt1"; this.bt1.Size = new System.Drawing.Size(75, 23); this.bt1.TabIndex = 0; this.bt1.Text = "bt1"; this.bt1.UseVisualStyleBackColor = true; // // bt2 // this.bt2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bt2.Location = new System.Drawing.Point(279, 8); this.bt2.Name = "bt2"; this.bt2.Size = new System.Drawing.Size(75, 23); this.bt2.TabIndex = 1; this.bt2.Text = "bt2"; this.bt2.UseVisualStyleBackColor = true; // // bt3 // this.bt3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bt3.Location = new System.Drawing.Point(360, 8); this.bt3.Name = "bt3"; this.bt3.Size = new System.Drawing.Size(75, 23); this.bt3.TabIndex = 2; this.bt3.Text = "bt3"; this.bt3.UseVisualStyleBackColor = true; // // cbVerify // this.cbVerify.AutoSize = true; this.cbVerify.Location = new System.Drawing.Point(13, 34); this.cbVerify.Name = "cbVerify"; this.cbVerify.Size = new System.Drawing.Size(136, 17); this.cbVerify.TabIndex = 4; this.cbVerify.Text = "Don\'t ask me this again"; this.cbVerify.UseVisualStyleBackColor = true; this.cbVerify.Visible = false; // // lbShowHideDetails // this.lbShowHideDetails.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.lbShowHideDetails.ImageIndex = 3; this.lbShowHideDetails.ImageList = this.imageList1; this.lbShowHideDetails.Location = new System.Drawing.Point(8, 6); this.lbShowHideDetails.Name = "lbShowHideDetails"; this.lbShowHideDetails.Size = new System.Drawing.Size(94, 23); this.lbShowHideDetails.TabIndex = 3; this.lbShowHideDetails.Text = " Show details"; this.lbShowHideDetails.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.lbShowHideDetails.MouseLeave += new System.EventHandler(this.lbDetails_MouseLeave); this.lbShowHideDetails.Click += new System.EventHandler(this.lbDetails_Click); this.lbShowHideDetails.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lbDetails_MouseDown); this.lbShowHideDetails.MouseUp += new System.Windows.Forms.MouseEventHandler(this.lbDetails_MouseUp); this.lbShowHideDetails.MouseEnter += new System.EventHandler(this.lbDetails_MouseEnter); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Fuchsia; this.imageList1.Images.SetKeyName(0, "arrow_up_bw.bmp"); this.imageList1.Images.SetKeyName(1, "arrow_up_color.bmp"); this.imageList1.Images.SetKeyName(2, "arrow_up_color_pressed.bmp"); this.imageList1.Images.SetKeyName(3, "arrow_down_bw.bmp"); this.imageList1.Images.SetKeyName(4, "arrow_down_color.bmp"); this.imageList1.Images.SetKeyName(5, "arrow_down_color_pressed.bmp"); this.imageList1.Images.SetKeyName(6, "green_arrow.bmp"); // // panel2 // this.panel2.BackColor = System.Drawing.Color.Gainsboro; this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(444, 1); this.panel2.TabIndex = 0; // // pnlFooter // this.pnlFooter.BackColor = System.Drawing.Color.WhiteSmoke; this.pnlFooter.Controls.Add(this.lbFooter); this.pnlFooter.Controls.Add(this.imgFooter); this.pnlFooter.Controls.Add(this.panel5); this.pnlFooter.Controls.Add(this.panel3); this.pnlFooter.Dock = System.Windows.Forms.DockStyle.Top; this.pnlFooter.Location = new System.Drawing.Point(0, 359); this.pnlFooter.Name = "pnlFooter"; this.pnlFooter.Size = new System.Drawing.Size(444, 36); this.pnlFooter.TabIndex = 2; // // lbFooter // this.lbFooter.Location = new System.Drawing.Point(30, 11); this.lbFooter.Name = "lbFooter"; this.lbFooter.Size = new System.Drawing.Size(409, 15); this.lbFooter.TabIndex = 4; this.lbFooter.Text = "lbFooter"; // // imgFooter // this.imgFooter.Location = new System.Drawing.Point(8, 10); this.imgFooter.Name = "imgFooter"; this.imgFooter.Size = new System.Drawing.Size(16, 16); this.imgFooter.TabIndex = 4; this.imgFooter.TabStop = false; // // panel5 // this.panel5.BackColor = System.Drawing.Color.White; this.panel5.Dock = System.Windows.Forms.DockStyle.Top; this.panel5.Location = new System.Drawing.Point(0, 1); this.panel5.Name = "panel5"; this.panel5.Size = new System.Drawing.Size(444, 1); this.panel5.TabIndex = 2; // // panel3 // this.panel3.BackColor = System.Drawing.Color.Gainsboro; this.panel3.Dock = System.Windows.Forms.DockStyle.Top; this.panel3.Location = new System.Drawing.Point(0, 0); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(444, 1); this.panel3.TabIndex = 1; // // pnlCommandButtons // this.pnlCommandButtons.Dock = System.Windows.Forms.DockStyle.Top; this.pnlCommandButtons.Location = new System.Drawing.Point(0, 202); this.pnlCommandButtons.Name = "pnlCommandButtons"; this.pnlCommandButtons.Size = new System.Drawing.Size(444, 99); this.pnlCommandButtons.TabIndex = 4; // // pnlMainInstruction // this.pnlMainInstruction.Controls.Add(this.imgMain); this.pnlMainInstruction.Dock = System.Windows.Forms.DockStyle.Top; this.pnlMainInstruction.Location = new System.Drawing.Point(0, 0); this.pnlMainInstruction.Name = "pnlMainInstruction"; this.pnlMainInstruction.Size = new System.Drawing.Size(444, 41); this.pnlMainInstruction.TabIndex = 1; this.pnlMainInstruction.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlMainInstruction_Paint); // // pnlContent // this.pnlContent.Controls.Add(this.lbContent); this.pnlContent.Dock = System.Windows.Forms.DockStyle.Top; this.pnlContent.Location = new System.Drawing.Point(0, 41); this.pnlContent.Name = "pnlContent"; this.pnlContent.Size = new System.Drawing.Size(444, 30); this.pnlContent.TabIndex = 2; // // pnlExpandedInfo // this.pnlExpandedInfo.Controls.Add(this.lbExpandedInfo); this.pnlExpandedInfo.Dock = System.Windows.Forms.DockStyle.Top; this.pnlExpandedInfo.Location = new System.Drawing.Point(0, 71); this.pnlExpandedInfo.Name = "pnlExpandedInfo"; this.pnlExpandedInfo.Size = new System.Drawing.Size(444, 30); this.pnlExpandedInfo.TabIndex = 10; // // lbExpandedInfo // this.lbExpandedInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbExpandedInfo.Location = new System.Drawing.Point(50, 0); this.lbExpandedInfo.Name = "lbExpandedInfo"; this.lbExpandedInfo.Size = new System.Drawing.Size(389, 19); this.lbExpandedInfo.TabIndex = 0; this.lbExpandedInfo.Text = "lbExpandedInfo"; // // pnlRadioButtons // this.pnlRadioButtons.Dock = System.Windows.Forms.DockStyle.Top; this.pnlRadioButtons.Location = new System.Drawing.Point(0, 101); this.pnlRadioButtons.Name = "pnlRadioButtons"; this.pnlRadioButtons.Size = new System.Drawing.Size(444, 101); this.pnlRadioButtons.TabIndex = 3; // // frmTaskDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(444, 459); this.Controls.Add(this.pnlFooter); this.Controls.Add(this.pnlButtons); this.Controls.Add(this.pnlCommandButtons); this.Controls.Add(this.pnlRadioButtons); this.Controls.Add(this.pnlExpandedInfo); this.Controls.Add(this.pnlContent); this.Controls.Add(this.pnlMainInstruction); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmTaskDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "frmTaskDialog"; this.Shown += new System.EventHandler(this.frmTaskDialog_Shown); ((System.ComponentModel.ISupportInitialize)(this.imgMain)).EndInit(); this.pnlButtons.ResumeLayout(false); this.pnlButtons.PerformLayout(); this.pnlFooter.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.imgFooter)).EndInit(); this.pnlMainInstruction.ResumeLayout(false); this.pnlContent.ResumeLayout(false); this.pnlExpandedInfo.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox imgMain; private System.Windows.Forms.Label lbContent; private System.Windows.Forms.Panel pnlButtons; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Panel pnlFooter; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Panel panel5; private System.Windows.Forms.PictureBox imgFooter; private System.Windows.Forms.Label lbFooter; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.Label lbShowHideDetails; private System.Windows.Forms.Panel pnlCommandButtons; private System.Windows.Forms.CheckBox cbVerify; private System.Windows.Forms.Panel pnlMainInstruction; private System.Windows.Forms.Panel pnlContent; private System.Windows.Forms.Panel pnlExpandedInfo; private System.Windows.Forms.Label lbExpandedInfo; private System.Windows.Forms.Panel pnlRadioButtons; private System.Windows.Forms.Button bt1; private System.Windows.Forms.Button bt2; private System.Windows.Forms.Button bt3; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.Web.Routing; using MvcContrib.TestHelper; using NUnit.Framework; using AssertionException = MvcContrib.TestHelper.AssertionException; namespace MvcContrib.UnitTests.TestHelper { [TestFixture] public class RouteTestingExtensionsTester { public class FunkyController : Controller { public ActionResult Index() { return null; } public ActionResult Bar(string id) { return null; } public ActionResult New() { return null; } public ActionResult List(Bar bar) { return null; } public ActionResult Foo(int id) { return null; } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Zordo(int id) { return null; } public ActionResult Guid(Guid id) { return null; } public ActionResult Nullable(int? id) { return null; } public ActionResult DateTime(DateTime id) { return null; } public ActionResult NullableDateTime(DateTime? id) { return null; } [ActionName("ActionName")] public ActionResult MethodNameDoesntMatch() { return null; } public ActionResult ParameterNameDoesntMatch(string someParameter) { return null; } } public class OptionalExampleController : Controller { public ActionResult NullableInt(int? id) { return null; } public ActionResult String(string id) { return null; } } public class Bar {} public class AwesomeController : Controller {} public class HasControllerInMiddleOfNameController : Controller { public ActionResult Index() { return null; } } [SetUp] public void Setup() { RouteTable.Routes.Clear(); RouteTable.Routes.IgnoreRoute("{resource}.gif/{*pathInfo}"); RouteTable.Routes.MapRoute( "optional-nullable", "optional/nullableint/{id}", new {controller = "OptionalExample", Action = "NullableInt", id = UrlParameter.Optional} ); RouteTable.Routes.MapRoute( "optional-string", "optional/string/{id}", new {controller = "OptionalExample", Action = "String", id = UrlParameter.Optional} ); RouteTable.Routes.MapRoute( "default", "{controller}/{action}/{id}", new {controller = "Funky", Action = "Index", id = ""}); } [TearDown] public void TearDown() { RouteTable.Routes.Clear(); } [Test] public void should_be_able_to_pull_routedata_from_a_string() { var routeData = "~/charlie/brown".Route(); Assert.That(routeData, Is.Not.Null); Assert.That(routeData.Values.ContainsValue("charlie")); Assert.That(routeData.Values.ContainsValue("brown")); } [Test] public void should_be_able_to_match_controller_from_route_data() { "~/".Route().ShouldMapTo<FunkyController>(); } [Test, ExpectedException(typeof(AssertionException))] public void should_be_able_to_detect_when_a_controller_doesnt_match() { "~/".Route().ShouldMapTo<AwesomeController>(); } [Test] public void should_be_able_to_match_action_with_lambda() { "~/".Route().ShouldMapTo<FunkyController>(x => x.Index()); } [Test, ExpectedException(typeof(AssertionException))] public void should_be_able_to_detect_an_incorrect_action() { "~/".Route().ShouldMapTo<FunkyController>(x => x.New()); } [Test] public void should_be_able_to_match_action_parameters() { "~/funky/bar/widget".Route().ShouldMapTo<FunkyController>(x => x.Bar("widget")); } [Test, ExpectedException(typeof(AssertionException))] public void should_be_able_to_detect_invalid_action_parameters() { "~/funky/bar/widget".Route().ShouldMapTo<FunkyController>(x => x.Bar("something_else")); } [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Value for parameter 'id' did not match: expected 'something_else' but was 'widget'.")] public void should_provide_detailed_exception_message_when_detecting_invalid_action_parameters() { "~/funky/bar/widget".Route().ShouldMapTo<FunkyController>(x => x.Bar("something_else")); } [Test] public void should_be_able_to_test_routes_directly_from_a_string() { "~/funky/bar/widget".ShouldMapTo<FunkyController>(x => x.Bar("widget")); } [Test] public void should_be_able_to_test_routes_with_member_expressions_being_used() { var widget = "widget"; "~/funky/bar/widget".ShouldMapTo<FunkyController>(x => x.Bar(widget)); } [Test] public void should_be_able_to_test_routes_with_member_expressions_being_used_but_ignore_null_complex_parameteres() { "~/funky/List".ShouldMapTo<FunkyController>(x => x.List(null)); } [Test] public void should_be_able_to_ignore_requests() { "~/someimage.gif".ShouldBeIgnored(); } [Test] public void should_be_able_to_ignore_requests_with_path_info() { "~/someimage.gif/with_stuff".ShouldBeIgnored(); } [Test] public void should_be_able_to_match_non_string_action_parameters() { "~/funky/foo/1234".Route().ShouldMapTo<FunkyController>(x => x.Foo(1234)); } [Test] public void assertion_exception_should_hide_the_test_helper_frames_in_the_call_stack() { IEnumerable<string> callstack = new string[0]; try { "~/badroute that is not configures/foo/1234".Route().ShouldMapTo<FunkyController>(x => x.Foo(1234)); } catch(Exception ex) { callstack = ex.StackTrace.Split(new[] {Environment.NewLine}, StringSplitOptions.None); } callstack.Count().ShouldEqual(1); } [Test] public void should_be_able_to_generate_url_from_named_route() { RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute( "namedRoute", "{controller}/{action}/{id}", new {controller = "Funky", Action = "Index", id = ""}); OutBoundUrl.OfRouteNamed("namedRoute").ShouldMapToUrl("/"); } [Test] public void should_be_able_to_generate_url_from_controller_action_where_action_is_default() { OutBoundUrl.Of<FunkyController>(x => x.Index()).ShouldMapToUrl("/"); } [Test] public void should_be_able_to_generate_url_from_controller_action() { OutBoundUrl.Of<FunkyController>(x => x.New()).ShouldMapToUrl("/Funky/New"); } [Test] public void should_be_able_to_generate_url_from_controller_action_with_parameter() { OutBoundUrl.Of<FunkyController>(x => x.Foo(1)).ShouldMapToUrl("/Funky/Foo/1"); } [Test] public void should_be_able_to_match_action_with_lambda_and_httpmethod() { RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute( "zordoRoute", "{controller}/{action}/{id}", new {controller = "Funky", Action = "Zordo", id = "0"}, new {httpMethod = new HttpMethodConstraint("POST")}); "~/Funky/Zordo/0".WithMethod(HttpVerbs.Post).ShouldMapTo<FunkyController>(x => x.Zordo(0)); } [Test] public void should_not_be_able_to_get_routedata_with_wrong_httpmethod() { RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute( "zordoRoute", "{controller}/{action}/{id}", new {controller = "Funky", Action = "Zordo", id = "0"}, new {httpMethod = new HttpMethodConstraint("POST")}); var routeData = "~/Funky/Zordo/0".WithMethod(HttpVerbs.Get); Assert.IsNull(routeData); } [Test] public void should_match_guid() { "~/funky/guid/80e70232-e660-40ae-af6b-2b2b8e87ee48".Route().ShouldMapTo<FunkyController>(c => c.Guid(new Guid("80e70232-e660-40ae-af6b-2b2b8e87ee48"))); } [Test] public void should_match_nullable_int() { "~/funky/nullable/24".Route().ShouldMapTo<FunkyController>(c => c.Nullable(24)); } [Test] public void should_match_nullable_int_when_null() { RouteTable.Routes.Clear(); RouteTable.Routes.IgnoreRoute("{resource}.gif/{*pathInfo}"); RouteTable.Routes.MapRoute( "default", "{controller}/{action}/{id}", new {controller = "Funky", Action = "Index", id = (int?)null}); "~/funky/nullable".Route().ShouldMapTo<FunkyController>(c => c.Nullable(null)); } [Test] public void should_be_able_to_generate_url_with_nullable_int_action_parameter() { OutBoundUrl.Of<FunkyController>(c => c.Nullable(24)).ShouldMapToUrl("/funky/nullable/24"); } [Test] public void should_be_able_to_generate_url_with_optional_nullable_int_action_parameter() { OutBoundUrl.Of<OptionalExampleController>(c => c.NullableInt(24)) .ShouldMapToUrl("/optional/nullableint/24"); } [Test] public void should_be_able_to_generate_url_with_optional_nullable_int_action_parameter_with_null() { OutBoundUrl.Of<OptionalExampleController>(c => c.NullableInt(null)) .ShouldMapToUrl("/optional/nullableint"); } [Test] public void should_be_able_to_generate_url_with_optional_string_action_parameter() { OutBoundUrl.Of<OptionalExampleController>(c => c.String("foo")) .ShouldMapToUrl("/optional/string/foo"); } [Test] public void should_be_able_to_generate_url_with_optional_string_action_parameter_with_empty_string() { OutBoundUrl.Of<OptionalExampleController>(c => c.String("")) .ShouldMapToUrl("/optional/string"); } [Test] public void should_be_able_to_generate_url_with_optional_string_action_parameter_with_null() { OutBoundUrl.Of<OptionalExampleController>(c => c.String(null)) .ShouldMapToUrl("/optional/string"); } [Test] public void should_match_datetime() { "~/funky/DateTime/2009-1-1".Route().ShouldMapTo<FunkyController>(x => x.DateTime(new DateTime(2009, 1, 1))); } [Test] public void should_match_nullabledatetime() { "~/funky/NullableDateTime/2009-1-1".Route().ShouldMapTo<FunkyController>(x => x.NullableDateTime(new DateTime(2009, 1, 1))); } [Test] public void should_match_method_with_different_name_than_action() { "~/funky/ActionName".Route().ShouldMapTo<FunkyController>(x => x.MethodNameDoesntMatch()); } [Test] public void should_be_able_to_match_optional_parameter_against_a_lambda_with_a_nullable_missing_expected_value() { "~/optional/nullableint".Route() .ShouldMapTo<OptionalExampleController>(x => x.NullableInt(null)); } [Test] public void should_be_able_to_match_optional_parameter_with_a_slash_against_a_lambda_with_a_nullable_missing_expected_value() { "~/optional/nullableint/".Route() .ShouldMapTo<OptionalExampleController>(x => x.NullableInt(null)); } [Test] public void should_be_able_to_match_optional_parameter_against_a_lambda_with_a_nullable_correct_expected_value() { "~/optional/nullableint/3".Route() .ShouldMapTo<OptionalExampleController>(x => x.NullableInt(3)); } [Test, ExpectedException(typeof(AssertionException))] public void should_throw_with_match_optional_parameter_against_a_lambda_with_a_nullable_incorrect_expected_value() { "~/optional/nullableint/5".Route() .ShouldMapTo<OptionalExampleController>(x => x.NullableInt(3)); } [Test, ExpectedException(typeof(AssertionException))] public void should_throw_with_optional_string_parameter_against_a_lambda_with_an_actual_expected_value() { "~/optional/string".Route() .ShouldMapTo<OptionalExampleController>(x => x.String("charlie")); } [Test] public void should_be_able_to_match_optional_string_parameter_against_a_lambda_with_a_nullable_missing_expected_value() { "~/optional/string".Route() .ShouldMapTo<OptionalExampleController>(x => x.String(null)); } [Test] public void should_be_able_to_match_optional_string_parameter_with_a_slash_against_a_lambda_with_a_nullable_missing_expected_value() { "~/optional/string/".Route() .ShouldMapTo<OptionalExampleController>(x => x.String(null)); } [Test] public void should_be_able_to_match_optional_string_parameter_against_a_lambda_with_a_nullable_correct_expected_value() { "~/optional/string/foo".Route() .ShouldMapTo<OptionalExampleController>(x => x.String("foo")); } [Test, ExpectedException(typeof(AssertionException))] public void should_throw_with_an_optional_string_parameter_against_a_lambda_with_a_nullable_incorrect_expected_value() { "~/optional/string/bar".Route() .ShouldMapTo<OptionalExampleController>(x => x.String("foo")); } [Test, ExpectedException(typeof(AssertionException), ExpectedMessage = "Value for parameter 'someParameter' did not match: expected 'foo' but was ''; no value found in the route context action parameter named 'someParameter' - does your matching route contain a token called 'someParameter'?")] public void should_provide_detailed_exception_message_when_detecting_a_parameter_name_that_doesnt_match() { "~/funky/parameterNameDoesntMatch/foo".Route().ShouldMapTo<FunkyController>(x => x.ParameterNameDoesntMatch("foo")); } [Test] public void ShouldMapToPage_detects_route_is_for_webforms() { RouteTable.Routes.Clear(); RouteTable.Routes.MapPageRoute("webform-page", "web/forms/route", "~/MyPage.aspx"); "~/web/forms/route".ShouldMapToPage("~/MyPage.aspx"); } [Test] public void ShouldMapToPage_Throws_when_WebForm_route_maps_to_wrong_page() { RouteTable.Routes.Clear(); RouteTable.Routes.MapPageRoute("webform-page", "web/forms/route", "~/MyPage.aspx"); Assert.Throws<MvcContrib.TestHelper.AssertionException>(() => "~/web/forms/route".ShouldMapToPage("~/Foo.aspx")); } [Test] public void ShouldMapToPage_throws_when_route_does_not_use_PageRouteHandler() { RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute("broken-route", "web/forms/route", new { controller = "Broken", action = "Index" }); Assert.Throws<MvcContrib.TestHelper.AssertionException>(() => "~/web/forms/route".ShouldMapToPage("~/MyPage.aspx")); } [Test] public void ShouldMapTo_DoesNotStripControllerFromMiddleOfName() { RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute("test", "foo", new { controller = "HasControllerInMiddleOfName", action = "index" }); "~/foo".ShouldMapTo<HasControllerInMiddleOfNameController>(x => x.Index()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using IdentityModel; using IdentityServer4.Events; using IdentityServer; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Host.Quickstart.Account { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IEventService _events; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _events = events; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public async Task<IActionResult> Challenge(string provider, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return await ProcessWindowsLoginAsync(returnUrl); } else { // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username)); await HttpContext.SignInAsync(user.SubjectId, user.Username, provider, localSignInProps, additionalLocalClaims.ToArray()); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl }); } } return Redirect(returnUrl); } private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, treating windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return Redirect(props.RedirectUri); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return Challenge(AccountOptions.WindowsAuthenticationSchemeName); } } private (TestUser user, string provider, string providerUserId, IEnumerable<Claim> claims) FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = _users.FindByExternalProvider(provider, providerUserId); return (user, provider, providerUserId, claims); } private TestUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList()); return user; } private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var id_token = externalResult.Properties.GetTokenValue("id_token"); if (id_token != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } } private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal struct AidContainer { internal static readonly AidContainer NullAidContainer = default(AidContainer); private enum Kind { None = 0, File, ExternAlias } private object _value; public AidContainer(FileRecord file) { _value = file; } } internal sealed class BSYMMGR { private HashSet<KAID> bsetGlobalAssemblies; // Assemblies in the global alias. // Special nullable members. public PropertySymbol propNubValue; public MethodSymbol methNubCtor; private readonly SymFactory _symFactory; private readonly MiscSymFactory _miscSymFactory; private readonly NamespaceSymbol _rootNS; // The "root" (unnamed) namespace. // Map from aids to INFILESYMs and EXTERNALIASSYMs private List<AidContainer> ssetAssembly; // Map from aids to MODULESYMs and OUTFILESYMs private NameManager m_nameTable; private SYMTBL tableGlobal; // The hash table for type arrays. private Dictionary<TypeArrayKey, TypeArray> tableTypeArrays; private const int LOG2_SYMTBL_INITIAL_BUCKET_CNT = 13; // Initial local size: 8192 buckets. private static readonly TypeArray s_taEmpty = new TypeArray(Array.Empty<CType>()); public BSYMMGR(NameManager nameMgr, TypeManager typeManager) { this.m_nameTable = nameMgr; this.tableGlobal = new SYMTBL(); _symFactory = new SymFactory(this.tableGlobal, this.m_nameTable); _miscSymFactory = new MiscSymFactory(this.tableGlobal); this.ssetAssembly = new List<AidContainer>(); InputFile infileUnres = new InputFile {isSource = false}; infileUnres.SetAssemblyID(KAID.kaidUnresolved); ssetAssembly.Add(new AidContainer(infileUnres)); this.bsetGlobalAssemblies = new HashSet<KAID>(); this.bsetGlobalAssemblies.Add(KAID.kaidThisAssembly); this.tableTypeArrays = new Dictionary<TypeArrayKey, TypeArray>(); _rootNS = _symFactory.CreateNamespace(m_nameTable.Add(""), null); GetNsAid(_rootNS, KAID.kaidGlobal); } public void Init() { /* tableTypeArrays.Init(&this->GetPageHeap(), this->getAlloc()); tableNameToSym.Init(this); nsToExtensionMethods.Init(this); // Some root symbols. Name* emptyName = m_nameTable->AddString(L""); rootNS = symFactory.CreateNamespace(emptyName, NULL); // Root namespace nsaGlobal = GetNsAid(rootNS, kaidGlobal); m_infileUnres.name = emptyName; m_infileUnres.isSource = false; m_infileUnres.idLocalAssembly = mdTokenNil; m_infileUnres.SetAssemblyID(kaidUnresolved, allocGlobal); size_t isym; isym = ssetAssembly.Add(&m_infileUnres); ASSERT(isym == 0); */ InitPreLoad(); } public NameManager GetNameManager() { return m_nameTable; } public SYMTBL GetSymbolTable() { return tableGlobal; } public static TypeArray EmptyTypeArray() { return s_taEmpty; } public AssemblyQualifiedNamespaceSymbol GetRootNsAid(KAID aid) { return GetNsAid(_rootNS, aid); } public NamespaceSymbol GetRootNS() { return _rootNS; } public KAID AidAlloc(InputFile sym) { ssetAssembly.Add(new AidContainer(sym)); return (KAID)(ssetAssembly.Count - 1 + KAID.kaidUnresolved); } public BetterType CompareTypes(TypeArray ta1, TypeArray ta2) { if (ta1 == ta2) { return BetterType.Same; } if (ta1.Size != ta2.Size) { // The one with more parameters is more specific. return ta1.Size > ta2.Size ? BetterType.Left : BetterType.Right; } BetterType nTot = BetterType.Neither; for (int i = 0; i < ta1.Size; i++) { CType type1 = ta1.Item(i); CType type2 = ta2.Item(i); BetterType nParam = BetterType.Neither; LAgain: if (type1.GetTypeKind() != type2.GetTypeKind()) { if (type1.IsTypeParameterType()) { nParam = BetterType.Right; } else if (type2.IsTypeParameterType()) { nParam = BetterType.Left; } } else { switch (type1.GetTypeKind()) { default: Debug.Assert(false, "Bad kind in CompareTypes"); break; case TypeKind.TK_TypeParameterType: case TypeKind.TK_ErrorType: break; case TypeKind.TK_PointerType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: type1 = type1.GetBaseOrParameterOrElementType(); type2 = type2.GetBaseOrParameterOrElementType(); goto LAgain; case TypeKind.TK_AggregateType: nParam = CompareTypes(type1.AsAggregateType().GetTypeArgsAll(), type2.AsAggregateType().GetTypeArgsAll()); break; } } if (nParam == BetterType.Right || nParam == BetterType.Left) { if (nTot == BetterType.Same || nTot == BetterType.Neither) { nTot = nParam; } else if (nParam != nTot) { return BetterType.Neither; } } } return nTot; } public SymFactory GetSymFactory() { return _symFactory; } public MiscSymFactory GetMiscSymFactory() { return _miscSymFactory; } //////////////////////////////////////////////////////////////////////////////// // Build the data structures needed to make FPreLoad fast. Make sure the // namespaces are created. Compute and sort hashes of the NamespaceSymbol * value and type // name (sans arity indicator). private void InitPreLoad() { for (int i = 0; i < (int)PredefinedType.PT_COUNT; ++i) { NamespaceSymbol ns = GetRootNS(); string name = PredefinedTypeFacts.GetName((PredefinedType)i); int start = 0; while (start < name.Length) { int iDot = name.IndexOf('.', start); if (iDot == -1) break; string sub = (iDot > start) ? name.Substring(start, iDot - start) : name.Substring(start); Name nm = this.GetNameManager().Add(sub); NamespaceSymbol sym = this.LookupGlobalSymCore(nm, ns, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol(); if (sym == null) { ns = _symFactory.CreateNamespace(nm, ns); } else { ns = sym; } start += sub.Length + 1; } } } public Symbol LookupGlobalSymCore(Name name, ParentSymbol parent, symbmask_t kindmask) { return tableGlobal.LookupSym(name, parent, kindmask); } public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask) { return tableGlobal.LookupSym(name, agg, mask); } public static Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask) { Debug.Assert(sym.parent == parent); sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); // Keep traversing the list of symbols with same name and parent. while (sym != null) { if ((kindmask & sym.mask()) > 0) return sym; sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); } return null; } public Name GetNameFromPtrs(object u1, object u2) { // Note: this won't produce the same names as the native logic if (u2 != null) { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}-{1:X}", u1.GetHashCode(), u2.GetHashCode())); } else { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}", u1.GetHashCode())); } } private AssemblyQualifiedNamespaceSymbol GetNsAid(NamespaceSymbol ns, KAID aid) { Name name = GetNameFromPtrs(aid, 0); Debug.Assert(name != null); AssemblyQualifiedNamespaceSymbol nsa = LookupGlobalSymCore(name, ns, symbmask_t.MASK_AssemblyQualifiedNamespaceSymbol).AsAssemblyQualifiedNamespaceSymbol(); if (nsa == null) { // Create a new one. nsa = _symFactory.CreateNamespaceAid(name, ns, aid); } Debug.Assert(nsa.GetNS() == ns); return nsa; } //////////////////////////////////////////////////////////////////////////////// // Allocate a type array; used to represent a parameter list. // We use a hash table to make sure that allocating the same type array twice // returns the same value. This does two things: // // 1) Save a lot of memory. // 2) Make it so parameter lists can be compared by a simple pointer comparison // 3) Allow us to associate a token with each signature for faster metadata emit private struct TypeArrayKey : IEquatable<TypeArrayKey> { private readonly CType[] _types; private readonly int _hashCode; public TypeArrayKey(CType[] types) { _types = types; _hashCode = 0; for (int i = 0, n = types.Length; i < n; i++) { _hashCode ^= types[i].GetHashCode(); } } public bool Equals(TypeArrayKey other) { if (other._types == _types) return true; if (other._types.Length != _types.Length) return false; if (other._hashCode != _hashCode) return false; for (int i = 0, n = _types.Length; i < n; i++) { if (!_types[i].Equals(other._types[i])) return false; } return true; } public override bool Equals(object obj) { if (obj is TypeArrayKey) { return this.Equals((TypeArrayKey)obj); } return false; } public override int GetHashCode() { return _hashCode; } } public TypeArray AllocParams(int ctype, CType[] prgtype) { if (ctype == 0) { return s_taEmpty; } Debug.Assert(ctype == prgtype.Length); return AllocParams(prgtype); } public TypeArray AllocParams(int ctype, TypeArray array, int offset) { CType[] types = array.ToArray(); CType[] newTypes = new CType[ctype]; Array.ConstrainedCopy(types, offset, newTypes, 0, ctype); return AllocParams(newTypes); } public TypeArray AllocParams(params CType[] types) { if (types == null || types.Length == 0) { return s_taEmpty; } TypeArrayKey key = new TypeArrayKey(types); TypeArray result; if (!tableTypeArrays.TryGetValue(key, out result)) { result = new TypeArray(types); tableTypeArrays.Add(key, result); } return result; } private TypeArray ConcatParams(CType[] prgtype1, CType[] prgtype2) { CType[] combined = new CType[prgtype1.Length + prgtype2.Length]; Array.Copy(prgtype1, 0, combined, 0, prgtype1.Length); Array.Copy(prgtype2, 0, combined, prgtype1.Length, prgtype2.Length); return AllocParams(combined); } public TypeArray ConcatParams(TypeArray pta1, TypeArray pta2) { return ConcatParams(pta1.ToArray(), pta2.ToArray()); } } }
using System; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Umbraco.Cms.Core.Dictionary; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.ContentEditing; using Umbraco.Cms.Core.Models.Editors; using Umbraco.Cms.Core.PropertyEditors; using Umbraco.Cms.Core.Serialization; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Web.Common.Filters; using Umbraco.Extensions; namespace Umbraco.Cms.Web.BackOffice.Controllers { /// <summary> /// An abstract base controller used for media/content/members to try to reduce code replication. /// </summary> [JsonDateTimeFormat] public abstract class ContentControllerBase : BackOfficeNotificationsController { private readonly ILogger<ContentControllerBase> _logger; private readonly IJsonSerializer _serializer; /// <summary> /// Initializes a new instance of the <see cref="ContentControllerBase"/> class. /// </summary> protected ContentControllerBase( ICultureDictionary cultureDictionary, ILoggerFactory loggerFactory, IShortStringHelper shortStringHelper, IEventMessagesFactory eventMessages, ILocalizedTextService localizedTextService, IJsonSerializer serializer) { CultureDictionary = cultureDictionary; LoggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger<ContentControllerBase>(); ShortStringHelper = shortStringHelper; EventMessages = eventMessages; LocalizedTextService = localizedTextService; _serializer = serializer; } /// <summary> /// Gets the <see cref="ICultureDictionary"/> /// </summary> protected ICultureDictionary CultureDictionary { get; } /// <summary> /// Gets the <see cref="ILoggerFactory"/> /// </summary> protected ILoggerFactory LoggerFactory { get; } /// <summary> /// Gets the <see cref="IShortStringHelper"/> /// </summary> protected IShortStringHelper ShortStringHelper { get; } /// <summary> /// Gets the <see cref="IEventMessagesFactory"/> /// </summary> protected IEventMessagesFactory EventMessages { get; } /// <summary> /// Gets the <see cref="ILocalizedTextService"/> /// </summary> protected ILocalizedTextService LocalizedTextService { get; } /// <summary> /// Handles if the content for the specified ID isn't found /// </summary> /// <param name="id">The content ID to find</param> /// <param name="throwException">Whether to throw an exception</param> /// <returns>The error response</returns> protected NotFoundObjectResult HandleContentNotFound(object id) { ModelState.AddModelError("id", $"content with id: {id} was not found"); NotFoundObjectResult errorResponse = NotFound(ModelState); return errorResponse; } /// <summary> /// Maps the dto property values to the persisted model /// </summary> internal void MapPropertyValuesForPersistence<TPersisted, TSaved>( TSaved contentItem, ContentPropertyCollectionDto dto, Func<TSaved, IProperty, object> getPropertyValue, Action<TSaved, IProperty, object> savePropertyValue, string culture) where TPersisted : IContentBase where TSaved : IContentSave<TPersisted> { // map the property values foreach (ContentPropertyDto propertyDto in dto.Properties) { // get the property editor if (propertyDto.PropertyEditor == null) { _logger.LogWarning("No property editor found for property {PropertyAlias}", propertyDto.Alias); continue; } // get the value editor // nothing to save/map if it is readonly IDataValueEditor valueEditor = propertyDto.PropertyEditor.GetValueEditor(); if (valueEditor.IsReadOnly) { continue; } // get the property IProperty property = contentItem.PersistedContent.Properties[propertyDto.Alias]; // prepare files, if any matching property and culture ContentPropertyFile[] files = contentItem.UploadedFiles .Where(x => x.PropertyAlias == propertyDto.Alias && x.Culture == propertyDto.Culture && x.Segment == propertyDto.Segment) .ToArray(); foreach (ContentPropertyFile file in files) { file.FileName = file.FileName.ToSafeFileName(ShortStringHelper); } // create the property data for the property editor var data = new ContentPropertyData(propertyDto.Value, propertyDto.DataType.Configuration) { ContentKey = contentItem.PersistedContent.Key, PropertyTypeKey = property.PropertyType.Key, Files = files }; // let the editor convert the value that was received, deal with files, etc object value = valueEditor.FromEditor(data, getPropertyValue(contentItem, property)); // set the value - tags are special TagsPropertyEditorAttribute tagAttribute = propertyDto.PropertyEditor.GetTagAttribute(); if (tagAttribute != null) { TagConfiguration tagConfiguration = ConfigurationEditor.ConfigurationAs<TagConfiguration>(propertyDto.DataType.Configuration); if (tagConfiguration.Delimiter == default) { tagConfiguration.Delimiter = tagAttribute.Delimiter; } var tagCulture = property.PropertyType.VariesByCulture() ? culture : null; property.SetTagsValue(_serializer, value, tagConfiguration, tagCulture); } else { savePropertyValue(contentItem, property, value); } } } /// <summary> /// A helper method to attempt to get the instance from the request storage if it can be found there, /// otherwise gets it from the callback specified /// </summary> /// <typeparam name="TPersisted"></typeparam> /// <param name="getFromService"></param> /// <returns></returns> /// <remarks> /// This is useful for when filters have already looked up a persisted entity and we don't want to have /// to look it up again. /// </remarks> protected TPersisted GetObjectFromRequest<TPersisted>(Func<TPersisted> getFromService) { // checks if the request contains the key and the item is not null, if that is the case, return it from the request, otherwise return // it from the callback return HttpContext.Items.ContainsKey(typeof(TPersisted).ToString()) && HttpContext.Items[typeof(TPersisted).ToString()] != null ? (TPersisted)HttpContext.Items[typeof(TPersisted).ToString()] : getFromService(); } /// <summary> /// Returns true if the action passed in means we need to create something new /// </summary> /// <param name="action">The content action</param> /// <returns>Returns true if this is a creating action</returns> internal static bool IsCreatingAction(ContentSaveAction action) => action.ToString().EndsWith("New"); /// <summary> /// Adds a cancelled message to the display /// </summary> /// <param name="display"></param> /// <param name="messageArea"></param> /// <param name="messageAlias"></param> /// <param name="messageParams"></param> protected void AddCancelMessage( INotificationModel display, string messageArea = "speechBubbles", string messageAlias ="operationCancelledText", string[] messageParams = null) { // if there's already a default event message, don't add our default one IEventMessagesFactory messages = EventMessages; if (messages != null && messages.GetOrDefault().GetAll().Any(x => x.IsDefaultEventMessage)) { return; } display.AddWarningNotification( LocalizedTextService.Localize("speechBubbles", "operationCancelledHeader"), LocalizedTextService.Localize(messageArea, messageAlias, messageParams)); } /// <summary> /// Adds a cancelled message to the display /// </summary> /// <param name="display"></param> /// <param name="header"></param> /// <param name="message"></param> /// <param name="headerArea"></param> /// <param name="headerAlias"></param> /// <param name="headerParams"></param> protected void AddCancelMessage(INotificationModel display, string message) { // if there's already a default event message, don't add our default one IEventMessagesFactory messages = EventMessages; if (messages?.GetOrDefault()?.GetAll().Any(x => x.IsDefaultEventMessage) == true) { return; } display.AddWarningNotification(LocalizedTextService.Localize("speechBubbles", "operationCancelledHeader"), message); } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="Certificate.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.Security { using System; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MSBuild.ExtensionPack.Security.Extended; internal enum CryptGetProvParamType { /// <summary> /// PP_ENUMALGS /// </summary> PP_ENUMALGS = 1, /// <summary> /// PP_ENUMCONTAINERS /// </summary> PP_ENUMCONTAINERS = 2, /// <summary> /// PP_IMPTYPE /// </summary> PP_IMPTYPE = 3, /// <summary> /// PP_NAME /// </summary> PP_NAME = 4, /// <summary> /// PP_VERSION /// </summary> PP_VERSION = 5, /// <summary> /// PP_CONTAINER /// </summary> PP_CONTAINER = 6, /// <summary> /// PP_CHANGE_PASSWORD /// </summary> PP_CHANGE_PASSWORD = 7, /// <summary> /// PP_KEYSET_SEC_DESCR /// </summary> PP_KEYSET_SEC_DESCR = 8, /// <summary> /// PP_CERTCHAIN /// </summary> PP_CERTCHAIN = 9, /// <summary> /// PP_KEY_TYPE_SUBTYPE /// </summary> PP_KEY_TYPE_SUBTYPE = 10, /// <summary> /// PP_PROVTYPE /// </summary> PP_PROVTYPE = 16, /// <summary> /// PP_KEYSTORAGE /// </summary> PP_KEYSTORAGE = 17, /// <summary> /// PP_APPLI_CERT /// </summary> PP_APPLI_CERT = 18, /// <summary> /// PP_SYM_KEYSIZE /// </summary> PP_SYM_KEYSIZE = 19, /// <summary> /// PP_SESSION_KEYSIZE /// </summary> PP_SESSION_KEYSIZE = 20, /// <summary> /// PP_UI_PROMPT /// </summary> PP_UI_PROMPT = 21, /// <summary> /// PP_ENUMALGS_EX /// </summary> PP_ENUMALGS_EX = 22, /// <summary> /// PP_ENUMMANDROOTS /// </summary> PP_ENUMMANDROOTS = 25, /// <summary> /// PP_ENUMELECTROOTS /// </summary> PP_ENUMELECTROOTS = 26, /// <summary> /// PP_KEYSET_TYPE /// </summary> PP_KEYSET_TYPE = 27, /// <summary> /// PP_ADMIN_PIN /// </summary> PP_ADMIN_PIN = 31, /// <summary> /// PP_KEYEXCHANGE_PIN /// </summary> PP_KEYEXCHANGE_PIN = 32, /// <summary> /// PP_SIGNATURE_PIN /// </summary> PP_SIGNATURE_PIN = 33, /// <summary> /// PP_SIG_KEYSIZE_INC /// </summary> PP_SIG_KEYSIZE_INC = 34, /// <summary> /// PP_KEYX_KEYSIZE_INC /// </summary> PP_KEYX_KEYSIZE_INC = 35, /// <summary> /// PP_UNIQUE_CONTAINER /// </summary> PP_UNIQUE_CONTAINER = 36, /// <summary> /// PP_SGC_INFO /// </summary> PP_SGC_INFO = 37, /// <summary> /// PP_USE_HARDWARE_RNG /// </summary> PP_USE_HARDWARE_RNG = 38, /// <summary> /// PP_KEYSPEC /// </summary> PP_KEYSPEC = 39, /// <summary> /// PP_ENUMEX_SIGNING_PROT /// </summary> PP_ENUMEX_SIGNING_PROT = 40, /// <summary> /// PP_CRYPT_COUNT_KEY_USE /// </summary> PP_CRYPT_COUNT_KEY_USE = 41, } /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Add</i> (<b>Required: </b>FileName <b>Optional: </b>MachineStore, CertPassword, Exportable, StoreName <b>Output: </b>Thumbprint, SubjectDName)</para> /// <para><i>GetBase64EncodedCertificate</i> (<b>Required: Thumbprint or SubjectDName</b> <b> Optional:</b> MachineStore, <b>Output:</b> Base64EncodedCertificate)</para> /// <para><i>GetExpiryDate</i> (<b>Required: </b> Thumbprint or SubjectDName<b> Optional: MachineStore, </b> <b>Output:</b> CertificateExpiryDate)</para> /// <para><i>GetInfo</i> (<b>Required: </b> Thumbprint or SubjectDName <b> Optional:</b> MachineStore, StoreName <b>Output:</b> CertInfo)</para> /// <para><i>Remove</i> (<b>Required: </b>Thumbprint or SubjectDName <b>Optional: </b>MachineStore, StoreName)</para> /// <para><i>SetUserRights</i> (<b>Required: </b> AccountName, Thumbprint or SubjectDName<b> Optional:</b> MachineStore, <b>Output:</b> )</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"> /// <!-- Add a certificate --> /// <MSBuild.ExtensionPack.Security.Certificate TaskAction="Add" FileName="C:\MyCertificate.cer" CertPassword="PASSW"> /// <Output TaskParameter="Thumbprint" PropertyName="TPrint"/> /// <Output TaskParameter="SubjectDName" PropertyName="SName"/> /// </MSBuild.ExtensionPack.Security.Certificate> /// <Message Text="Thumbprint: $(TPrint)"/> /// <Message Text="SubjectName: $(SName)"/> /// <!-- Get Certificate Information --> /// <MSBuild.ExtensionPack.Security.Certificate TaskAction="GetInfo" SubjectDName="$(SName)"> /// <Output TaskParameter="CertInfo" ItemName="ICertInfo" /> /// </MSBuild.ExtensionPack.Security.Certificate> /// <Message Text="SubjectName: %(ICertInfo.SubjectName)"/> /// <Message Text="SubjectNameOidValue: %(ICertInfo.SubjectNameOidValue)"/> /// <Message Text="SerialNumber: %(ICertInfo.SerialNumber)"/> /// <Message Text="Archived: %(ICertInfo.Archived)"/> /// <Message Text="NotBefore: %(ICertInfo.NotBefore)"/> /// <Message Text="NotAfter: %(ICertInfo.NotAfter)"/> /// <Message Text="PrivateKeyFileName: %(ICertInfo.PrivateKeyFileName)"/> /// <Message Text="FriendlyName: %(ICertInfo.FriendlyName)"/> /// <Message Text="HasPrivateKey: %(ICertInfo.HasPrivateKey)"/> /// <Message Text="Thumbprint: %(ICertInfo.Thumbprint)"/> /// <Message Text="Version: %(ICertInfo.Version)"/> /// <Message Text="PrivateKeyFileName: %(ICertInfo.PrivateKeyFileName)"/> /// <Message Text="SignatureAlgorithm: %(ICertInfo.SignatureAlgorithm)"/> /// <Message Text="IssuerName: %(ICertInfo.IssuerName)"/> /// <Message Text="PrivateKeyFileName: %(ICertInfo.PrivateKeyFileName)"/> /// <!-- Remove a certificate --> /// <MSBuild.ExtensionPack.Security.Certificate TaskAction="Remove" Thumbprint="$(TPrint)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class Certificate : BaseTask { private const string AddTaskAction = "Add"; private const string RemoveTaskAction = "Remove"; private const string SetUserRightsTaskAction = "SetUserRights"; private const string GetExpiryDateTaskAction = "GetExpiryDate"; private const string GetBase64EncodedCertificateTaskAction = "GetBase64EncodedCertificate"; private const string GetInfoTaskAction = "GetInfo"; private const string AccessRightsRead = "Read"; private const string AccessRightsReadAndExecute = "ReadAndExecute"; private const string AccessRightsWrite = "Write"; private const string AccessRightsFullControl = "FullControl"; private StoreName storeName = System.Security.Cryptography.X509Certificates.StoreName.My; /// <summary> /// Sets a value indicating whether to use the MachineStore. Default is false /// </summary> public bool MachineStore { get; set; } /// <summary> /// Sets the password for the pfx file from which the certificate is to be imported, defaults to blank /// </summary> public string CertPassword { get; set; } /// <summary> /// Sets a value indicating whether the certificate is exportable. /// </summary> public bool Exportable { get; set; } /// <summary> /// The distinguished subject name of the certificate /// </summary> [Output] public string SubjectDName { get; set; } /// <summary> /// Gets or sets the Base 64 Encoded string of the certificate /// </summary> [Output] public string Base64EncodedCertificate { get; set; } /// <summary> /// Gets the thumbprint. Used to uniquely identify certificate in further tasks /// The thumprint can be used in place of distinguished name to identify a certificate /// </summary> [Output] public string Thumbprint { get; set; } /// <summary> /// Gets the Distinguished Name for the certificate used to to uniquely identify certificate in further tasks. /// The distinguished name can be used in place of thumbprint to identify a certificate /// </summary> [Output] public string DistinguishedName { get; set; } /// <summary> /// Gets the Certificate Exprity Date. /// </summary> [Output] public string CertificateExpiryDate { get; set; } /// <summary> /// The name of user or group that needs to be given rights on the given certificate /// </summary> public string AccountName { get; set; } /// <summary> /// The access rights that need to be given. /// </summary> public string AccessRights { get; set; } /// <summary> /// Sets the name of the store. Defaults to My /// <para/> /// AddressBook: The store for other users<br /> /// AuthRoot: The store for third-party certificate authorities<br /> /// CertificateAuthority: The store for intermediate certificate authorities<br /> /// Disallowed: The store for revoked certificates<br /> /// My: The store for personal certificates<br /> /// Root: The store for trusted root certificate authorities <br /> /// TrustedPeople: The store for directly trusted people and resources<br /> /// TrustedPublisher: The store for directly trusted publishers<br /> /// </summary> public string StoreName { get => this.storeName.ToString(); set => this.storeName = (StoreName)Enum.Parse(typeof(StoreName), value); } /// <summary> /// Sets the name of the file. /// </summary> [Output] public ITaskItem FileName { get; set; } /// <summary> /// Gets the item which contains the Certificate information. The following Metadata is populated: SubjectName, SignatureAlgorithm, SubjectNameOidValue, SerialNumber, Archived, NotAfter, NotBefore, FriendlyName, HasPrivateKey, Thumbprint, Version, PrivateKeyFileName, IssuerName /// </summary> [Output] public ITaskItem CertInfo { get; protected set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } switch (this.TaskAction) { case AddTaskAction: this.Add(); break; case RemoveTaskAction: this.Remove(); break; case SetUserRightsTaskAction: this.SetUserAccessRights(); break; case GetExpiryDateTaskAction: this.GetCertificateExpiryDate(); break; case GetBase64EncodedCertificateTaskAction: this.GetCertificateAsBase64String(); break; case GetInfoTaskAction: this.GetInfo(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } /// <summary> /// Extracts a certificate from the certificate Distinguished Name /// </summary> /// <param name="distinguishedName">The distinguished name of the certificate</param> /// <param name="certificateStore">The certificate store to look for certificate for.</param> /// <returns>Returns the X509 certificate with the given DName</returns> private static X509Certificate2 GetCertificateFromDistinguishedName(string distinguishedName, X509Store certificateStore) { // Iterate through each certificate trying to find the first unexpired certificate return certificateStore.Certificates.Cast<X509Certificate2>().FirstOrDefault(certificate => string.Compare(certificate.Subject, distinguishedName, StringComparison.CurrentCultureIgnoreCase) == 0); } /// <summary> /// Extracts a certificate from the certificate Thumbprint Name /// </summary> /// <param name="thumbprint">The thumbprint of the certificate to look for</param> /// <param name="certificateStore">The certificate store to look for certificate for.</param> /// <returns>Returns the X509 certificate with the given DName</returns> private static X509Certificate2 GetCertificateFromThumbprint(string thumbprint, X509Store certificateStore) { // Iterate through each certificate trying to find the first unexpired certificate return certificateStore.Certificates.Cast<X509Certificate2>().FirstOrDefault(certificate => certificate.Thumbprint == thumbprint); } /// <summary> /// The method search for the given Key Name in the Application Data folders and return the folder location /// where the key file resides /// </summary> /// <param name="keyFileName">The name of the key file whose file location needs to be found</param> /// <returns>Returns the location of the given key file name</returns> private static string FindKeyLocation(string keyFileName) { // First search for the key in the Common (All User) Application Data directory string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); string rsaFolder = appDataFolder + @"\Microsoft\Crypto\RSA\MachineKeys"; if (Directory.GetFiles(rsaFolder, keyFileName).Length > 0) { return rsaFolder; } // If not found, search the key in the currently signed in user's Application Data directory appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); rsaFolder = appDataFolder + @"\Microsoft\Crypto\RSA\"; string[] directoryList = Directory.GetDirectories(rsaFolder); if (directoryList.Length > 0) { foreach (string directoryName in directoryList) { if (Directory.GetFiles(directoryName, keyFileName).Length != 0) { return directoryName; } } } return string.Empty; } private static string GetKeyFileName(X509Certificate cert) { IntPtr hprovider = IntPtr.Zero; // CSP handle bool freeProvider = false; // Do we need to free the CSP ? const uint AcquireFlags = 0; int keyNumber = 0; string keyFileName = null; // Determine whether there is private key information available for this certificate in the key store if (NativeMethods.CryptAcquireCertificatePrivateKey(cert.Handle, AcquireFlags, IntPtr.Zero, ref hprovider, ref keyNumber, ref freeProvider)) { IntPtr pbytes = IntPtr.Zero; // Native Memory for the CRYPT_KEY_PROV_INFO structure int cbbytes = 0; // Native Memory size try { if (NativeMethods.CryptGetProvParam(hprovider, CryptGetProvParamType.PP_UNIQUE_CONTAINER, IntPtr.Zero, ref cbbytes, 0)) { pbytes = Marshal.AllocHGlobal(cbbytes); if (NativeMethods.CryptGetProvParam(hprovider, CryptGetProvParamType.PP_UNIQUE_CONTAINER, pbytes, ref cbbytes, 0)) { byte[] keyFileBytes = new byte[cbbytes]; Marshal.Copy(pbytes, keyFileBytes, 0, cbbytes); // Copy eveything except tailing null byte keyFileName = System.Text.Encoding.ASCII.GetString(keyFileBytes, 0, keyFileBytes.Length - 1); } } } finally { if (freeProvider) { NativeMethods.CryptReleaseContext(hprovider, 0); } // Free our native memory if (pbytes != IntPtr.Zero) { Marshal.FreeHGlobal(pbytes); } } } return keyFileName ?? string.Empty; } private void GetInfo() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); X509Certificate2 cert = null; if (!string.IsNullOrEmpty(this.Thumbprint)) { var matches = store.Certificates.Find(X509FindType.FindByThumbprint, this.Thumbprint, false); if (matches.Count > 1) { this.Log.LogError("More than one certificate with Thumbprint '{0}' found in the {1} store.", this.Thumbprint, this.StoreName); return; } if (matches.Count == 0) { this.Log.LogError("No certificates with Thumbprint '{0}' found in the {1} store.", this.Thumbprint, this.StoreName); return; } cert = matches[0]; } else if (!string.IsNullOrEmpty(this.SubjectDName)) { var matches = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, this.SubjectDName, false); if (matches.Count > 1) { this.Log.LogError("More than one certificate with SubjectDName '{0}' found in the {1} store.", this.SubjectDName, this.StoreName); return; } if (matches.Count == 0) { this.Log.LogError("No certificates with SubjectDName '{0}' found in the {1} store.", this.SubjectDName, this.StoreName); return; } cert = matches[0]; } if (cert != null) { this.CertInfo = new TaskItem("CertInfo"); this.CertInfo.SetMetadata("SubjectName", cert.SubjectName.Name); this.CertInfo.SetMetadata("SubjectNameOidValue", cert.SubjectName.Oid.Value ?? string.Empty); this.CertInfo.SetMetadata("SerialNumber", cert.SerialNumber ?? string.Empty); this.CertInfo.SetMetadata("Archived", cert.Archived.ToString()); this.CertInfo.SetMetadata("NotBefore", cert.NotBefore.ToString(CultureInfo.CurrentCulture)); this.CertInfo.SetMetadata("FriendlyName", cert.FriendlyName); this.CertInfo.SetMetadata("HasPrivateKey", cert.HasPrivateKey.ToString()); this.CertInfo.SetMetadata("Thumbprint", cert.Thumbprint ?? string.Empty); this.CertInfo.SetMetadata("Version", cert.Version.ToString()); this.CertInfo.SetMetadata("SignatureAlgorithm", cert.SignatureAlgorithm.FriendlyName); this.CertInfo.SetMetadata("IssuerName", cert.IssuerName.Name); this.CertInfo.SetMetadata("NotAfter", cert.NotAfter.ToString(CultureInfo.CurrentCulture)); var privateKeyFileName = GetKeyFileName(cert); if (!string.IsNullOrEmpty(privateKeyFileName)) { // Adapted from the FindPrivateKey application. See http://msdn.microsoft.com/en-us/library/aa717039(v=VS.90).aspx. var keyFileDirectory = this.GetKeyFileDirectory(privateKeyFileName); if (!string.IsNullOrEmpty(privateKeyFileName) && !string.IsNullOrEmpty(keyFileDirectory)) { this.CertInfo.SetMetadata("PrivateKeyFileName", Path.Combine(keyFileDirectory, privateKeyFileName)); } } } store.Close(); } private void Remove() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); X509Certificate2 cert; if (!string.IsNullOrEmpty(this.Thumbprint)) { var matches = store.Certificates.Find(X509FindType.FindByThumbprint, this.Thumbprint, false); if (matches.Count > 1) { this.Log.LogError("More than one certificate with Thumbprint '{0}' found in the {1} store.", this.Thumbprint, this.StoreName); return; } if (matches.Count == 0) { this.Log.LogError("No certificates with Thumbprint '{0}' found in the {1} store.", this.Thumbprint, this.StoreName); return; } cert = matches[0]; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Removing Certificate: {0}", cert.Thumbprint)); store.Remove(cert); } else if (!string.IsNullOrEmpty(this.SubjectDName)) { var matches = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, this.SubjectDName, false); if (matches.Count > 1) { this.Log.LogError("More than one certificate with SubjectDName '{0}' found in the {1} store.", this.SubjectDName, this.StoreName); return; } if (matches.Count == 0) { this.Log.LogError("No certificates with SubjectDName '{0}' found in the {1} store.", this.SubjectDName, this.StoreName); return; } cert = matches[0]; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Removing Certificate: {0}", cert.SubjectName)); store.Remove(cert); } store.Close(); } private void Add() { if (this.FileName == null) { this.Log.LogError("FileName not provided"); return; } if (System.IO.File.Exists(this.FileName.GetMetadata("FullPath")) == false) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "FileName not found: {0}", this.FileName.GetMetadata("FullPath"))); return; } X509Certificate2 cert = new X509Certificate2(); X509KeyStorageFlags keyflags = this.MachineStore ? X509KeyStorageFlags.MachineKeySet : X509KeyStorageFlags.DefaultKeySet; if (this.Exportable) { keyflags |= X509KeyStorageFlags.Exportable; } keyflags |= X509KeyStorageFlags.PersistKeySet; cert.Import(this.FileName.GetMetadata("FullPath"), this.CertPassword, keyflags); StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding Certificate: {0} to Store: {1}", this.FileName.GetMetadata("FullPath"), this.StoreName)); X509Store store = this.GetStore(locationFlag); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite); store.Add(cert); store.Close(); this.Thumbprint = cert.Thumbprint; this.SubjectDName = cert.SubjectName.Name; } private string GetKeyFileDirectory(string keyFileName) { // Look up All User profile from environment variable string allUserProfile = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // set up searching directory string machineKeyDir = allUserProfile + "\\Microsoft\\Crypto\\RSA\\MachineKeys"; // Seach the key file string[] fs = System.IO.Directory.GetFiles(machineKeyDir, keyFileName); // If found if (fs.Length > 0) { return machineKeyDir; } // Next try current user profile string currentUserProfile = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // seach all sub directory string userKeyDir = currentUserProfile + "\\Microsoft\\Crypto\\RSA\\"; fs = System.IO.Directory.GetDirectories(userKeyDir); if (fs.Length > 0) { // for each sub directory foreach (string keyDir in fs) { fs = System.IO.Directory.GetFiles(keyDir, keyFileName); if (fs.Length == 0) { continue; } return keyDir; } } this.Log.LogError("Unable to locate private key file directory"); return string.Empty; } /// <summary> /// Retrieves the Expiry Date of the Certificate /// </summary> private void GetCertificateExpiryDate() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); X509Certificate2 certificate = null; try { store.Open(OpenFlags.ReadOnly); if (string.IsNullOrEmpty(this.Thumbprint) == false) { certificate = GetCertificateFromThumbprint(this.Thumbprint, store); } else if (string.IsNullOrEmpty(this.DistinguishedName) == false) { certificate = GetCertificateFromDistinguishedName(this.DistinguishedName, store); } if (certificate == null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Error fetching expiry date. Could not find the certificate in the certificate store")); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Returning Expiry Date of Certificate: {0}", certificate.Thumbprint)); this.CertificateExpiryDate = certificate.NotAfter.ToString("s", CultureInfo.CurrentCulture); } } finally { store.Close(); } } /// <summary> /// Retrieves the Expiry Date of the Certificate /// </summary> private void GetCertificateAsBase64String() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); X509Certificate2 certificate = null; try { store.Open(OpenFlags.ReadOnly); if (string.IsNullOrEmpty(this.Thumbprint) == false) { certificate = GetCertificateFromThumbprint(this.Thumbprint, store); } else if (string.IsNullOrEmpty(this.DistinguishedName) == false) { certificate = GetCertificateFromDistinguishedName(this.DistinguishedName, store); } if (certificate == null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Error fetching base 64 encoded certificate string. Could not find the certificate in the certificate store")); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Returning Expiry Date of Certificate: {0}", certificate.Thumbprint)); this.Base64EncodedCertificate = Convert.ToBase64String(certificate.RawData); } } finally { store.Close(); } } private X509Store GetStore(StoreLocation locationFlag) { X509Store store = new X509Store(this.storeName, locationFlag); this.Log.LogMessage(MessageImportance.Low, "Opening store {0} at location {1}.", this.StoreName, locationFlag); return store; } /// <summary> /// Set the given user access rights on the given certificate to the given user /// </summary> private void SetUserAccessRights() { StoreLocation locationFlag = this.MachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; X509Store store = this.GetStore(locationFlag); X509Certificate2 certificate = null; try { store.Open(OpenFlags.ReadOnly); if (string.IsNullOrEmpty(this.Thumbprint) == false) { certificate = GetCertificateFromThumbprint(this.Thumbprint, store); } else if (string.IsNullOrEmpty(this.DistinguishedName) == false) { certificate = GetCertificateFromDistinguishedName(this.DistinguishedName, store); } if (certificate == null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Error in setting user rights on certificate. Could not find the certificate in the certificate store")); } else { RSACryptoServiceProvider rsa = certificate.PrivateKey as RSACryptoServiceProvider; FileSystemRights fileSystemAccessRights = FileSystemRights.ReadAndExecute; if (rsa != null) { switch (this.AccessRights) { case AccessRightsRead: fileSystemAccessRights = FileSystemRights.Read; break; case AccessRightsReadAndExecute: fileSystemAccessRights = FileSystemRights.ReadAndExecute; break; case AccessRightsWrite: fileSystemAccessRights = FileSystemRights.Write; break; case AccessRightsFullControl: fileSystemAccessRights = FileSystemRights.FullControl; break; } string keyfilepath = FindKeyLocation(rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileInfo file = new FileInfo(keyfilepath + "\\" + rsa.CspKeyContainerInfo.UniqueKeyContainerName); FileSecurity fs = file.GetAccessControl(); NTAccount account = new NTAccount(this.AccountName); fs.AddAccessRule(new FileSystemAccessRule(account, fileSystemAccessRights, AccessControlType.Allow)); file.SetAccessControl(fs); } } } finally { store.Close(); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Jint.Native.Object; using Jint.Parser; using Jint.Parser.Ast; using Jint.Runtime; namespace Jint.Native.Json { public class JsonParser { private readonly Engine _engine; public JsonParser(Engine engine) { _engine = engine; } private Extra _extra; private int _index; // position in the stream private int _length; // length of the stream private int _lineNumber; private int _lineStart; private Location _location; private Token _lookahead; private string _source; private State _state; private static bool IsDecimalDigit(char ch) { return (ch >= '0' && ch <= '9'); } private static bool IsHexDigit(char ch) { return ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F' ; } private static bool IsOctalDigit(char ch) { return ch >= '0' && ch <= '7'; } private static bool IsWhiteSpace(char ch) { return (ch == ' ') || (ch == '\t') || (ch == '\n') || (ch == '\r'); } private static bool IsLineTerminator(char ch) { return (ch == 10) || (ch == 13) || (ch == 0x2028) || (ch == 0x2029); } private static bool IsNullChar(char ch) { return ch == 'n' || ch == 'u' || ch == 'l' || ch == 'l' ; } private static bool IsTrueOrFalseChar(char ch) { return ch == 't' || ch == 'r' || ch == 'u' || ch == 'e' || ch == 'f' || ch == 'a' || ch == 'l' || ch == 's' ; } private char ScanHexEscape(char prefix) { int code = char.MinValue; int len = (prefix == 'u') ? 4 : 2; for (int i = 0; i < len; ++i) { if (_index < _length && IsHexDigit(_source.CharCodeAt(_index))) { char ch = _source.CharCodeAt(_index++); code = code * 16 + "0123456789abcdef".IndexOf(ch.ToString(), StringComparison.OrdinalIgnoreCase); } else { throw new JavaScriptException(_engine.SyntaxError, string.Format("Expected hexadecimal digit:{0}", _source)); } } return (char)code; } private void SkipWhiteSpace() { while (_index < _length) { char ch = _source.CharCodeAt(_index); if (IsWhiteSpace(ch)) { ++_index; } else { break; } } } private Token ScanPunctuator() { int start = _index; char code = _source.CharCodeAt(_index); switch ((int) code) { // Check for most common single-character punctuators. case 46: // . dot case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++_index; return new Token { Type = Tokens.Punctuator, Value = code.ToString(), LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] {start, _index} }; } throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, code)); } private Token ScanNumericLiteral() { char ch = _source.CharCodeAt(_index); int start = _index; string number = ""; // Number start with a - if (ch == '-') { number += _source.CharCodeAt(_index++).ToString(); ch = _source.CharCodeAt(_index); } if (ch != '.') { number += _source.CharCodeAt(_index++).ToString(); ch = _source.CharCodeAt(_index); // Hex number starts with '0x'. // Octal number starts with '0'. if (number == "0") { // decimal number starts with '0' such as '09' is illegal. if (ch > 0 && IsDecimalDigit(ch)) { throw new Exception(Messages.UnexpectedToken); } } while (IsDecimalDigit(_source.CharCodeAt(_index))) { number += _source.CharCodeAt(_index++).ToString(); } ch = _source.CharCodeAt(_index); } if (ch == '.') { number += _source.CharCodeAt(_index++).ToString(); while (IsDecimalDigit(_source.CharCodeAt(_index))) { number += _source.CharCodeAt(_index++).ToString(); } ch = _source.CharCodeAt(_index); } if (ch == 'e' || ch == 'E') { number += _source.CharCodeAt(_index++).ToString(); ch = _source.CharCodeAt(_index); if (ch == '+' || ch == '-') { number += _source.CharCodeAt(_index++).ToString(); } if (IsDecimalDigit(_source.CharCodeAt(_index))) { while (IsDecimalDigit(_source.CharCodeAt(_index))) { number += _source.CharCodeAt(_index++).ToString(); } } else { throw new Exception(Messages.UnexpectedToken); } } return new Token { Type = Tokens.Number, Value = Double.Parse(number, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture), LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] {start, _index} }; } private Token ScanBooleanLiteral() { int start = _index; string s = ""; while (IsTrueOrFalseChar(_source.CharCodeAt(_index))) { s += _source.CharCodeAt(_index++).ToString(); } if (s == "true" || s == "false") { return new Token { Type = Tokens.BooleanLiteral, Value = s == "true", LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] { start, _index } }; } else { throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, s)); } } private Token ScanNullLiteral() { int start = _index; string s = ""; while (IsNullChar(_source.CharCodeAt(_index))) { s += _source.CharCodeAt(_index++).ToString(); } if (s == Null.Text) { return new Token { Type = Tokens.NullLiteral, Value = Null.Instance, LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] { start, _index } }; } else { throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, s)); } } private Token ScanStringLiteral() { var sb = new System.Text.StringBuilder(); char quote = _source.CharCodeAt(_index); int start = _index; ++_index; while (_index < _length) { char ch = _source.CharCodeAt(_index++); if (ch == quote) { quote = char.MinValue; break; } if (ch <= 31) { throw new JavaScriptException(_engine.SyntaxError, string.Format("Invalid character '{0}', position:{1}, string:{2}", ch, _index, _source)); } if (ch == '\\') { ch = _source.CharCodeAt(_index++); if (ch > 0 || !IsLineTerminator(ch)) { switch (ch) { case 'n': sb.Append('\n'); break; case 'r': sb.Append('\r'); break; case 't': sb.Append('\t'); break; case 'u': case 'x': int restore = _index; char unescaped = ScanHexEscape(ch); if (unescaped > 0) { sb.Append(unescaped.ToString()); } else { _index = restore; sb.Append(ch.ToString()); } break; case 'b': sb.Append("\b"); break; case 'f': sb.Append("\f"); break; case 'v': sb.Append("\x0B"); break; default: if (IsOctalDigit(ch)) { int code = "01234567".IndexOf(ch); if (_index < _length && IsOctalDigit(_source.CharCodeAt(_index))) { code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++)); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ("0123".IndexOf(ch) >= 0 && _index < _length && IsOctalDigit(_source.CharCodeAt(_index))) { code = code * 8 + "01234567".IndexOf(_source.CharCodeAt(_index++)); } } sb.Append(((char)code).ToString()); } else { sb.Append(ch.ToString()); } break; } } else { ++_lineNumber; if (ch == '\r' && _source.CharCodeAt(_index) == '\n') { ++_index; } } } else if (IsLineTerminator(ch)) { break; } else { sb.Append(ch.ToString()); } } if (quote != 0) { throw new JavaScriptException(_engine.SyntaxError, string.Format(Messages.UnexpectedToken, _source)); } return new Token { Type = Tokens.String, Value = sb.ToString(), LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] {start, _index} }; } private Token Advance() { SkipWhiteSpace(); if (_index >= _length) { return new Token { Type = Tokens.EOF, LineNumber = _lineNumber, LineStart = _lineStart, Range = new[] {_index, _index} }; } char ch = _source.CharCodeAt(_index); // Very common: ( and ) and ; if (ch == 40 || ch == 41 || ch == 58) { return ScanPunctuator(); } // String literal starts with double quote (#34). // Single quote (#39) are not allowed in JSON. if (ch == 34) { return ScanStringLiteral(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch == 46) { if (IsDecimalDigit(_source.CharCodeAt(_index + 1))) { return ScanNumericLiteral(); } return ScanPunctuator(); } if (ch == '-') // Negative Number { if (IsDecimalDigit(_source.CharCodeAt(_index + 1))) { return ScanNumericLiteral(); } return ScanPunctuator(); } if (IsDecimalDigit(ch)) { return ScanNumericLiteral(); } if (ch == 't' || ch == 'f') { return ScanBooleanLiteral(); } if (ch == 'n') { return ScanNullLiteral(); } return ScanPunctuator(); } private Token CollectToken() { _location = new Location { Start = new Position { Line = _lineNumber, Column = _index - _lineStart } }; Token token = Advance(); _location.End = new Position { Line = _lineNumber, Column = _index - _lineStart }; if (token.Type != Tokens.EOF) { var range = new[] {token.Range[0], token.Range[1]}; string value = _source.Slice(token.Range[0], token.Range[1]); _extra.Tokens.Add(new Token { Type = token.Type, Value = value, Range = range, }); } return token; } private Token Lex() { Token token = _lookahead; _index = token.Range[1]; _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0; _lineStart = token.LineStart; _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance(); _index = token.Range[1]; _lineNumber = token.LineNumber.HasValue ? token.LineNumber.Value : 0; _lineStart = token.LineStart; return token; } private void Peek() { int pos = _index; int line = _lineNumber; int start = _lineStart; _lookahead = (_extra.Tokens != null) ? CollectToken() : Advance(); _index = pos; _lineNumber = line; _lineStart = start; } private void MarkStart() { if (_extra.Loc.HasValue) { _state.MarkerStack.Push(_index - _lineStart); _state.MarkerStack.Push(_lineNumber); } if (_extra.Range != null) { _state.MarkerStack.Push(_index); } } private T MarkEnd<T>(T node) where T : SyntaxNode { if (_extra.Range != null) { node.Range = new[] {_state.MarkerStack.Pop(), _index}; } if (_extra.Loc.HasValue) { node.Location = new Location { Start = new Position { Line = _state.MarkerStack.Pop(), Column = _state.MarkerStack.Pop() }, End = new Position { Line = _lineNumber, Column = _index - _lineStart } }; PostProcess(node); } return node; } public T MarkEndIf<T>(T node) where T : SyntaxNode { if (node.Range != null || node.Location != null) { if (_extra.Loc.HasValue) { _state.MarkerStack.Pop(); _state.MarkerStack.Pop(); } if (_extra.Range != null) { _state.MarkerStack.Pop(); } } else { MarkEnd(node); } return node; } public SyntaxNode PostProcess(SyntaxNode node) { if (_extra.Source != null) { node.Location.Source = _extra.Source; } return node; } public ObjectInstance CreateArrayInstance(IEnumerable<JsValue> values) { var jsArray = _engine.Array.Construct(Arguments.Empty); _engine.Array.PrototypeObject.Push(jsArray, values.ToArray()); return jsArray; } // Throw an exception private void ThrowError(Token token, string messageFormat, params object[] arguments) { ParserException exception; string msg = System.String.Format(messageFormat, arguments); if (token.LineNumber.HasValue) { exception = new ParserException("Line " + token.LineNumber + ": " + msg) { Index = token.Range[0], LineNumber = token.LineNumber.Value, Column = token.Range[0] - _lineStart + 1 }; } else { exception = new ParserException("Line " + _lineNumber + ": " + msg) { Index = _index, LineNumber = _lineNumber, Column = _index - _lineStart + 1 }; } exception.Description = msg; throw exception; } // Throw an exception because of the token. private void ThrowUnexpected(Token token) { if (token.Type == Tokens.EOF) { ThrowError(token, Messages.UnexpectedEOS); } if (token.Type == Tokens.Number) { ThrowError(token, Messages.UnexpectedNumber); } if (token.Type == Tokens.String) { ThrowError(token, Messages.UnexpectedString); } // BooleanLiteral, NullLiteral, or Punctuator. ThrowError(token, Messages.UnexpectedToken, token.Value as string); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. private void Expect(string value) { Token token = Lex(); if (token.Type != Tokens.Punctuator || !value.Equals(token.Value)) { ThrowUnexpected(token); } } // Return true if the next token matches the specified punctuator. private bool Match(string value) { return _lookahead.Type == Tokens.Punctuator && value.Equals(_lookahead.Value); } private ObjectInstance ParseJsonArray() { var elements = new List<JsValue>(); Expect("["); while (!Match("]")) { if (Match(",")) { Lex(); elements.Add(Null.Instance); } else { elements.Add(ParseJsonValue()); if (!Match("]")) { Expect(","); } } } Expect("]"); return CreateArrayInstance(elements); } public ObjectInstance ParseJsonObject() { Expect("{"); var obj = _engine.Object.Construct(Arguments.Empty); while (!Match("}")) { Tokens type = _lookahead.Type; if (type != Tokens.String) { ThrowUnexpected(Lex()); } var name = Lex().Value.ToString(); if (PropertyNameContainsInvalidChar0To31(name)) { throw new JavaScriptException(_engine.SyntaxError, string.Format("Invalid character in property name '{0}'", name)); } Expect(":"); var value = ParseJsonValue(); obj.FastAddProperty(name, value, true, true, true); if (!Match("}")) { Expect(","); } } Expect("}"); return obj; } private bool PropertyNameContainsInvalidChar0To31(string s) { const int max = 31; for (var i = 0; i < s.Length; i++) { var val = (int)s[i]; if (val <= max) return true; } return false; } /// <summary> /// Optimization. /// By calling Lex().Value for each type, we parse the token twice. /// It was already parsed by the peek() method. /// _lookahead.Value already contain the value. /// </summary> /// <returns></returns> private JsValue ParseJsonValue() { Tokens type = _lookahead.Type; MarkStart(); switch (type) { case Tokens.NullLiteral: var v = Lex().Value; return Null.Instance; case Tokens.BooleanLiteral: return new JsValue((bool)Lex().Value); case Tokens.String: return new JsValue((string)Lex().Value); case Tokens.Number: return new JsValue((double)Lex().Value); } if (Match("[")) { return ParseJsonArray(); } if (Match("{")) { return ParseJsonObject(); } ThrowUnexpected(Lex()); // can't be reached return Null.Instance; } public JsValue Parse(string code) { return Parse(code, null); } public JsValue Parse(string code, ParserOptions options) { _source = code; _index = 0; _lineNumber = (_source.Length > 0) ? 1 : 0; _lineStart = 0; _length = _source.Length; _lookahead = null; _state = new State { AllowIn = true, LabelSet = new HashSet<string>(), InFunctionBody = false, InIteration = false, InSwitch = false, LastCommentStart = -1, MarkerStack = new Stack<int>() }; _extra = new Extra { Range = new int[0], Loc = 0, }; if (options != null) { if (!System.String.IsNullOrEmpty(options.Source)) { _extra.Source = options.Source; } if (options.Tokens) { _extra.Tokens = new List<Token>(); } } try { MarkStart(); Peek(); JsValue jsv = ParseJsonValue(); Peek(); Tokens type = _lookahead.Type; object value = _lookahead.Value; if(_lookahead.Type != Tokens.EOF) { throw new JavaScriptException(_engine.SyntaxError, string.Format("Unexpected {0} {1}", _lookahead.Type, _lookahead.Value)); } return jsv; } finally { _extra = new Extra(); } } private class Extra { public int? Loc; public int[] Range; public string Source; public List<Token> Tokens; } private enum Tokens { NullLiteral, BooleanLiteral, String, Number, Punctuator, EOF, }; class Token { public Tokens Type; public object Value; public int[] Range; public int? LineNumber; public int LineStart; } static class Messages { public const string UnexpectedToken = "Unexpected token {0}"; public const string UnexpectedNumber = "Unexpected number"; public const string UnexpectedString = "Unexpected string"; public const string UnexpectedEOS = "Unexpected end of input"; }; } }
// 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.Collections.Generic; using System.Collections.ObjectModel; using Gallio.Common.Markup; namespace Gallio.Common.Text { /// <summary> /// A diff set consists of a sequence of differences between a left document and a right document /// that indicate changed and unchanged regions. /// </summary> /// <remarks> /// <para> /// If the changes are applied in order to the left document, the right document will be /// reproduced. If the inverse changes are applied in order to the right document, the /// left document will be reproduced. /// </para> /// <para> /// This implementation is based on Myers' O((M + N) * D) time and O(M + N) space algorithm /// for computing the longest common subsequence from his paper /// "An O(ND) Difference Algorithm and Its Variations." /// (http://citeseer.ist.psu.edu/myers86ond.html) /// </para> /// <para> /// There were two other sources for inspiration although this implementation is not /// a direct port of either of them. /// <list type="bullet"> /// <item>The org.eclipse.compare.internal.LCS class in Eclipse (http://www.eclipse.org) from /// which we borrow the concept of limiting the number of differences to produce an approximate /// result with a reduced time bound for large data sets. Since the Eclipse implementation /// of the LCS follows Myers' algorithm pretty closely, it was also very useful as a point /// of comparison for finding bugs.</item> /// <item>Neil Fraser's "Diff Match and Patch" algorithm (http://code.google.com/p/google-diff-match-patch/). /// We borrow some ideas about semantic cleanup from here.</item> /// </list> /// </para> /// </remarks> [Serializable] public sealed class DiffSet : IMarkupStreamWritable { private const int SmallChangeThreshold = 5; private readonly IList<Diff> diffs; private readonly string leftDocument; private readonly string rightDocument; /// <summary> /// Constructs a diff set. /// </summary> /// <param name="diffs">The list of differences that indicate the changed and /// unchanged regions between the left and right documents. The diffs span /// the entire range of the left and right documents and are listed in document order.</param> /// <param name="leftDocument">The left document.</param> /// <param name="rightDocument">The right document.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="leftDocument"/>, /// <paramref name="rightDocument"/> or <paramref name="diffs"/> is null.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="diffs"/> does not /// completely cover the left and right documents or are not listed in the correct order.</exception> public DiffSet(IList<Diff> diffs, string leftDocument, string rightDocument) { if (diffs == null) throw new ArgumentNullException("diffs"); if (leftDocument == null) throw new ArgumentNullException("leftDocument"); if (rightDocument == null) throw new ArgumentNullException("rightDocument"); if (!ValidateDiffs(diffs, leftDocument.Length, rightDocument.Length)) throw new ArgumentException("The list of differences should cover the left and right documents in order.", "diffs"); this.diffs = diffs; this.rightDocument = rightDocument; this.leftDocument = leftDocument; } /// <summary> /// Gets the set of differences between a left document and a right document. /// </summary> /// <param name="leftDocument">The left document.</param> /// <param name="rightDocument">The right document.</param> /// <returns>The set of differences.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="leftDocument"/> or /// <paramref name="rightDocument"/> is null.</exception> public static DiffSet GetDiffSet(string leftDocument, string rightDocument) { return GetDiffSet(leftDocument, rightDocument, true, true); } internal static DiffSet GetDiffSet(string leftDocument, string rightDocument, bool optimize, bool boundRuntime) { if (leftDocument == null) throw new ArgumentNullException("leftDocument"); if (rightDocument == null) throw new ArgumentNullException("rightDocument"); var diffs = new List<Diff>(); if (optimize) FastDiff(diffs, new Substring(leftDocument), new Substring(rightDocument), boundRuntime); else SlowDiff(diffs, new Substring(leftDocument), new Substring(rightDocument), boundRuntime); CanonicalizeDiffs(diffs); return new DiffSet(diffs, leftDocument, rightDocument); } /// <summary> /// Gets the list of differences that indicate the changed and /// unchanged regions between the left and right documents. /// </summary> /// <remarks> /// <para> /// The diffs span the entire range of the left and right documents and are listed in document order. /// </para> /// </remarks> public IList<Diff> Diffs { get { return new ReadOnlyCollection<Diff>(diffs); } } /// <summary> /// Gets the left document. /// </summary> public string LeftDocument { get { return leftDocument; } } /// <summary> /// Gets the right document. /// </summary> public string RightDocument { get { return rightDocument; } } /// <summary> /// Returns true if the list of differences contains changed regions. /// </summary> public bool ContainsChanges { get { foreach (Diff diff in diffs) if (diff.Kind == DiffKind.Change) return true; return false; } } /// <summary> /// Returns true if the list of differences is empty which can only occur when /// both document being compared are empty. /// </summary> public bool IsEmpty { get { return diffs.Count == 0; } } /// <summary> /// Writes the diffs using the <see cref="DiffStyle.Interleaved" /> /// presentation style and no limits on the context length. /// </summary> /// <remarks> /// <para> /// For the purposes of determining additions and deletions, the left document /// is considered the original and the right document is the considered to be the /// one that was modified. Changes are annotated by markers: /// by <see cref="Marker.DiffAddition" />, <see cref="Marker.DiffDeletion" /> /// and <see cref="Marker.DiffChange" />. /// </para> /// </remarks> /// <param name="writer">The test log stream writer to receive the highlighted document.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref nameref="writer" /> if null.</exception> public void WriteTo(MarkupStreamWriter writer) { WriteTo(writer, DiffStyle.Interleaved, int.MaxValue); } /// <summary> /// Writes the diffs using the specified /// presentation style and no limits on the context length. /// </summary> /// <remarks> /// <para> /// Changes are annotated by markers: <see cref="Marker.DiffAddition" />, <see cref="Marker.DiffDeletion" /> /// and <see cref="Marker.DiffChange" />. /// </para> /// <para> /// If the style is <see cref="DiffStyle.Interleaved" /> then the left document /// is considered the original and the right document is the considered to be the /// one that was modified so deletions appear within the left and additions within the right. /// </para> /// <para> /// If the style is <see cref="DiffStyle.LeftOnly" /> or <see cref="DiffStyle.RightOnly" /> /// then only the deletion and changed markers are used. /// </para> /// </remarks> /// <param name="writer">The test log stream writer to receive the highlighted document.</param> /// <param name="style">The presentation style.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref nameref="writer" /> if null.</exception> public void WriteTo(MarkupStreamWriter writer, DiffStyle style) { WriteTo(writer, style, int.MaxValue); } /// <summary> /// Writes the diffs using the specified presentation style and max context length. /// </summary> /// <remarks> /// <para> /// Changes are annotated by markers: <see cref="Marker.DiffAddition" />, <see cref="Marker.DiffDeletion" /> /// and <see cref="Marker.DiffChange" />. /// </para> /// <para> /// If the style is <see cref="DiffStyle.Interleaved" /> then the left document /// is considered the original and the right document is the considered to be the /// one that was modified so deletions appear within the left and additions within the right. /// </para> /// <para> /// If the style is <see cref="DiffStyle.LeftOnly" /> or <see cref="DiffStyle.RightOnly" /> /// then only the deletion and changed markers are used. /// </para> /// </remarks> /// <param name="writer">The test log stream writer to receive the highlighted document.</param> /// <param name="style">The presentation style.</param> /// <param name="maxContextLength">The maximum number of characters of unchanged regions /// to display for context, or <see cref="int.MaxValue" /> for no limit. Extraneous context /// is split in two with an ellipsis inserted in between both halves.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref nameref="writer" /> if null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="maxContextLength"/> /// is negative.</exception> public void WriteTo(MarkupStreamWriter writer, DiffStyle style, int maxContextLength) { if (writer == null) throw new ArgumentNullException("writer"); if (maxContextLength < 0) throw new ArgumentOutOfRangeException("maxContextLength"); foreach (Diff diff in diffs) { if (diff.Kind == DiffKind.NoChange) { WriteContext(writer, new Substring(leftDocument, diff.LeftRange), maxContextLength); } else { if (diff.LeftRange.Length != 0) { switch (style) { case DiffStyle.Interleaved: using (writer.BeginMarker(Marker.DiffDeletion)) writer.Write(diff.LeftRange.SubstringOf(leftDocument)); break; case DiffStyle.LeftOnly: using (writer.BeginMarker(diff.RightRange.Length == 0 ? Marker.DiffDeletion : Marker.DiffChange)) writer.Write(diff.LeftRange.SubstringOf(leftDocument)); break; } } if (diff.RightRange.Length != 0) { switch (style) { case DiffStyle.Interleaved: using (writer.BeginMarker(Marker.DiffAddition)) writer.Write(diff.RightRange.SubstringOf(rightDocument)); break; case DiffStyle.RightOnly: using (writer.BeginMarker(diff.LeftRange.Length == 0 ? Marker.DiffDeletion : Marker.DiffChange)) writer.Write(diff.RightRange.SubstringOf(rightDocument)); break; } } } } } /// <summary> /// Simplifies the diff for presentation. /// </summary> /// <remarks> /// <para> /// This method applies a series of heuristics to make the diff easier to read /// but perhaps less optimal, including the following: /// <list type="bullet"> /// <item>Adjacent diffs of the same kind are combined.</item> /// <item>Small unchanged regions sandwiched between larger changed regions are /// converted to larger changed regions. This improves the case when only /// a few scattered characters coincidentally match between the two documents.</item> /// </list> /// </para> /// </remarks> /// <returns>Returns a simplified diff.</returns> public DiffSet Simplify() { if (diffs.Count <= 1) return this; var simplifiedDiffs = new List<Diff>(diffs); CanonicalizeDiffs(simplifiedDiffs); for (int i = 1; i < simplifiedDiffs.Count - 1; i++) { Diff middleDiff = simplifiedDiffs[i]; if (middleDiff.Kind == DiffKind.NoChange) { int middleLength = middleDiff.EffectiveLength; if (middleLength > SmallChangeThreshold) continue; // Note: Because the diffs have been canonicalized, we know that the adjacent // diffs must be Changes. Diff leftDiff = simplifiedDiffs[i - 1]; Diff rightDiff = simplifiedDiffs[i + 1]; if (middleLength <= leftDiff.EffectiveLength && middleLength <= rightDiff.EffectiveLength) { Diff simplifiedDiff = new Diff(DiffKind.Change, Range.Between(leftDiff.LeftRange.StartIndex, rightDiff.LeftRange.EndIndex), Range.Between(leftDiff.RightRange.StartIndex, rightDiff.RightRange.EndIndex)); simplifiedDiffs[i - 1] = simplifiedDiff; simplifiedDiffs.RemoveRange(i, 2); // Go back to the previous unchanged region, if there is one, and re-evaluate // whether it should be merged given that we just increased the length of its // successor. Otherwise we simply continue on to the next unchanged region. if (i > 2) i -= 3; else i -= 1; } } } return new DiffSet(simplifiedDiffs, leftDocument, rightDocument); } private static void WriteContext(MarkupStreamWriter writer, Substring context, int maxContextLength) { if (context.Length < maxContextLength) { writer.Write(context.ToString()); } else { int split = maxContextLength / 2; if (split > 0) { writer.Write(context.Extract(0, split).ToString()); writer.WriteEllipsis(); writer.Write(context.Extract(context.Length - split)); } } } private static bool ValidateDiffs(IEnumerable<Diff> diffs, int leftLength, int rightLength) { Range prevLeftRange = new Range(0, 0); Range prevRightRange = new Range(0, 0); foreach (Diff diff in diffs) { if (diff.LeftRange.StartIndex != prevLeftRange.EndIndex) return false; if (diff.RightRange.StartIndex != prevRightRange.EndIndex) return false; prevLeftRange = diff.LeftRange; prevRightRange = diff.RightRange; } return prevLeftRange.EndIndex == leftLength && prevRightRange.EndIndex == rightLength; } private static void FastDiff(IList<Diff> diffs, Substring left, Substring right, bool boundRuntime) { // If either document is empty, then the change covers the whole document. if (left.Length == 0 || right.Length == 0) { diffs.Add(new Diff(DiffKind.Change, left.Range, right.Range)); return; } // Reduce the problem size by identifying a common prefix and suffix, if any. int commonPrefixLength = left.FindCommonPrefixLength(right); if (commonPrefixLength != 0) { if (commonPrefixLength == left.Length && commonPrefixLength == right.Length) { diffs.Add(new Diff(DiffKind.NoChange, left.Range, right.Range)); return; } diffs.Add(new Diff(DiffKind.NoChange, new Range(left.Range.StartIndex, commonPrefixLength), new Range(right.Range.StartIndex, commonPrefixLength))); } int commonSuffixLength = left.Extract(commonPrefixLength).FindCommonSuffixLength(right.Extract(commonPrefixLength)); // Now work on the middle part. Substring leftMiddle = left.Extract(commonPrefixLength, left.Length - commonPrefixLength - commonSuffixLength); Substring rightMiddle = right.Extract(commonPrefixLength, right.Length - commonPrefixLength - commonSuffixLength); SlowDiff(diffs, leftMiddle, rightMiddle, boundRuntime); // Tack on the final diff for the common suffix, if any. if (commonSuffixLength != 0) { diffs.Add(new Diff(DiffKind.NoChange, new Range(leftMiddle.Range.EndIndex, commonSuffixLength), new Range(rightMiddle.Range.EndIndex, commonSuffixLength))); } } private static void SlowDiff(IList<Diff> diffs, Substring left, Substring right, bool boundRuntime) { DiffAlgorithm.PopulateDiffs(diffs, left, right, boundRuntime); } private static void CanonicalizeDiffs(IList<Diff> diffs) { for (int i = 0; i < diffs.Count; i++) { Diff curDiff = diffs[i]; if (curDiff.LeftRange.Length == 0 && curDiff.RightRange.Length == 0) { diffs.RemoveAt(i); } else if (i != 0) { Diff prevDiff = diffs[i - 1]; if (prevDiff.Kind == curDiff.Kind) { diffs.RemoveAt(i); i -= 1; diffs[i] = new Diff(prevDiff.Kind, prevDiff.LeftRange.ExtendWith(curDiff.LeftRange), prevDiff.RightRange.ExtendWith(curDiff.RightRange)); } } } } private sealed class DiffAlgorithm { // Ordinarily the worst case runtime is O((N + M) * D) which can be very large // as D approaches N + M. Here we attempt to limit the worst case to O(D ^ PowLimit) // when N * M is too big. private const double PowLimit = 1.5; // The value of N * M at which to start binding the runtime. // We want a value sufficiently high that we will get accurate diffs // for sequences that contain relatively a large number of adjacent differences // but not so big that it takes too long to run. // // Experimental results on completely different strings of identical size // with disjoint alphabets on Intel Core 2 Duo U7700, 1.33Ghz laptop. // // N and M Unbounded Bounded // 1000 169ms 16ms // 2000 615ms 40ms // 3000 1545ms 66ms // 4000 2481ms 91ms // 5000 4416ms 169ms // 6000 6189ms 210ms // 7000 7430ms 267ms // 8000 10337ms 293ms // 9000 13661ms 381ms // 10000 17579ms 464ms // // The Eclipse implementation uses a limit of 10,000,000 which in our chart would // mean applying to runtime bounded approximations at a problem size of about 3162. // Still rather slow and there are plenty of slower machines out there. // // So instead we bound the problem size to 2500 ^ 2 = 6,250,000 for now. private const long TooLong = 6250000; // The maximum number of non-diagonal edits (differences) to consider. private readonly int max; // Each of these represents a "V" vector from Myers' algorithm which allows signed integer indices in // a range -MAX .. MAX. We must add the offset "max" to find the center of the vector. private readonly int[] leftVector; private readonly int[] rightVector; private readonly IList<Diff> diffs; private int commonSeqLeftStartIndex, commonSeqRightStartIndex, commonSeqLength; private DiffAlgorithm(IList<Diff> diffs, int leftStartIndex, int rightStartIndex, int max) { this.diffs = diffs; this.commonSeqLeftStartIndex = leftStartIndex; this.commonSeqRightStartIndex = rightStartIndex; this.max = max; int vectorLength = max * 2 + 1; leftVector = new int[vectorLength]; rightVector = new int[vectorLength]; } public static void PopulateDiffs(IList<Diff> diffs, Substring left, Substring right, bool boundRuntime) { int n = left.Length; int m = right.Length; int max = CeilNPlusMOverTwo(n, m); if (boundRuntime && ((long) n) * ((long) m) > TooLong) max = (int) Math.Pow(max, PowLimit - 1.0); DiffAlgorithm algorithm = new DiffAlgorithm(diffs, left.Range.StartIndex, right.Range.StartIndex, max); algorithm.ComputeLCS(left, right); algorithm.FlushDiffs(left.Range.EndIndex, right.Range.EndIndex); } private void EmitDiffsFromCommonSequence(int leftIndex, int rightIndex, int length) { if (length == 0) return; int commonSeqLeftEndIndex = commonSeqLeftStartIndex + commonSeqLength; int commonSeqRightEndIndex = commonSeqRightStartIndex + commonSeqLength; if (leftIndex == commonSeqLeftEndIndex && rightIndex == commonSeqRightEndIndex) { commonSeqLength += length; } else { if (commonSeqLength != 0) diffs.Add(new Diff(DiffKind.NoChange, new Range(commonSeqLeftStartIndex, commonSeqLength), new Range(commonSeqRightStartIndex, commonSeqLength))); diffs.Add(new Diff(DiffKind.Change, new Range(commonSeqLeftEndIndex, leftIndex - commonSeqLeftEndIndex), new Range(commonSeqRightEndIndex, rightIndex - commonSeqRightEndIndex))); commonSeqLeftStartIndex = leftIndex; commonSeqRightStartIndex = rightIndex; commonSeqLength = length; } } private void FlushDiffs(int leftEndIndex, int rightEndIndex) { int commonSeqLeftEndIndex = commonSeqLeftStartIndex + commonSeqLength; int commonSeqRightEndIndex = commonSeqRightStartIndex + commonSeqLength; if (commonSeqLength != 0) diffs.Add(new Diff(DiffKind.NoChange, new Range(commonSeqLeftStartIndex, commonSeqLength), new Range(commonSeqRightStartIndex, commonSeqLength))); if (leftEndIndex != commonSeqLeftEndIndex || rightEndIndex != commonSeqRightEndIndex) diffs.Add(new Diff(DiffKind.Change, new Range(commonSeqLeftEndIndex, leftEndIndex - commonSeqLeftEndIndex), new Range(commonSeqRightEndIndex, rightEndIndex - commonSeqRightEndIndex))); } // Determines the longest common subsequence between two sequences and populates the // list of diffs derived from the result as we go. Each recursive step identifies // a middle "snake" (a common sequence) then splits the problem until nothing remains. private void ComputeLCS(Substring left, Substring right) { int n = left.Length; int m = right.Length; if (n != 0 && m != 0) { int middleSnakeLeftStartIndex, middleSnakeRightStartIndex, middleSnakeLength; int ses = FindMiddleSnake(left, right, out middleSnakeLeftStartIndex, out middleSnakeRightStartIndex, out middleSnakeLength); if (ses > 1) { // If SES >= 2 then the edit script includes at least 2 differences, so we divide the problem. ComputeLCS( left.Extract(0, middleSnakeLeftStartIndex), right.Extract(0, middleSnakeRightStartIndex)); EmitDiffsFromCommonSequence( left.Range.StartIndex + middleSnakeLeftStartIndex, right.Range.StartIndex + middleSnakeRightStartIndex, middleSnakeLength); ComputeLCS( left.Extract(middleSnakeLeftStartIndex + middleSnakeLength), right.Extract(middleSnakeRightStartIndex + middleSnakeLength)); } else { // If SES = 1, then exactly one symbol needs to be added or deleted from either sequence. // If SES = 0, then both sequences are equal. if (ses != 0) { // The middle snake is the common part after the change so we just need to grab the // common part before the change. EmitDiffsFromCommonSequence( left.Range.StartIndex, right.Range.StartIndex, Math.Min(middleSnakeLeftStartIndex, middleSnakeRightStartIndex)); } EmitDiffsFromCommonSequence( left.Range.StartIndex + middleSnakeLeftStartIndex, right.Range.StartIndex + middleSnakeRightStartIndex, middleSnakeLength); } } } // Finds a middle "snake", which is a (possibly empty) sequence of diagonal edges in the edit // graph. Thus it directly represents a common sequence. // // In essence, this function searches D-paths forward and backward in the sequence until it // finds the middle snake. The middle snake informs us about a common sequence sandwiched // between two other sequences that may contain changes. By definition, the left and right // middle snakes must be of equal length. private int FindMiddleSnake(Substring left, Substring right, out int middleSnakeLeftStartIndex, out int middleSnakeRightStartIndex, out int middleSnakeLength) { int n = left.Length; int m = right.Length; int delta = n - m; bool isDeltaOdd = (delta & 1) != 0; leftVector[max + 1] = 0; rightVector[max - 1] = n; int end = Math.Min(CeilNPlusMOverTwo(n, m), max); for (int d = 0; d <= end; d++) { // Search forward D-paths. for (int k = -d; k <= d; k += 2) { // Find the end of the furthest reaching forward D-path in diagonal k. int x = k == -d || k != d && leftVector[max + k - 1] < leftVector[max + k + 1] ? leftVector[max + k + 1] : leftVector[max + k - 1] + 1; int origX = x; for (int y = x - k; x < n && y < m && left[x] == right[y]; ) { x += 1; y += 1; } leftVector[max + k] = x; // If the D-path is feasible and overlaps the furthest reaching reverse (D-1)-Path in diagonal k // then we have found the middle snake. if (isDeltaOdd && k >= delta - d + 1 && k <= delta + d - 1) { int u = rightVector[max + k - delta]; if (x >= u) { middleSnakeLeftStartIndex = origX; middleSnakeRightStartIndex = origX - k; middleSnakeLength = x - origX; return d * 2 - 1; } } } // Search reverse D-paths. for (int k = -d; k <= d; k += 2) { // Find the end of the furthest reaching reverse D-path in diagonal k + delta. int u = k == d || k != -d && rightVector[max + k - 1] < rightVector[max + k + 1] ? rightVector[max + k - 1] : rightVector[max + k + 1] - 1; int kPlusDelta = k + delta; int origU = u; int v; for (v = u - kPlusDelta; u > 0 && v > 0 && left[u - 1] == right[v - 1]; ) { u -= 1; v -= 1; } rightVector[max + k] = u; // If the D-path is feasible and overlaps the furthest reaching forward D-Path in diagonal k // then we have found the middle snake. if (!isDeltaOdd && kPlusDelta >= -d && kPlusDelta <= d) { int x = leftVector[max + kPlusDelta]; if (u <= x) { middleSnakeLeftStartIndex = u; middleSnakeRightStartIndex = v; middleSnakeLength = origU - u; return d * 2; } } } } // We have exceeded the maximum effort we are willing to expend finding a diff. // // So we artificially divide the problem by finding the snakes in the forward / reverse // direction that have the most progress toward (N, M) / (0, 0). These are the // ones that maximize x + y / minimize u + v. The snake we return will not actually // be the middle snake (since we haven't found it yet) but it will be good enough // to reduce the problem. // // These snakes all begin on the same diagonal as the others of equal // progress in the same direction. As there may be several of them, we need a way // to decide which one to pursue. // // The Eclipse LCS implementation chooses the median of these snakes with respect to k. // Intuitively this is the one that is nearer the direct line between (0, 0) and (N, M) // so it has a good chance of forming a path with more balanced changes between A and B // than the snakes that consist of significantly more changes to A than B or vice-versa. // Consequently the median of theses snakes should yield a pretty good approximation. -- Jeff. int bestProgress = 0; Dictionary<int, bool> bestKs = new Dictionary<int,bool>(); // with the forward direction indicated by value true for (int k = -end; k <= end; k += 2) { // Forward direction. int x = leftVector[max + k]; int y = x - k; if (x < n && y < m) { int progress = x + y; if (progress >= bestProgress) { if (progress > bestProgress) { bestProgress = progress; bestKs.Clear(); } bestKs[k] = true; } } // Reverse direction. int u = rightVector[max + k]; int v = u - k - delta; if (u >= 0 && v >= 0) { int progress = n + m - u - v; if (progress >= bestProgress) { if (progress > bestProgress) { bestProgress = progress; bestKs.Clear(); } bestKs[k] = false; } } } int[] sortedKs = new int[bestKs.Count]; bestKs.Keys.CopyTo(sortedKs, 0); Array.Sort(sortedKs); int medianK = sortedKs[sortedKs.Length / 2]; if (bestKs[medianK]) { int x = leftVector[max + medianK]; int y = x - medianK; middleSnakeLeftStartIndex = x; middleSnakeRightStartIndex = y; } else { int u = rightVector[max + medianK]; int v = u - medianK - delta; middleSnakeLeftStartIndex = u; middleSnakeRightStartIndex = v; } middleSnakeLength = 0; // We need to return the length of the shortest edit script but we don't actually know // what it is. Fortunately the caller does not care as long as it's greater than 2, which // it must be since d > end >= max > 2. return int.MaxValue; } private static int CeilNPlusMOverTwo(int n, int m) { return (n + m + 1) / 2; } } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using Aurora.Simulation.Base; using OpenSim.Services.Interfaces; using Aurora.Framework; using Aurora.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Services.CapsService { public class CapsService : ICapsService, IService { #region Declares /// <summary> /// A list of all clients and their Client Caps Handlers /// </summary> protected Dictionary<UUID, IClientCapsService> m_ClientCapsServices = new Dictionary<UUID, IClientCapsService>(); /// <summary> /// A list of all regions Caps Services /// </summary> protected Dictionary<ulong, IRegionCapsService> m_RegionCapsServices = new Dictionary<ulong, IRegionCapsService>(); protected IRegistryCore m_registry; public IRegistryCore Registry { get { return m_registry; } } protected IHttpServer m_server; public IHttpServer Server { get { return m_server; } } public string HostUri { get { return m_server.ServerURI; } } #endregion #region IService members public string Name { get { return GetType().Name; } } public void Initialize(IConfigSource config, IRegistryCore registry) { IConfig handlerConfig = config.Configs["Handlers"]; if (handlerConfig.GetString("CapsHandler", "") != Name) return; m_registry = registry; registry.RegisterModuleInterface<ICapsService>(this); } public void Start(IConfigSource config, IRegistryCore registry) { ISimulationBase simBase = registry.RequestModuleInterface<ISimulationBase>(); m_server = simBase.GetHttpServer(0); if (MainConsole.Instance != null) MainConsole.Instance.Commands.AddCommand("show presences", "show presences", "Shows all presences in the grid", ShowUsers); } public void FinishedStartup() { } #endregion #region Console Commands protected void ShowUsers(string[] cmd) { //Check for all or full to show child agents bool showChildAgents = cmd.Length == 3 && (cmd[2] == "all" || (cmd[2] == "full")); #if (!ISWIN) int count = 0; foreach (IRegionCapsService regionCaps in m_RegionCapsServices.Values) foreach (IRegionClientCapsService client in regionCaps.GetClients()) { if ((client.RootAgent || showChildAgents)) count++; } #else int count = m_RegionCapsServices.Values.SelectMany(regionCaps => regionCaps.GetClients()).Count(clientCaps => (clientCaps.RootAgent || showChildAgents)); #endif MainConsole.Instance.WarnFormat ("{0} agents found: ", count); foreach (IClientCapsService clientCaps in m_ClientCapsServices.Values) { foreach(IRegionClientCapsService caps in clientCaps.GetCapsServices()) { if((caps.RootAgent || showChildAgents)) { MainConsole.Instance.InfoFormat("Region - {0}, User {1}, {2}, {3}", caps.Region.RegionName, clientCaps.AccountInfo.Name, caps.RootAgent ? "Root Agent" : "Child Agent", caps.Disabled ? "Disabled" : "Not Disabled"); } } } } #endregion #region ICapsService members #region Client Caps /// <summary> /// Remove the all of the user's CAPS from the system /// </summary> /// <param name="AgentID"></param> public void RemoveCAPS(UUID AgentID) { if(m_ClientCapsServices.ContainsKey(AgentID)) { IClientCapsService perClient = m_ClientCapsServices[AgentID]; perClient.Close(); m_ClientCapsServices.Remove(AgentID); m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UserLogout", AgentID); } } /// <summary> /// Create a Caps URL for the given user/region. Called normally by the EventQueueService or the LLLoginService on login /// </summary> /// <param name="AgentID"></param> /// <param name="CAPSBase"></param> /// <param name="regionHandle"></param> /// <param name="IsRootAgent">Will this child be a root agent</param> /// <param name="circuitData"></param> /// <returns></returns> public string CreateCAPS(UUID AgentID, string CAPSBase, ulong regionHandle, bool IsRootAgent, AgentCircuitData circuitData) { return CreateCAPS (AgentID, CAPSBase, regionHandle, IsRootAgent, circuitData, 0); } public string CreateCAPS (UUID AgentID, string CAPSBase, ulong regionHandle, bool IsRootAgent, AgentCircuitData circuitData, uint port) { //Now make sure we didn't use an old one or something IClientCapsService service = GetOrCreateClientCapsService(AgentID); IRegionClientCapsService clientService = service.GetOrCreateCapsService(regionHandle, CAPSBase, circuitData, port); //Fix the root agent status clientService.RootAgent = IsRootAgent; m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("UserLogin", AgentID); MainConsole.Instance.Debug("[CapsService]: Adding Caps URL " + clientService.CapsUrl + " for agent " + AgentID); return clientService.CapsUrl; } /// <summary> /// Get or create a new Caps Service for the given client /// Note: This does not add them to a region if one is created. /// </summary> /// <param name="AgentID"></param> /// <returns></returns> public IClientCapsService GetOrCreateClientCapsService(UUID AgentID) { if (!m_ClientCapsServices.ContainsKey(AgentID)) { PerClientBasedCapsService client = new PerClientBasedCapsService(); client.Initialise(this, AgentID); m_ClientCapsServices.Add(AgentID, client); } return m_ClientCapsServices[AgentID]; } /// <summary> /// Get a Caps Service for the given client /// </summary> /// <param name="AgentID"></param> /// <returns></returns> public IClientCapsService GetClientCapsService(UUID AgentID) { if (!m_ClientCapsServices.ContainsKey(AgentID)) return null; return m_ClientCapsServices[AgentID]; } public List<IClientCapsService> GetClientsCapsServices() { return new List<IClientCapsService>(m_ClientCapsServices.Values); } #endregion #region Region Caps /// <summary> /// Get a region handler for the given region /// </summary> /// <param name="RegionHandle"></param> public IRegionCapsService GetCapsForRegion(ulong RegionHandle) { IRegionCapsService service; if (m_RegionCapsServices.TryGetValue(RegionHandle, out service)) { return service; } return null; } /// <summary> /// Create a caps handler for the given region /// </summary> /// <param name="RegionHandle"></param> public void AddCapsForRegion(ulong RegionHandle) { if (!m_RegionCapsServices.ContainsKey(RegionHandle)) { IRegionCapsService service = new PerRegionCapsService(); service.Initialise(RegionHandle, Registry); m_RegionCapsServices.Add(RegionHandle, service); } } /// <summary> /// Remove the handler for the given region /// </summary> /// <param name="RegionHandle"></param> public void RemoveCapsForRegion(ulong RegionHandle) { if (m_RegionCapsServices.ContainsKey(RegionHandle)) m_RegionCapsServices.Remove(RegionHandle); } public List<IRegionCapsService> GetRegionsCapsServices() { return new List<IRegionCapsService>(m_RegionCapsServices.Values); } #endregion #endregion } }
//------------------------------------------------------------------------------ // <copyright file="FontInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.ComponentModel.Design; using System; using System.ComponentModel; using System.Collections; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Web; /// <devdoc> /// <para>Represents the font properties for text. This class cannot be inherited.</para> /// </devdoc> [ TypeConverterAttribute(typeof(ExpandableObjectConverter)) ] public sealed class FontInfo { private Style owner; /// <devdoc> /// </devdoc> internal FontInfo(Style owner) { this.owner = owner; } /// <devdoc> /// <para>Indicates whether the text is bold.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(false), WebSysDescription(SR.FontInfo_Bold), NotifyParentProperty(true) ] public bool Bold { get { if (owner.IsSet(Style.PROP_FONT_BOLD)) { return (bool)(owner.ViewState["Font_Bold"]); } return false; } set { owner.ViewState["Font_Bold"] = value; owner.SetBit(Style.PROP_FONT_BOLD); } } /// <devdoc> /// <para>Indicates whether the text is italic.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(false), WebSysDescription(SR.FontInfo_Italic), NotifyParentProperty(true) ] public bool Italic { get { if (owner.IsSet(Style.PROP_FONT_ITALIC)) { return (bool)(owner.ViewState["Font_Italic"]); } return false; } set { owner.ViewState["Font_Italic"] = value; owner.SetBit(Style.PROP_FONT_ITALIC); } } /// <devdoc> /// <para>Indicates the name of the font.</para> /// </devdoc> [ Editor("System.Drawing.Design.FontNameEditor, " + AssemblyRef.SystemDrawingDesign, typeof(UITypeEditor)), TypeConverterAttribute(typeof(FontConverter.FontNameConverter)), WebCategory("Appearance"), DefaultValue(""), WebSysDescription(SR.FontInfo_Name), NotifyParentProperty(true), RefreshProperties(RefreshProperties.Repaint), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public string Name { get { string[] names = Names; if (names.Length > 0) return names[0]; return String.Empty; } set { if (value == null) throw new ArgumentNullException("value"); if (value.Length == 0) { Names = null; } else { Names = new string[1] { value }; } } } /// <devdoc> /// </devdoc> [ TypeConverterAttribute(typeof(FontNamesConverter)), WebCategory("Appearance"), Editor("System.Windows.Forms.Design.StringArrayEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor)), WebSysDescription(SR.FontInfo_Names), RefreshProperties(RefreshProperties.Repaint), NotifyParentProperty(true) ] public string[] Names { get { if (owner.IsSet(Style.PROP_FONT_NAMES)) { string[] names = (string[])owner.ViewState["Font_Names"]; if (names != null) return names; } return new string[0]; } set { owner.ViewState["Font_Names"] = value; owner.SetBit(Style.PROP_FONT_NAMES); } } /// <devdoc> /// <para>Indicates whether the text is overline.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(false), WebSysDescription(SR.FontInfo_Overline), NotifyParentProperty(true) ] public bool Overline { get { if (owner.IsSet(Style.PROP_FONT_OVERLINE)) { return (bool)(owner.ViewState["Font_Overline"]); } return false; } set { owner.ViewState["Font_Overline"] = value; owner.SetBit(Style.PROP_FONT_OVERLINE); } } /// <devdoc> /// </devdoc> internal Style Owner { get { return owner; } } /// <devdoc> /// <para>Indicates the font size.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(typeof(FontUnit), ""), WebSysDescription(SR.FontInfo_Size), NotifyParentProperty(true), RefreshProperties(RefreshProperties.Repaint) ] public FontUnit Size { get { if (owner.IsSet(Style.PROP_FONT_SIZE)) { return (FontUnit)(owner.ViewState["Font_Size"]); } return FontUnit.Empty; } set { if ((value.Type == FontSize.AsUnit) && (value.Unit.Value < 0)) { throw new ArgumentOutOfRangeException("value"); } owner.ViewState["Font_Size"] = value; owner.SetBit(Style.PROP_FONT_SIZE); } } /// <devdoc> /// <para>Indicates whether the text is striked out.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(false), WebSysDescription(SR.FontInfo_Strikeout), NotifyParentProperty(true) ] public bool Strikeout { get { if (owner.IsSet(Style.PROP_FONT_STRIKEOUT)) { return (bool)(owner.ViewState["Font_Strikeout"]); } return false; } set { owner.ViewState["Font_Strikeout"] = value; owner.SetBit(Style.PROP_FONT_STRIKEOUT); } } /// <devdoc> /// <para>Indicates whether the text is underlined.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(false), WebSysDescription(SR.FontInfo_Underline), NotifyParentProperty(true) ] public bool Underline { get { if (owner.IsSet(Style.PROP_FONT_UNDERLINE)) { return (bool)(owner.ViewState["Font_Underline"]); } return false; } set { owner.ViewState["Font_Underline"] = value; owner.SetBit(Style.PROP_FONT_UNDERLINE); } } /// <devdoc> /// <para>Resets all properties that have their default value to their unset state. </para> /// </devdoc> public void ClearDefaults() { if (Names.Length == 0) { owner.ViewState.Remove("Font_Names"); owner.ClearBit(Style.PROP_FONT_NAMES); } if (Size == FontUnit.Empty) { owner.ViewState.Remove("Font_Size"); owner.ClearBit(Style.PROP_FONT_SIZE); } if (Bold == false) ResetBold(); if (Italic == false) ResetItalic(); if (Underline == false) ResetUnderline(); if (Overline == false) ResetOverline(); if (Strikeout == false) ResetStrikeout(); } /// <devdoc> /// <para>Copies the font properties of another <see cref='System.Web.UI.WebControls.FontInfo'/> into this instance. </para> /// </devdoc> public void CopyFrom(FontInfo f) { if (f != null) { Style fOwner = f.Owner; if (fOwner.RegisteredCssClass.Length != 0) { if (fOwner.IsSet(Style.PROP_FONT_NAMES)) ResetNames(); if (fOwner.IsSet(Style.PROP_FONT_SIZE) && (f.Size != FontUnit.Empty)) ResetFontSize(); if (fOwner.IsSet(Style.PROP_FONT_BOLD)) ResetBold(); if (fOwner.IsSet(Style.PROP_FONT_ITALIC)) ResetItalic(); if (fOwner.IsSet(Style.PROP_FONT_OVERLINE)) ResetOverline(); if (fOwner.IsSet(Style.PROP_FONT_STRIKEOUT)) ResetStrikeout(); if (fOwner.IsSet(Style.PROP_FONT_UNDERLINE)) ResetUnderline(); } else { if (fOwner.IsSet(Style.PROP_FONT_NAMES)) { Names = f.Names; } if (fOwner.IsSet(Style.PROP_FONT_SIZE) && (f.Size != FontUnit.Empty)) Size = f.Size; // Only carry through true boolean values. Otherwise merging and copying // can do 3 different things for each property, but they are only persisted // as 2 state values. if (fOwner.IsSet(Style.PROP_FONT_BOLD)) Bold = f.Bold; if (fOwner.IsSet(Style.PROP_FONT_ITALIC)) Italic = f.Italic; if (fOwner.IsSet(Style.PROP_FONT_OVERLINE)) Overline = f.Overline; if (fOwner.IsSet(Style.PROP_FONT_STRIKEOUT)) Strikeout = f.Strikeout; if (fOwner.IsSet(Style.PROP_FONT_UNDERLINE)) Underline = f.Underline; } } } /// <devdoc> /// <para>Combines the font properties of another <see cref='System.Web.UI.WebControls.FontInfo'/> with this /// instance. </para> /// </devdoc> public void MergeWith(FontInfo f) { if (f != null) { Style fOwner = f.Owner; if (fOwner.RegisteredCssClass.Length == 0) { if (fOwner.IsSet(Style.PROP_FONT_NAMES) && !owner.IsSet(Style.PROP_FONT_NAMES)) Names = f.Names; if (fOwner.IsSet(Style.PROP_FONT_SIZE) && (!owner.IsSet(Style.PROP_FONT_SIZE) || (Size == FontUnit.Empty))) Size = f.Size; if (fOwner.IsSet(Style.PROP_FONT_BOLD) && !owner.IsSet(Style.PROP_FONT_BOLD)) Bold = f.Bold; if (fOwner.IsSet(Style.PROP_FONT_ITALIC) && !owner.IsSet(Style.PROP_FONT_ITALIC)) Italic = f.Italic; if (fOwner.IsSet(Style.PROP_FONT_OVERLINE) && !owner.IsSet(Style.PROP_FONT_OVERLINE)) Overline = f.Overline; if (fOwner.IsSet(Style.PROP_FONT_STRIKEOUT) && !owner.IsSet(Style.PROP_FONT_STRIKEOUT)) Strikeout = f.Strikeout; if (fOwner.IsSet(Style.PROP_FONT_UNDERLINE) && !owner.IsSet(Style.PROP_FONT_UNDERLINE)) Underline = f.Underline; } } } /// <devdoc> /// Resets all properties to their defaults. /// </devdoc> internal void Reset() { if (owner.IsSet(Style.PROP_FONT_NAMES)) ResetNames(); if (owner.IsSet(Style.PROP_FONT_SIZE)) ResetFontSize(); if (owner.IsSet(Style.PROP_FONT_BOLD)) ResetBold(); if (owner.IsSet(Style.PROP_FONT_ITALIC)) ResetItalic(); if (owner.IsSet(Style.PROP_FONT_UNDERLINE)) ResetUnderline(); if (owner.IsSet(Style.PROP_FONT_OVERLINE)) ResetOverline(); if (owner.IsSet(Style.PROP_FONT_STRIKEOUT)) ResetStrikeout(); } /// <devdoc> /// Only serialize if the Bold property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private void ResetBold() { owner.ViewState.Remove("Font_Bold"); owner.ClearBit(Style.PROP_FONT_BOLD); } private void ResetNames() { owner.ViewState.Remove("Font_Names"); owner.ClearBit(Style.PROP_FONT_NAMES); } private void ResetFontSize() { owner.ViewState.Remove("Font_Size"); owner.ClearBit(Style.PROP_FONT_SIZE); } /// <devdoc> /// Only serialize if the Italic property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private void ResetItalic() { owner.ViewState.Remove("Font_Italic"); owner.ClearBit(Style.PROP_FONT_ITALIC); } /// <devdoc> /// Only serialize if the Overline property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private void ResetOverline() { owner.ViewState.Remove("Font_Overline"); owner.ClearBit(Style.PROP_FONT_OVERLINE); } /// <devdoc> /// Only serialize if the Strikeout property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private void ResetStrikeout() { owner.ViewState.Remove("Font_Strikeout"); owner.ClearBit(Style.PROP_FONT_STRIKEOUT); } /// <devdoc> /// Only serialize if the Underline property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private void ResetUnderline() { owner.ViewState.Remove("Font_Underline"); owner.ClearBit(Style.PROP_FONT_UNDERLINE); } /// <devdoc> /// Only serialize if the Bold property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private bool ShouldSerializeBold() { return owner.IsSet(Style.PROP_FONT_BOLD); } /// <devdoc> /// Only serialize if the Italic property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private bool ShouldSerializeItalic() { return owner.IsSet(Style.PROP_FONT_ITALIC); } /// <devdoc> /// Only serialize if the Overline property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private bool ShouldSerializeOverline() { return owner.IsSet(Style.PROP_FONT_OVERLINE); } /// <devdoc> /// Only serialize if the Strikeout property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private bool ShouldSerializeStrikeout() { return owner.IsSet(Style.PROP_FONT_STRIKEOUT); } /// <devdoc> /// Only serialize if the Underline property has changed. This means that we serialize "false" /// if they were set to false in the designer. /// </devdoc> private bool ShouldSerializeUnderline() { return owner.IsSet(Style.PROP_FONT_UNDERLINE); } /// <internalonly/> public bool ShouldSerializeNames() { string[] names = Names; return names.Length > 0; } /// <devdoc> /// </devdoc> public override string ToString() { string size = this.Size.ToString(CultureInfo.InvariantCulture); string s = this.Name; if (size.Length != 0) { if (s.Length != 0) { s += ", " + size; } else { s = size; } } return s; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the MamEcografium class. /// </summary> [Serializable] public partial class MamEcografiumCollection : ActiveList<MamEcografium, MamEcografiumCollection> { public MamEcografiumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>MamEcografiumCollection</returns> public MamEcografiumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { MamEcografium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the MAM_Ecografia table. /// </summary> [Serializable] public partial class MamEcografium : ActiveRecord<MamEcografium>, IActiveRecord { #region .ctors and Default Settings public MamEcografium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public MamEcografium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public MamEcografium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public MamEcografium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("MAM_Ecografia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEcografiaMamaria = new TableSchema.TableColumn(schema); colvarIdEcografiaMamaria.ColumnName = "idEcografiaMamaria"; colvarIdEcografiaMamaria.DataType = DbType.Int32; colvarIdEcografiaMamaria.MaxLength = 0; colvarIdEcografiaMamaria.AutoIncrement = true; colvarIdEcografiaMamaria.IsNullable = false; colvarIdEcografiaMamaria.IsPrimaryKey = true; colvarIdEcografiaMamaria.IsForeignKey = false; colvarIdEcografiaMamaria.IsReadOnly = false; colvarIdEcografiaMamaria.DefaultSetting = @""; colvarIdEcografiaMamaria.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEcografiaMamaria); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = true; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @"((0))"; colvarIdPaciente.ForeignKeyTableName = "Sys_Paciente"; schema.Columns.Add(colvarIdPaciente); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = false; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @"((0))"; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarIdMotivoEstudio = new TableSchema.TableColumn(schema); colvarIdMotivoEstudio.ColumnName = "idMotivoEstudio"; colvarIdMotivoEstudio.DataType = DbType.Int32; colvarIdMotivoEstudio.MaxLength = 0; colvarIdMotivoEstudio.AutoIncrement = false; colvarIdMotivoEstudio.IsNullable = false; colvarIdMotivoEstudio.IsPrimaryKey = false; colvarIdMotivoEstudio.IsForeignKey = true; colvarIdMotivoEstudio.IsReadOnly = false; colvarIdMotivoEstudio.DefaultSetting = @"((0))"; colvarIdMotivoEstudio.ForeignKeyTableName = "MAM_MotivoConsulta"; schema.Columns.Add(colvarIdMotivoEstudio); TableSchema.TableColumn colvarFechaEcografia = new TableSchema.TableColumn(schema); colvarFechaEcografia.ColumnName = "fechaEcografia"; colvarFechaEcografia.DataType = DbType.DateTime; colvarFechaEcografia.MaxLength = 0; colvarFechaEcografia.AutoIncrement = false; colvarFechaEcografia.IsNullable = false; colvarFechaEcografia.IsPrimaryKey = false; colvarFechaEcografia.IsForeignKey = false; colvarFechaEcografia.IsReadOnly = false; colvarFechaEcografia.DefaultSetting = @""; colvarFechaEcografia.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaEcografia); TableSchema.TableColumn colvarIdEfectorSolicita = new TableSchema.TableColumn(schema); colvarIdEfectorSolicita.ColumnName = "idEfectorSolicita"; colvarIdEfectorSolicita.DataType = DbType.Int32; colvarIdEfectorSolicita.MaxLength = 0; colvarIdEfectorSolicita.AutoIncrement = false; colvarIdEfectorSolicita.IsNullable = false; colvarIdEfectorSolicita.IsPrimaryKey = false; colvarIdEfectorSolicita.IsForeignKey = true; colvarIdEfectorSolicita.IsReadOnly = false; colvarIdEfectorSolicita.DefaultSetting = @"((0))"; colvarIdEfectorSolicita.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfectorSolicita); TableSchema.TableColumn colvarIdEfectorInforma = new TableSchema.TableColumn(schema); colvarIdEfectorInforma.ColumnName = "idEfectorInforma"; colvarIdEfectorInforma.DataType = DbType.Int32; colvarIdEfectorInforma.MaxLength = 0; colvarIdEfectorInforma.AutoIncrement = false; colvarIdEfectorInforma.IsNullable = false; colvarIdEfectorInforma.IsPrimaryKey = false; colvarIdEfectorInforma.IsForeignKey = true; colvarIdEfectorInforma.IsReadOnly = false; colvarIdEfectorInforma.DefaultSetting = @"((0))"; colvarIdEfectorInforma.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfectorInforma); TableSchema.TableColumn colvarIdProfesionalSolicita = new TableSchema.TableColumn(schema); colvarIdProfesionalSolicita.ColumnName = "idProfesionalSolicita"; colvarIdProfesionalSolicita.DataType = DbType.Int32; colvarIdProfesionalSolicita.MaxLength = 0; colvarIdProfesionalSolicita.AutoIncrement = false; colvarIdProfesionalSolicita.IsNullable = false; colvarIdProfesionalSolicita.IsPrimaryKey = false; colvarIdProfesionalSolicita.IsForeignKey = true; colvarIdProfesionalSolicita.IsReadOnly = false; colvarIdProfesionalSolicita.DefaultSetting = @"((0))"; colvarIdProfesionalSolicita.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdProfesionalSolicita); TableSchema.TableColumn colvarFechaInforme = new TableSchema.TableColumn(schema); colvarFechaInforme.ColumnName = "fechaInforme"; colvarFechaInforme.DataType = DbType.DateTime; colvarFechaInforme.MaxLength = 0; colvarFechaInforme.AutoIncrement = false; colvarFechaInforme.IsNullable = false; colvarFechaInforme.IsPrimaryKey = false; colvarFechaInforme.IsForeignKey = false; colvarFechaInforme.IsReadOnly = false; colvarFechaInforme.DefaultSetting = @""; colvarFechaInforme.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaInforme); TableSchema.TableColumn colvarIdBiradsI = new TableSchema.TableColumn(schema); colvarIdBiradsI.ColumnName = "idBiradsI"; colvarIdBiradsI.DataType = DbType.Int32; colvarIdBiradsI.MaxLength = 0; colvarIdBiradsI.AutoIncrement = false; colvarIdBiradsI.IsNullable = false; colvarIdBiradsI.IsPrimaryKey = false; colvarIdBiradsI.IsForeignKey = true; colvarIdBiradsI.IsReadOnly = false; colvarIdBiradsI.DefaultSetting = @"((0))"; colvarIdBiradsI.ForeignKeyTableName = "MAM_Birads"; schema.Columns.Add(colvarIdBiradsI); TableSchema.TableColumn colvarIdBiradsD = new TableSchema.TableColumn(schema); colvarIdBiradsD.ColumnName = "idBiradsD"; colvarIdBiradsD.DataType = DbType.Int32; colvarIdBiradsD.MaxLength = 0; colvarIdBiradsD.AutoIncrement = false; colvarIdBiradsD.IsNullable = false; colvarIdBiradsD.IsPrimaryKey = false; colvarIdBiradsD.IsForeignKey = true; colvarIdBiradsD.IsReadOnly = false; colvarIdBiradsD.DefaultSetting = @"((0))"; colvarIdBiradsD.ForeignKeyTableName = "MAM_Birads"; schema.Columns.Add(colvarIdBiradsD); TableSchema.TableColumn colvarIdBiradsDef = new TableSchema.TableColumn(schema); colvarIdBiradsDef.ColumnName = "idBiradsDef"; colvarIdBiradsDef.DataType = DbType.Int32; colvarIdBiradsDef.MaxLength = 0; colvarIdBiradsDef.AutoIncrement = false; colvarIdBiradsDef.IsNullable = false; colvarIdBiradsDef.IsPrimaryKey = false; colvarIdBiradsDef.IsForeignKey = true; colvarIdBiradsDef.IsReadOnly = false; colvarIdBiradsDef.DefaultSetting = @"((0))"; colvarIdBiradsDef.ForeignKeyTableName = "MAM_Birads"; schema.Columns.Add(colvarIdBiradsDef); TableSchema.TableColumn colvarInforme = new TableSchema.TableColumn(schema); colvarInforme.ColumnName = "informe"; colvarInforme.DataType = DbType.AnsiString; colvarInforme.MaxLength = 2000; colvarInforme.AutoIncrement = false; colvarInforme.IsNullable = false; colvarInforme.IsPrimaryKey = false; colvarInforme.IsForeignKey = false; colvarInforme.IsReadOnly = false; colvarInforme.DefaultSetting = @""; colvarInforme.ForeignKeyTableName = ""; schema.Columns.Add(colvarInforme); TableSchema.TableColumn colvarMaterialRemitido = new TableSchema.TableColumn(schema); colvarMaterialRemitido.ColumnName = "materialRemitido"; colvarMaterialRemitido.DataType = DbType.AnsiString; colvarMaterialRemitido.MaxLength = 50; colvarMaterialRemitido.AutoIncrement = false; colvarMaterialRemitido.IsNullable = false; colvarMaterialRemitido.IsPrimaryKey = false; colvarMaterialRemitido.IsForeignKey = false; colvarMaterialRemitido.IsReadOnly = false; colvarMaterialRemitido.DefaultSetting = @"('')"; colvarMaterialRemitido.ForeignKeyTableName = ""; schema.Columns.Add(colvarMaterialRemitido); TableSchema.TableColumn colvarIdProfesionalResponsable = new TableSchema.TableColumn(schema); colvarIdProfesionalResponsable.ColumnName = "idProfesionalResponsable"; colvarIdProfesionalResponsable.DataType = DbType.Int32; colvarIdProfesionalResponsable.MaxLength = 0; colvarIdProfesionalResponsable.AutoIncrement = false; colvarIdProfesionalResponsable.IsNullable = false; colvarIdProfesionalResponsable.IsPrimaryKey = false; colvarIdProfesionalResponsable.IsForeignKey = true; colvarIdProfesionalResponsable.IsReadOnly = false; colvarIdProfesionalResponsable.DefaultSetting = @"((0))"; colvarIdProfesionalResponsable.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdProfesionalResponsable); TableSchema.TableColumn colvarActivo = new TableSchema.TableColumn(schema); colvarActivo.ColumnName = "activo"; colvarActivo.DataType = DbType.Boolean; colvarActivo.MaxLength = 0; colvarActivo.AutoIncrement = false; colvarActivo.IsNullable = false; colvarActivo.IsPrimaryKey = false; colvarActivo.IsForeignKey = false; colvarActivo.IsReadOnly = false; colvarActivo.DefaultSetting = @"((1))"; colvarActivo.ForeignKeyTableName = ""; schema.Columns.Add(colvarActivo); TableSchema.TableColumn colvarCreatedBy = new TableSchema.TableColumn(schema); colvarCreatedBy.ColumnName = "CreatedBy"; colvarCreatedBy.DataType = DbType.String; colvarCreatedBy.MaxLength = 50; colvarCreatedBy.AutoIncrement = false; colvarCreatedBy.IsNullable = false; colvarCreatedBy.IsPrimaryKey = false; colvarCreatedBy.IsForeignKey = false; colvarCreatedBy.IsReadOnly = false; colvarCreatedBy.DefaultSetting = @"('')"; colvarCreatedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedBy); TableSchema.TableColumn colvarCreatedOn = new TableSchema.TableColumn(schema); colvarCreatedOn.ColumnName = "CreatedOn"; colvarCreatedOn.DataType = DbType.DateTime; colvarCreatedOn.MaxLength = 0; colvarCreatedOn.AutoIncrement = false; colvarCreatedOn.IsNullable = false; colvarCreatedOn.IsPrimaryKey = false; colvarCreatedOn.IsForeignKey = false; colvarCreatedOn.IsReadOnly = false; colvarCreatedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarCreatedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarCreatedOn); TableSchema.TableColumn colvarModifiedBy = new TableSchema.TableColumn(schema); colvarModifiedBy.ColumnName = "ModifiedBy"; colvarModifiedBy.DataType = DbType.String; colvarModifiedBy.MaxLength = 50; colvarModifiedBy.AutoIncrement = false; colvarModifiedBy.IsNullable = false; colvarModifiedBy.IsPrimaryKey = false; colvarModifiedBy.IsForeignKey = false; colvarModifiedBy.IsReadOnly = false; colvarModifiedBy.DefaultSetting = @"('')"; colvarModifiedBy.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedBy); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; colvarModifiedOn.DefaultSetting = @"(((1)/(1))/(1900))"; colvarModifiedOn.ForeignKeyTableName = ""; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarIdEfectorRealizaEstudio = new TableSchema.TableColumn(schema); colvarIdEfectorRealizaEstudio.ColumnName = "idEfectorRealizaEstudio"; colvarIdEfectorRealizaEstudio.DataType = DbType.Int32; colvarIdEfectorRealizaEstudio.MaxLength = 0; colvarIdEfectorRealizaEstudio.AutoIncrement = false; colvarIdEfectorRealizaEstudio.IsNullable = false; colvarIdEfectorRealizaEstudio.IsPrimaryKey = false; colvarIdEfectorRealizaEstudio.IsForeignKey = true; colvarIdEfectorRealizaEstudio.IsReadOnly = false; colvarIdEfectorRealizaEstudio.DefaultSetting = @"((0))"; colvarIdEfectorRealizaEstudio.ForeignKeyTableName = "Sys_Efector"; schema.Columns.Add(colvarIdEfectorRealizaEstudio); TableSchema.TableColumn colvarIdTipoEquipo = new TableSchema.TableColumn(schema); colvarIdTipoEquipo.ColumnName = "idTipoEquipo"; colvarIdTipoEquipo.DataType = DbType.Int32; colvarIdTipoEquipo.MaxLength = 0; colvarIdTipoEquipo.AutoIncrement = false; colvarIdTipoEquipo.IsNullable = false; colvarIdTipoEquipo.IsPrimaryKey = false; colvarIdTipoEquipo.IsForeignKey = true; colvarIdTipoEquipo.IsReadOnly = false; colvarIdTipoEquipo.DefaultSetting = @"((0))"; colvarIdTipoEquipo.ForeignKeyTableName = "MAM_TipoEquipo"; schema.Columns.Add(colvarIdTipoEquipo); TableSchema.TableColumn colvarIdProfesionalTecnico = new TableSchema.TableColumn(schema); colvarIdProfesionalTecnico.ColumnName = "idProfesionalTecnico"; colvarIdProfesionalTecnico.DataType = DbType.Int32; colvarIdProfesionalTecnico.MaxLength = 0; colvarIdProfesionalTecnico.AutoIncrement = false; colvarIdProfesionalTecnico.IsNullable = false; colvarIdProfesionalTecnico.IsPrimaryKey = false; colvarIdProfesionalTecnico.IsForeignKey = true; colvarIdProfesionalTecnico.IsReadOnly = false; colvarIdProfesionalTecnico.DefaultSetting = @"((0))"; colvarIdProfesionalTecnico.ForeignKeyTableName = "Sys_Profesional"; schema.Columns.Add(colvarIdProfesionalTecnico); TableSchema.TableColumn colvarProtocolo = new TableSchema.TableColumn(schema); colvarProtocolo.ColumnName = "protocolo"; colvarProtocolo.DataType = DbType.AnsiString; colvarProtocolo.MaxLength = 20; colvarProtocolo.AutoIncrement = false; colvarProtocolo.IsNullable = false; colvarProtocolo.IsPrimaryKey = false; colvarProtocolo.IsForeignKey = false; colvarProtocolo.IsReadOnly = false; colvarProtocolo.DefaultSetting = @"('')"; colvarProtocolo.ForeignKeyTableName = ""; schema.Columns.Add(colvarProtocolo); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("MAM_Ecografia",schema); } } #endregion #region Props [XmlAttribute("IdEcografiaMamaria")] [Bindable(true)] public int IdEcografiaMamaria { get { return GetColumnValue<int>(Columns.IdEcografiaMamaria); } set { SetColumnValue(Columns.IdEcografiaMamaria, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int Edad { get { return GetColumnValue<int>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("IdMotivoEstudio")] [Bindable(true)] public int IdMotivoEstudio { get { return GetColumnValue<int>(Columns.IdMotivoEstudio); } set { SetColumnValue(Columns.IdMotivoEstudio, value); } } [XmlAttribute("FechaEcografia")] [Bindable(true)] public DateTime FechaEcografia { get { return GetColumnValue<DateTime>(Columns.FechaEcografia); } set { SetColumnValue(Columns.FechaEcografia, value); } } [XmlAttribute("IdEfectorSolicita")] [Bindable(true)] public int IdEfectorSolicita { get { return GetColumnValue<int>(Columns.IdEfectorSolicita); } set { SetColumnValue(Columns.IdEfectorSolicita, value); } } [XmlAttribute("IdEfectorInforma")] [Bindable(true)] public int IdEfectorInforma { get { return GetColumnValue<int>(Columns.IdEfectorInforma); } set { SetColumnValue(Columns.IdEfectorInforma, value); } } [XmlAttribute("IdProfesionalSolicita")] [Bindable(true)] public int IdProfesionalSolicita { get { return GetColumnValue<int>(Columns.IdProfesionalSolicita); } set { SetColumnValue(Columns.IdProfesionalSolicita, value); } } [XmlAttribute("FechaInforme")] [Bindable(true)] public DateTime FechaInforme { get { return GetColumnValue<DateTime>(Columns.FechaInforme); } set { SetColumnValue(Columns.FechaInforme, value); } } [XmlAttribute("IdBiradsI")] [Bindable(true)] public int IdBiradsI { get { return GetColumnValue<int>(Columns.IdBiradsI); } set { SetColumnValue(Columns.IdBiradsI, value); } } [XmlAttribute("IdBiradsD")] [Bindable(true)] public int IdBiradsD { get { return GetColumnValue<int>(Columns.IdBiradsD); } set { SetColumnValue(Columns.IdBiradsD, value); } } [XmlAttribute("IdBiradsDef")] [Bindable(true)] public int IdBiradsDef { get { return GetColumnValue<int>(Columns.IdBiradsDef); } set { SetColumnValue(Columns.IdBiradsDef, value); } } [XmlAttribute("Informe")] [Bindable(true)] public string Informe { get { return GetColumnValue<string>(Columns.Informe); } set { SetColumnValue(Columns.Informe, value); } } [XmlAttribute("MaterialRemitido")] [Bindable(true)] public string MaterialRemitido { get { return GetColumnValue<string>(Columns.MaterialRemitido); } set { SetColumnValue(Columns.MaterialRemitido, value); } } [XmlAttribute("IdProfesionalResponsable")] [Bindable(true)] public int IdProfesionalResponsable { get { return GetColumnValue<int>(Columns.IdProfesionalResponsable); } set { SetColumnValue(Columns.IdProfesionalResponsable, value); } } [XmlAttribute("Activo")] [Bindable(true)] public bool Activo { get { return GetColumnValue<bool>(Columns.Activo); } set { SetColumnValue(Columns.Activo, value); } } [XmlAttribute("CreatedBy")] [Bindable(true)] public string CreatedBy { get { return GetColumnValue<string>(Columns.CreatedBy); } set { SetColumnValue(Columns.CreatedBy, value); } } [XmlAttribute("CreatedOn")] [Bindable(true)] public DateTime CreatedOn { get { return GetColumnValue<DateTime>(Columns.CreatedOn); } set { SetColumnValue(Columns.CreatedOn, value); } } [XmlAttribute("ModifiedBy")] [Bindable(true)] public string ModifiedBy { get { return GetColumnValue<string>(Columns.ModifiedBy); } set { SetColumnValue(Columns.ModifiedBy, value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime ModifiedOn { get { return GetColumnValue<DateTime>(Columns.ModifiedOn); } set { SetColumnValue(Columns.ModifiedOn, value); } } [XmlAttribute("IdEfectorRealizaEstudio")] [Bindable(true)] public int IdEfectorRealizaEstudio { get { return GetColumnValue<int>(Columns.IdEfectorRealizaEstudio); } set { SetColumnValue(Columns.IdEfectorRealizaEstudio, value); } } [XmlAttribute("IdTipoEquipo")] [Bindable(true)] public int IdTipoEquipo { get { return GetColumnValue<int>(Columns.IdTipoEquipo); } set { SetColumnValue(Columns.IdTipoEquipo, value); } } [XmlAttribute("IdProfesionalTecnico")] [Bindable(true)] public int IdProfesionalTecnico { get { return GetColumnValue<int>(Columns.IdProfesionalTecnico); } set { SetColumnValue(Columns.IdProfesionalTecnico, value); } } [XmlAttribute("Protocolo")] [Bindable(true)] public string Protocolo { get { return GetColumnValue<string>(Columns.Protocolo); } set { SetColumnValue(Columns.Protocolo, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a SysEfector ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysEfector SysEfector { get { return DalSic.SysEfector.FetchByID(this.IdEfectorRealizaEstudio); } set { SetColumnValue("idEfectorRealizaEstudio", value.IdEfector); } } /// <summary> /// Returns a SysEfector ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysEfector SysEfectorToIdEfectorSolicita { get { return DalSic.SysEfector.FetchByID(this.IdEfectorSolicita); } set { SetColumnValue("idEfectorSolicita", value.IdEfector); } } /// <summary> /// Returns a SysEfector ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysEfector SysEfectorToIdEfectorInforma { get { return DalSic.SysEfector.FetchByID(this.IdEfectorInforma); } set { SetColumnValue("idEfectorInforma", value.IdEfector); } } /// <summary> /// Returns a MamMotivoConsultum ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.MamMotivoConsultum MamMotivoConsultum { get { return DalSic.MamMotivoConsultum.FetchByID(this.IdMotivoEstudio); } set { SetColumnValue("idMotivoEstudio", value.IdMotivoConsulta); } } /// <summary> /// Returns a MamBirad ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.MamBirad MamBirad { get { return DalSic.MamBirad.FetchByID(this.IdBiradsDef); } set { SetColumnValue("idBiradsDef", value.IdBirads); } } /// <summary> /// Returns a MamBirad ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.MamBirad MamBiradToIdBiradsI { get { return DalSic.MamBirad.FetchByID(this.IdBiradsI); } set { SetColumnValue("idBiradsI", value.IdBirads); } } /// <summary> /// Returns a MamBirad ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.MamBirad MamBiradToIdBiradsD { get { return DalSic.MamBirad.FetchByID(this.IdBiradsD); } set { SetColumnValue("idBiradsD", value.IdBirads); } } /// <summary> /// Returns a SysPaciente ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysPaciente SysPaciente { get { return DalSic.SysPaciente.FetchByID(this.IdPaciente); } set { SetColumnValue("idPaciente", value.IdPaciente); } } /// <summary> /// Returns a MamTipoEquipo ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.MamTipoEquipo MamTipoEquipo { get { return DalSic.MamTipoEquipo.FetchByID(this.IdTipoEquipo); } set { SetColumnValue("idTipoEquipo", value.IdTipoEquipo); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysProfesional SysProfesional { get { return DalSic.SysProfesional.FetchByID(this.IdProfesionalTecnico); } set { SetColumnValue("idProfesionalTecnico", value.IdProfesional); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysProfesional SysProfesionalToIdProfesionalSolicita { get { return DalSic.SysProfesional.FetchByID(this.IdProfesionalSolicita); } set { SetColumnValue("idProfesionalSolicita", value.IdProfesional); } } /// <summary> /// Returns a SysProfesional ActiveRecord object related to this MamEcografium /// /// </summary> public DalSic.SysProfesional SysProfesionalToIdProfesionalResponsable { get { return DalSic.SysProfesional.FetchByID(this.IdProfesionalResponsable); } set { SetColumnValue("idProfesionalResponsable", value.IdProfesional); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdPaciente,int varEdad,int varIdMotivoEstudio,DateTime varFechaEcografia,int varIdEfectorSolicita,int varIdEfectorInforma,int varIdProfesionalSolicita,DateTime varFechaInforme,int varIdBiradsI,int varIdBiradsD,int varIdBiradsDef,string varInforme,string varMaterialRemitido,int varIdProfesionalResponsable,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn,int varIdEfectorRealizaEstudio,int varIdTipoEquipo,int varIdProfesionalTecnico,string varProtocolo) { MamEcografium item = new MamEcografium(); item.IdPaciente = varIdPaciente; item.Edad = varEdad; item.IdMotivoEstudio = varIdMotivoEstudio; item.FechaEcografia = varFechaEcografia; item.IdEfectorSolicita = varIdEfectorSolicita; item.IdEfectorInforma = varIdEfectorInforma; item.IdProfesionalSolicita = varIdProfesionalSolicita; item.FechaInforme = varFechaInforme; item.IdBiradsI = varIdBiradsI; item.IdBiradsD = varIdBiradsD; item.IdBiradsDef = varIdBiradsDef; item.Informe = varInforme; item.MaterialRemitido = varMaterialRemitido; item.IdProfesionalResponsable = varIdProfesionalResponsable; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IdEfectorRealizaEstudio = varIdEfectorRealizaEstudio; item.IdTipoEquipo = varIdTipoEquipo; item.IdProfesionalTecnico = varIdProfesionalTecnico; item.Protocolo = varProtocolo; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEcografiaMamaria,int varIdPaciente,int varEdad,int varIdMotivoEstudio,DateTime varFechaEcografia,int varIdEfectorSolicita,int varIdEfectorInforma,int varIdProfesionalSolicita,DateTime varFechaInforme,int varIdBiradsI,int varIdBiradsD,int varIdBiradsDef,string varInforme,string varMaterialRemitido,int varIdProfesionalResponsable,bool varActivo,string varCreatedBy,DateTime varCreatedOn,string varModifiedBy,DateTime varModifiedOn,int varIdEfectorRealizaEstudio,int varIdTipoEquipo,int varIdProfesionalTecnico,string varProtocolo) { MamEcografium item = new MamEcografium(); item.IdEcografiaMamaria = varIdEcografiaMamaria; item.IdPaciente = varIdPaciente; item.Edad = varEdad; item.IdMotivoEstudio = varIdMotivoEstudio; item.FechaEcografia = varFechaEcografia; item.IdEfectorSolicita = varIdEfectorSolicita; item.IdEfectorInforma = varIdEfectorInforma; item.IdProfesionalSolicita = varIdProfesionalSolicita; item.FechaInforme = varFechaInforme; item.IdBiradsI = varIdBiradsI; item.IdBiradsD = varIdBiradsD; item.IdBiradsDef = varIdBiradsDef; item.Informe = varInforme; item.MaterialRemitido = varMaterialRemitido; item.IdProfesionalResponsable = varIdProfesionalResponsable; item.Activo = varActivo; item.CreatedBy = varCreatedBy; item.CreatedOn = varCreatedOn; item.ModifiedBy = varModifiedBy; item.ModifiedOn = varModifiedOn; item.IdEfectorRealizaEstudio = varIdEfectorRealizaEstudio; item.IdTipoEquipo = varIdTipoEquipo; item.IdProfesionalTecnico = varIdProfesionalTecnico; item.Protocolo = varProtocolo; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEcografiaMamariaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdMotivoEstudioColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaEcografiaColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IdEfectorSolicitaColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdEfectorInformaColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdProfesionalSolicitaColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaInformeColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn IdBiradsIColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn IdBiradsDColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn IdBiradsDefColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn InformeColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn MaterialRemitidoColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn IdProfesionalResponsableColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn ActivoColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn CreatedByColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn CreatedOnColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn ModifiedByColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn ModifiedOnColumn { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn IdEfectorRealizaEstudioColumn { get { return Schema.Columns[20]; } } public static TableSchema.TableColumn IdTipoEquipoColumn { get { return Schema.Columns[21]; } } public static TableSchema.TableColumn IdProfesionalTecnicoColumn { get { return Schema.Columns[22]; } } public static TableSchema.TableColumn ProtocoloColumn { get { return Schema.Columns[23]; } } #endregion #region Columns Struct public struct Columns { public static string IdEcografiaMamaria = @"idEcografiaMamaria"; public static string IdPaciente = @"idPaciente"; public static string Edad = @"edad"; public static string IdMotivoEstudio = @"idMotivoEstudio"; public static string FechaEcografia = @"fechaEcografia"; public static string IdEfectorSolicita = @"idEfectorSolicita"; public static string IdEfectorInforma = @"idEfectorInforma"; public static string IdProfesionalSolicita = @"idProfesionalSolicita"; public static string FechaInforme = @"fechaInforme"; public static string IdBiradsI = @"idBiradsI"; public static string IdBiradsD = @"idBiradsD"; public static string IdBiradsDef = @"idBiradsDef"; public static string Informe = @"informe"; public static string MaterialRemitido = @"materialRemitido"; public static string IdProfesionalResponsable = @"idProfesionalResponsable"; public static string Activo = @"activo"; public static string CreatedBy = @"CreatedBy"; public static string CreatedOn = @"CreatedOn"; public static string ModifiedBy = @"ModifiedBy"; public static string ModifiedOn = @"ModifiedOn"; public static string IdEfectorRealizaEstudio = @"idEfectorRealizaEstudio"; public static string IdTipoEquipo = @"idTipoEquipo"; public static string IdProfesionalTecnico = @"idProfesionalTecnico"; public static string Protocolo = @"protocolo"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// /* ------------------ // ${Name} // (c)3Radical 2012 // by Mike Talbot // ------------------- */ // using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Linq; using Serialization; using System.IO; [AddComponentMenu("Storage/Advanced/Only In Range Manager")] public class OnlyInRangeManager : MonoBehaviour { //Class to hold information about tracked items public class InRange { public Transform transform; public Vector3 lastPosition; bool _inprogress; //Inprogress flag indicates that it is being loaded or saved public bool inprogress { get { return _inprogress; } set { _inprogress = value; count =0; } } //Unique identifier public string id; //Number of frames since coming into or going out of range public int count; //Test function to see if we should save this item public void Test(OnlyInRangeManager manager, Vector3 position, float sqrRange) { if(inprogress) return; if(transform != null) { if((transform.position - position).sqrMagnitude < sqrRange) { count++; if(count > 3) manager.hideList.Remove(this); } else { count = 0; manager.hideList.Add(this); } } else { if((lastPosition - position).sqrMagnitude < sqrRange) { count++; if(count > 3) manager.viewList.Add(this); } else { count = 0; manager.viewList.Remove(this); } } } } //Singleton instance public static OnlyInRangeManager Instance; //Add an item to be tracked public void AddRangedItem(GameObject go) { var ui = go.GetComponent<PrefabIdentifier>(); if(ui==null) { return; } if(!rangedItems.Any(i=>i.id == ui.Id)) { rangedItems.Add(new InRange { id = ui.Id, transform = go.transform}); } } //Remove an item from tracking public void DestroyRangedItem(GameObject go) { var ui = go.GetComponent<PrefabIdentifier>(); if(ui==null) { return; } var item = rangedItems.FirstOrDefault(i=>i.id == ui.Id); if(item == null || item.inprogress) { return; } if(File.Exists(Application.persistentDataPath + "/" + item.id + ".dat")) { File.Delete(Application.persistentDataPath + "/" + item.id + ".dat"); } rangedItems.Remove(item); } //All of the items currently tracked [SerializeThis] HashSet<InRange> rangedItems = new HashSet<InRange>(); //Items being hidden [SerializeThis] HashSet<InRange> hideList = new HashSet<InRange>(); //Items being shown [SerializeThis] HashSet<InRange> viewList = new HashSet<InRange>(); //Range public float range = 5; void Awake() { Instance = this; } void LateUpdate() { if(LevelSerializer.IsDeserializing) return; var sqrRange = range * range; var p = transform.position; //Test all of the items foreach(var r in rangedItems) { r.Test(this, p, sqrRange); } //Hide items on odd frames if(hideList.Count > 0 && (Time.frameCount & 1) != 0) { var h = hideList.First(); hideList.Remove(h); h.inprogress = true; StartCoroutine(HideItem(h)); } //Show items on even frames if(viewList.Count >0 && (Time.frameCount & 1)==0) { var v = viewList.First(); viewList.Remove(v); v.inprogress = true; StartCoroutine(ViewItem(v)); } } //Hide an item IEnumerator HideItem(InRange item) { LevelSerializer.DontCollect(); //Save the data var data = LevelSerializer.SerializeLevel(false, item.transform.GetComponent<UniqueIdentifier>().Id); yield return new WaitForEndOfFrame(); LevelSerializer.Collect(); //Write it to a file var f = File.Create(Application.persistentDataPath + "/" + item.id + ".dat"); f.Write(data,0,data.Length); yield return null; f.Close(); yield return new WaitForEndOfFrame(); //Destroy the game object item.lastPosition = item.transform.position; Destroy(item.transform.gameObject); yield return new WaitForEndOfFrame(); item.transform = null; item.inprogress = false; } //Load an item IEnumerator ViewItem(InRange item) { //Check for the file if(!File.Exists(Application.persistentDataPath + "/" + item.id + ".dat")) { yield break; } yield return new WaitForEndOfFrame(); //Load the data var f = File.Open(Application.persistentDataPath + "/" + item.id + ".dat", FileMode.Open); var d = new byte[f.Length]; f.Read(d, 0, (int)f.Length); f.Close(); yield return new WaitForEndOfFrame(); //Deserialize it var complete = false; LevelLoader loader = null; LevelSerializer.DontCollect(); LevelSerializer.LoadNow(d, true, false, (usedLevelLoader)=>{ complete = true; loader = usedLevelLoader; LevelSerializer.Collect(); }); while(!complete) { yield return null; } item.transform = loader.Last.transform; item.inprogress = false; } }
#region License //L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L #endregion using System; using System.Drawing; using System.Collections.Generic; using ClearCanvas.Common; using ClearCanvas.Common.Utilities; using ClearCanvas.Desktop; using ClearCanvas.Desktop.Configuration; using ClearCanvas.ImageViewer; using ClearCanvas.ImageViewer.Graphics; using AIM.Annotation.Graphics; using GeneralUtilities.Collections; namespace AIM.Annotation.Configuration { [ExtensionPoint] public sealed class AimMarkupColorComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView> { } [AssociateView(typeof(AimMarkupColorComponentViewExtensionPoint))] public class AimMarkupColorComponent : ConfigurationApplicationComponent { public static readonly string Path = "AIM/Markup"; private AimSettings _settings; private Color _defaultMarkupColor; private XmlSerializableStringToColorDictionary _loginNameMarkupColorsOriginalSettings; private bool _useRandomDefaultMarkupColor; private readonly ObservableDictionary<string, UserMarkupProperties> _userMarkupPropertiesDictionary = new ObservableDictionary<string, UserMarkupProperties>(); #region User Markup Properties class public class UserMarkupProperties { private readonly Color _originalColor; private readonly Color _newColor; private readonly bool _isDisplayed; private readonly bool _isReadFromSettings; public UserMarkupProperties(Color originalColor, Color newColor, bool isReadFromSettings, bool isDisplayed) { _originalColor = originalColor; _newColor = newColor; _isReadFromSettings = isReadFromSettings; _isDisplayed = isDisplayed; } public Color Color { get { return _newColor; } } public Color OriginalColor { get { return _originalColor; } } public bool IsReadFromSettings { get { return _isReadFromSettings; } } public bool IsDisplayed { get { return _isDisplayed; } } public bool HasColorChanges { get { return _originalColor != _newColor; } } } #endregion public Color DefaultMarkupColor { get { return _settings.DefaultMarkupColor; } set { if (_settings.DefaultMarkupColor != value) { _settings.DefaultMarkupColor = value; Modified = true; NotifyPropertyChanged("DefaultMarkupColor"); UpdateDisplayedImages(null); } } } public bool UseRandomDefaultMarkupColor { get { return _settings.UseRandomDefaultMarkupColor; } set { if (_settings.UseRandomDefaultMarkupColor != value) { _settings.UseRandomDefaultMarkupColor = value; Modified = true; NotifyPropertyChanged("UseRandomDefaultMarkupColor"); UpdateDisplayedImages(null); } } } public Color[] GetSavedColors() { var savedColors = new HashSet<Color>(); foreach (var loginNameMarkupColor in AimSettings.Default.LoginNameMarkupColors) { savedColors.Add(loginNameMarkupColor.Value); } var colors = new Color[savedColors.Count]; savedColors.CopyTo(colors); return colors; } public IDictionary<string, UserMarkupProperties> AvailableUserMarkupProperties { get { return _userMarkupPropertiesDictionary; } } public void AddLoginNameMarkupColor(out string loginName, out Color markupColor) { const string newuser = "newuser"; var i = 0; while (_userMarkupPropertiesDictionary.ContainsKey(newuser + i)) i++; loginName = newuser + i; markupColor = GetLoginNameMarkupColor(loginName); SetLoginNameMarkupColor(loginName, markupColor); } public UserMarkupProperties RemoveLoginNameMarkupColor(string loginName) { UserMarkupProperties newUserMarkupProperties = null; loginName = (loginName ?? "").ToLowerInvariant(); if (_userMarkupPropertiesDictionary.ContainsKey(loginName)) { var oldUserMarkupProperties = _userMarkupPropertiesDictionary[loginName]; _userMarkupPropertiesDictionary.Remove(loginName); Modified = true; } return newUserMarkupProperties; } public Color GetLoginNameMarkupColor(string loginName) { var markupColor = _settings.DefaultMarkupColor; loginName = (loginName ?? "").Trim().ToLower(); if (_userMarkupPropertiesDictionary.ContainsKey(loginName)) markupColor = _userMarkupPropertiesDictionary[loginName].Color; else { if (_settings.UseRandomDefaultMarkupColor) markupColor = AimSettings.CreateColorFromStringHash(loginName); } return markupColor; } public void SetLoginNameMarkupColor(string loginName, Color color) { loginName = (loginName ?? "").Trim().ToLower(); if (_userMarkupPropertiesDictionary.ContainsKey(loginName)) { if (_userMarkupPropertiesDictionary[loginName].Color == color) return; var markupProperties = _userMarkupPropertiesDictionary[loginName]; _userMarkupPropertiesDictionary[loginName] = new UserMarkupProperties(markupProperties.OriginalColor, color, markupProperties.IsReadFromSettings, markupProperties.IsDisplayed); } else { _userMarkupPropertiesDictionary[loginName] = new UserMarkupProperties(color, color, true, false); } Modified = true; } public void SetDefaultLoginNameMarkupColor(string loginName) { loginName = (loginName ?? "").Trim().ToLower(); var color = _settings.GetAimGraphicDefaultColorForUser(loginName); SetLoginNameMarkupColor(loginName, color); } public void UpdateLoginName(string oldLoginName, string newLoginName) { Color color; oldLoginName = (oldLoginName ?? "").Trim().ToLower(); if (_userMarkupPropertiesDictionary.ContainsKey(oldLoginName)) { color = _userMarkupPropertiesDictionary[oldLoginName].Color; _userMarkupPropertiesDictionary.Remove(oldLoginName); Modified = true; } else { color = GetLoginNameMarkupColor(newLoginName); } SetLoginNameMarkupColor(newLoginName, color); } public override void Start() { base.Start(); _settings = AimSettings.Default; _defaultMarkupColor = _settings.DefaultMarkupColor; _loginNameMarkupColorsOriginalSettings = new XmlSerializableStringToColorDictionary(_settings.LoginNameMarkupColors); _useRandomDefaultMarkupColor = _settings.UseRandomDefaultMarkupColor; InitUserMarkupProperties(); _userMarkupPropertiesDictionary.ItemAdded += OnUserMarkupPropertiesChanged; _userMarkupPropertiesDictionary.ItemChanged += OnUserMarkupPropertiesChanged; _userMarkupPropertiesDictionary.ItemRemoved += OnUserMarkupPropertiesChanged; _settings.LoginNameMarkupColors = GetNewUserColorSettings(); } public override void Save() { _settings.LoginNameMarkupColors = GetNewUserColorSettings(false); _settings.Save(); _defaultMarkupColor = _settings.DefaultMarkupColor; _loginNameMarkupColorsOriginalSettings = new XmlSerializableStringToColorDictionary(_settings.LoginNameMarkupColors); _useRandomDefaultMarkupColor = _settings.UseRandomDefaultMarkupColor; _userMarkupPropertiesDictionary.ItemAdded -= OnUserMarkupPropertiesChanged; _userMarkupPropertiesDictionary.ItemChanged -= OnUserMarkupPropertiesChanged; _userMarkupPropertiesDictionary.ItemRemoved -= OnUserMarkupPropertiesChanged; _userMarkupPropertiesDictionary.Clear(); } public override void Stop() { _settings.LoginNameMarkupColors = _loginNameMarkupColorsOriginalSettings; _settings.DefaultMarkupColor = _defaultMarkupColor; _settings.UseRandomDefaultMarkupColor = _useRandomDefaultMarkupColor; UpdateDisplayedImages(null); _settings = null; base.Stop(); } private void InitUserMarkupProperties() { _userMarkupPropertiesDictionary.Clear(); var displayedUserColors = GetDisplayedUsersAndMarkupColors(); foreach (var originalUserSetting in _loginNameMarkupColorsOriginalSettings) { if (displayedUserColors.ContainsKey(originalUserSetting.Key)) { _userMarkupPropertiesDictionary[originalUserSetting.Key] = new UserMarkupProperties(displayedUserColors[originalUserSetting.Key], displayedUserColors[originalUserSetting.Key], true, true); displayedUserColors.Remove(originalUserSetting.Key); } else _userMarkupPropertiesDictionary[originalUserSetting.Key] = new UserMarkupProperties(originalUserSetting.Value, originalUserSetting.Value, true, false); } foreach (var displayedUserColor in displayedUserColors) { _userMarkupPropertiesDictionary[displayedUserColor.Key] = new UserMarkupProperties(displayedUserColor.Value, displayedUserColor.Value, false, true); } displayedUserColors.Clear(); } private XmlSerializableStringToColorDictionary GetNewUserColorSettings() { return GetNewUserColorSettings(true); } private XmlSerializableStringToColorDictionary GetNewUserColorSettings(bool includeDisplayedDefaultColor) { var newUserColorSettings = new XmlSerializableStringToColorDictionary(); foreach (var userMarkupProperty in _userMarkupPropertiesDictionary) { if (includeDisplayedDefaultColor) { if (userMarkupProperty.Value.IsDisplayed || userMarkupProperty.Value.IsReadFromSettings || userMarkupProperty.Value.HasColorChanges) newUserColorSettings[userMarkupProperty.Key] = userMarkupProperty.Value.Color; } else { if (userMarkupProperty.Value.IsReadFromSettings || userMarkupProperty.Value.HasColorChanges || (userMarkupProperty.Value.IsDisplayed && userMarkupProperty.Value.Color != DefaultMarkupColor)) newUserColorSettings[userMarkupProperty.Key] = userMarkupProperty.Value.Color; } } return newUserColorSettings; } private void OnUserMarkupPropertiesChanged(object sender, DictionaryEventArgs<string, UserMarkupProperties> e) { _settings.LoginNameMarkupColors = GetNewUserColorSettings(); if (!_userMarkupPropertiesDictionary.ContainsKey(e.Key)) UpdateDisplayedImages(null); else if (_userMarkupPropertiesDictionary[e.Key].IsDisplayed) UpdateDisplayedImages(e.Key); } private static Dictionary<string, Color> GetDisplayedUsersAndMarkupColors() { var displayedUserColors = new Dictionary<string, Color>(); var imageViewer = ImageViewerComponent.GetAsImageViewer(Application.ActiveDesktopWindow.ActiveWorkspace); if (imageViewer != null) { foreach (ImageBox imageBox in imageViewer.PhysicalWorkspace.ImageBoxes) { foreach (Tile tile in imageBox.Tiles) { var graphicsProvider = tile.PresentationImage as IOverlayGraphicsProvider; if (graphicsProvider != null) { foreach (var graphic in graphicsProvider.OverlayGraphics) { var aimGraphic = graphic as AimGraphic; if (aimGraphic != null) { if (!displayedUserColors.ContainsKey(aimGraphic.UserLoginName)) displayedUserColors[aimGraphic.UserLoginName] = aimGraphic.Color; } } } } } } return displayedUserColors; } private static void UpdateDisplayedImages(string loginName) { foreach (var desktopWindow in Application.DesktopWindows) { foreach (var workspace in desktopWindow.Workspaces) { var imageViewer = ImageViewerComponent.GetAsImageViewer(workspace); if (imageViewer != null) { foreach (ImageBox imageBox in imageViewer.PhysicalWorkspace.ImageBoxes) { foreach (Tile tile in imageBox.Tiles) { var graphicsProvider = tile.PresentationImage as IOverlayGraphicsProvider; if (graphicsProvider != null) { foreach (var graphic in graphicsProvider.OverlayGraphics) { var aimGraphic = graphic as AimGraphic; if (aimGraphic != null && (string.IsNullOrEmpty(loginName) || string.Equals(loginName, aimGraphic.UserLoginName, StringComparison.InvariantCultureIgnoreCase))) { tile.PresentationImage.Draw(); break; } } } } } } } } } } }
using System; using UnityEngine; namespace UnitySampleAssets.ImageEffects { public enum Dof34QualitySetting { OnlyBackground = 1, BackgroundAndForeground = 2, } public enum DofResolution { High = 2, Medium = 3, Low = 4, } public enum DofBlurriness { Low = 1, High = 2, VeryHigh = 4, } [Flags] public enum BokehDestination { Background = 0x1, Foreground = 0x2, BackgroundAndForeground = 0x3, } [ExecuteInEditMode] [RequireComponent(typeof (Camera))] [AddComponentMenu("Image Effects/Depth of Field (3.4)")] public class DepthOfField34 : PostEffectsBase { private static int SMOOTH_DOWNSAMPLE_PASS = 6; private static float BOKEH_EXTRA_BLUR = 2.0f; public Dof34QualitySetting quality = Dof34QualitySetting.OnlyBackground; public DofResolution resolution = DofResolution.Low; public bool simpleTweakMode = true; public float focalPoint = 1.0f; public float smoothness = 0.5f; public float focalZDistance = 0.0f; public float focalZStartCurve = 1.0f; public float focalZEndCurve = 1.0f; private float focalStartCurve = 2.0f; private float focalEndCurve = 2.0f; private float focalDistance01 = 0.1f; public Transform objectFocus = null; public float focalSize = 0.0f; public DofBlurriness bluriness = DofBlurriness.High; public float maxBlurSpread = 1.75f; public float foregroundBlurExtrude = 1.15f; public Shader dofBlurShader; private Material dofBlurMaterial = null; public Shader dofShader; private Material dofMaterial = null; public bool visualize = false; public BokehDestination bokehDestination = BokehDestination.Background; private float widthOverHeight = 1.25f; private float oneOverBaseSize = 1.0f/512.0f; public bool bokeh = false; public bool bokehSupport = true; public Shader bokehShader; public Texture2D bokehTexture; public float bokehScale = 2.4f; public float bokehIntensity = 0.15f; public float bokehThreshholdContrast = 0.1f; public float bokehThreshholdLuminance = 0.55f; public int bokehDownsample = 1; private Material bokehMaterial; private void CreateMaterials() { dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial); dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial); } protected override bool CheckResources() { CheckSupport(true); dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial); dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial); if (!isSupported) ReportAutoDisable(); return isSupported; } private void OnDisable() { Quads.Cleanup(); } private void OnEnable() { camera.depthTextureMode |= DepthTextureMode.Depth; } private float FocalDistance01(float worldDist) { return camera.WorldToViewportPoint((worldDist - camera.nearClipPlane)*camera.transform.forward + camera.transform.position).z/(camera.farClipPlane - camera.nearClipPlane); } private int GetDividerBasedOnQuality() { int divider = 1; if (resolution == DofResolution.Medium) divider = 2; else if (resolution == DofResolution.Low) divider = 2; return divider; } private int GetLowResolutionDividerBasedOnQuality(int baseDivider) { int lowTexDivider = baseDivider; if (resolution == DofResolution.High) lowTexDivider *= 2; if (resolution == DofResolution.Low) lowTexDivider *= 2; return lowTexDivider; } private RenderTexture foregroundTexture = null; private RenderTexture mediumRezWorkTexture = null; private RenderTexture finalDefocus = null; private RenderTexture lowRezWorkTexture = null; private RenderTexture bokehSource = null; private RenderTexture bokehSource2 = null; private void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) { Graphics.Blit(source, destination); } if (smoothness < 0.1f) smoothness = 0.1f; // update needed focal & rt size parameter bokeh = bokeh && bokehSupport; float bokehBlurAmplifier = bokeh ? BOKEH_EXTRA_BLUR : 1.0f; bool blurForeground = quality > Dof34QualitySetting.OnlyBackground; float focal01Size = focalSize/(camera.farClipPlane - camera.nearClipPlane); ; if (simpleTweakMode) { focalDistance01 = objectFocus ? (camera.WorldToViewportPoint(objectFocus.position)).z/(camera.farClipPlane) : FocalDistance01(focalPoint); focalStartCurve = focalDistance01*smoothness; focalEndCurve = focalStartCurve; blurForeground = blurForeground && (focalPoint > (camera.nearClipPlane + Mathf.Epsilon)); } else { if (objectFocus) { var vpPoint = camera.WorldToViewportPoint(objectFocus.position); vpPoint.z = (vpPoint.z)/(camera.farClipPlane); focalDistance01 = vpPoint.z; } else focalDistance01 = FocalDistance01(focalZDistance); focalStartCurve = focalZStartCurve; focalEndCurve = focalZEndCurve; blurForeground = blurForeground && (focalPoint > (camera.nearClipPlane + Mathf.Epsilon)); } widthOverHeight = (1.0f*source.width)/(1.0f*source.height); oneOverBaseSize = 1.0f/512.0f; dofMaterial.SetFloat("_ForegroundBlurExtrude", foregroundBlurExtrude); dofMaterial.SetVector("_CurveParams", new Vector4(simpleTweakMode ? 1.0f/focalStartCurve : focalStartCurve, simpleTweakMode ? 1.0f/focalEndCurve : focalEndCurve, focal01Size*0.5f, focalDistance01)); dofMaterial.SetVector("_InvRenderTargetSize", new Vector4(1.0f/(1.0f*source.width), 1.0f/(1.0f*source.height), 0.0f, 0.0f)); int divider = GetDividerBasedOnQuality(); int lowTexDivider = GetLowResolutionDividerBasedOnQuality(divider); AllocateTextures(blurForeground, source, divider, lowTexDivider); // WRITE COC to alpha channel // source is only being bound to detect y texcoord flip Graphics.Blit(source, source, dofMaterial, 3); // better DOWNSAMPLE (could actually be weighted for higher quality) Downsample(source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later Blur(mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); if ((bokeh) && ((BokehDestination.Background & bokehDestination) != 0)) { dofMaterial.SetVector("_Threshhold", new Vector4(bokehThreshholdContrast, bokehThreshholdLuminance, 0.95f, 0.0f)); // add and mark the parts that should end up as bokeh shapes Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove those parts (maybe even a little tittle bittle more) from the regurlarly blurred buffer //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10); // maybe you want to reblur the small blur ... but not really needed. //Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); // bigger BLUR Blur(lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread*bokehBlurAmplifier); } else { // bigger BLUR Downsample(mediumRezWorkTexture, lowRezWorkTexture); Blur(lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread); } dofBlurMaterial.SetTexture("_TapLow", lowRezWorkTexture); dofBlurMaterial.SetTexture("_TapMedium", mediumRezWorkTexture); Graphics.Blit(null, finalDefocus, dofBlurMaterial, 3); // we are only adding bokeh now if the background is the only part we have to deal with if ((bokeh) && ((BokehDestination.Background & bokehDestination) != 0)) AddBokeh(bokehSource2, bokehSource, finalDefocus); dofMaterial.SetTexture("_TapLowBackground", finalDefocus); dofMaterial.SetTexture("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization // FINAL DEFOCUS (background) Graphics.Blit(source, blurForeground ? foregroundTexture : destination, dofMaterial, visualize ? 2 : 0); // FINAL DEFOCUS (foreground) if (blurForeground) { // WRITE COC to alpha channel Graphics.Blit(foregroundTexture, source, dofMaterial, 5); // DOWNSAMPLE (unweighted) Downsample(source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later BlurFg(mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 2, maxBlurSpread); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) { dofMaterial.SetVector("_Threshhold", new Vector4(bokehThreshholdContrast*0.5f, bokehThreshholdLuminance, 0.0f, 0.0f)); // add and mark the parts that should end up as bokeh shapes Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove the parts (maybe even a little tittle bittle more) that will end up in bokeh space //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10); // big BLUR BlurFg(lowRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread*bokehBlurAmplifier); } else { // big BLUR BlurFg(mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread); } // simple upsample once Graphics.Blit(lowRezWorkTexture, finalDefocus); dofMaterial.SetTexture("_TapLowForeground", finalDefocus); Graphics.Blit(source, destination, dofMaterial, visualize ? 1 : 4); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) AddBokeh(bokehSource2, bokehSource, destination); } ReleaseTextures(); } private void Blur(RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height); if (iterations > (DofBlurriness) 1) { BlurHex(from, to, blurPass, spread, tmp); if (iterations > (DofBlurriness) 2) { dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } } else { dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } RenderTexture.ReleaseTemporary(tmp); } private void BlurFg(RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { // we want a nice, big coc, hence we need to tap once from this (higher resolution) texture dofBlurMaterial.SetTexture("_TapHigh", from); RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height); if (iterations > (DofBlurriness) 1) { BlurHex(from, to, blurPass, spread, tmp); if (iterations > (DofBlurriness) 2) { dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } } else { dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } RenderTexture.ReleaseTemporary(tmp); } private void BlurHex(RenderTexture from, RenderTexture to, int blurPass, float spread, RenderTexture tmp) { dofBlurMaterial.SetVector("offsets", new Vector4(0.0f, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector("offsets", new Vector4(spread/widthOverHeight*oneOverBaseSize, -spread*oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } private void Downsample(RenderTexture from, RenderTexture to) { dofMaterial.SetVector("_InvRenderTargetSize", new Vector4(1.0f/(1.0f*to.width), 1.0f/(1.0f*to.height), 0.0f, 0.0f)); Graphics.Blit(from, to, dofMaterial, SMOOTH_DOWNSAMPLE_PASS); } private void AddBokeh(RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget) { if (bokehMaterial) { Mesh[] meshes = Quads.GetMeshes(tempTex.width, tempTex.height); // quads: exchanging more triangles with less overdraw RenderTexture.active = tempTex; GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); GL.PushMatrix(); GL.LoadIdentity(); // point filter mode is important, otherwise we get bokeh shape & size artefacts bokehInfo.filterMode = FilterMode.Point; float arW = (bokehInfo.width*1.0f)/(bokehInfo.height*1.0f); float sc = 2.0f/(1.0f*bokehInfo.width); sc += bokehScale*maxBlurSpread*BOKEH_EXTRA_BLUR*oneOverBaseSize; bokehMaterial.SetTexture("_Source", bokehInfo); bokehMaterial.SetTexture("_MainTex", bokehTexture); bokehMaterial.SetVector("_ArScale", new Vector4(sc, sc*arW, 0.5f, 0.5f*arW)); bokehMaterial.SetFloat("_Intensity", bokehIntensity); bokehMaterial.SetPass(0); foreach (var m in meshes) if (m) Graphics.DrawMeshNow(m, Matrix4x4.identity); GL.PopMatrix(); Graphics.Blit(tempTex, finalTarget, dofMaterial, 8); // important to set back as we sample from this later on bokehInfo.filterMode = FilterMode.Bilinear; } } private void ReleaseTextures() { if (foregroundTexture) RenderTexture.ReleaseTemporary(foregroundTexture); if (finalDefocus) RenderTexture.ReleaseTemporary(finalDefocus); if (mediumRezWorkTexture) RenderTexture.ReleaseTemporary(mediumRezWorkTexture); if (lowRezWorkTexture) RenderTexture.ReleaseTemporary(lowRezWorkTexture); if (bokehSource) RenderTexture.ReleaseTemporary(bokehSource); if (bokehSource2) RenderTexture.ReleaseTemporary(bokehSource2); } private void AllocateTextures(bool blurForeground, RenderTexture source, int divider, int lowTexDivider) { foregroundTexture = null; if (blurForeground) foregroundTexture = RenderTexture.GetTemporary(source.width, source.height, 0); mediumRezWorkTexture = RenderTexture.GetTemporary(source.width/divider, source.height/divider, 0); finalDefocus = RenderTexture.GetTemporary(source.width/divider, source.height/divider, 0); lowRezWorkTexture = RenderTexture.GetTemporary(source.width/lowTexDivider, source.height/lowTexDivider, 0); bokehSource = null; bokehSource2 = null; if (bokeh) { bokehSource = RenderTexture.GetTemporary(source.width/(lowTexDivider*bokehDownsample), source.height/(lowTexDivider*bokehDownsample), 0, RenderTextureFormat.ARGBHalf); bokehSource2 = RenderTexture.GetTemporary(source.width/(lowTexDivider*bokehDownsample), source.height/(lowTexDivider*bokehDownsample), 0, RenderTextureFormat.ARGBHalf); bokehSource.filterMode = FilterMode.Bilinear; bokehSource2.filterMode = FilterMode.Bilinear; RenderTexture.active = bokehSource2; GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); } // to make sure: always use bilinear filter setting source.filterMode = FilterMode.Bilinear; finalDefocus.filterMode = FilterMode.Bilinear; mediumRezWorkTexture.filterMode = FilterMode.Bilinear; lowRezWorkTexture.filterMode = FilterMode.Bilinear; if (foregroundTexture) foregroundTexture.filterMode = FilterMode.Bilinear; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // Based on W3C png specification: http://www.w3.org/TR/2003/REC-PNG-20031110/#11PLTE // The Initial Developer of this Original Code is Ted Dunsford. Created 2/18/2010 1:21:47 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; namespace DotSpatial.Data { /// <summary> /// mw.png provides read-write support for a png format that also can provide overviews etc. /// This cannot work with any possible png file, but rather provides at least one common /// format that can be used natively for large files that is better at compression than /// just storing the values directly. /// http://www.w3.org/TR/2003/REC-PNG-20031110/#11PLTE /// </summary> public class MwPng { #region Private Variables #endregion #region Methods /// <summary> /// For testing, see if we can write a png ourself that can be opened by .Net png. /// </summary> /// <param name="image">The image to write to png format</param> /// <param name="fileName">The string fileName</param> public void Write(Bitmap image, string fileName) { if (File.Exists(fileName)) File.Delete(fileName); Stream f = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1000000); WriteSignature(f); PngHeader header = new PngHeader(image.Width, image.Height); header.Write(f); WriteSrgb(f); byte[] refImage = GetBytesFromImage(image); byte[] filtered = Filter(refImage, 0, refImage.Length, image.Width * 4); byte[] compressed = Deflate.Compress(filtered); WriteIDat(f, compressed); WriteEnd(f); f.Flush(); f.Close(); } /// <summary> /// Reads a fileName into the specified bitmap. /// </summary> /// <param name="fileName"></param> /// <returns></returns> /// <exception cref="PngInvalidSignatureException">If the file signature doesn't match the png file signature</exception> public Bitmap Read(string fileName) { Stream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1000000); byte[] signature = new byte[8]; f.Read(signature, 0, 8); if (!SignatureIsValid(signature)) { throw new PngInvalidSignatureException(); } f.Close(); return new Bitmap(10, 10); } ///<summary> ///</summary> ///<param name="signature"></param> ///<returns></returns> public static bool SignatureIsValid(byte[] signature) { byte[] test = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }; for (int i = 0; i < 8; i++) { if (signature[i] != test[i]) return false; } return true; } private static void WriteIDat(Stream f, byte[] data) { f.Write(ToBytesAsUInt32((uint)data.Length), 0, 4); byte[] tag = new byte[] { 73, 68, 65, 84 }; f.Write(tag, 0, 4); // IDAT f.Write(data, 0, data.Length); byte[] combined = new byte[data.Length + 4]; Array.Copy(tag, 0, combined, 0, 4); Array.Copy(data, 0, combined, 4, data.Length); f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(combined)), 0, 4); //// The IDAT chunks can be no more than 32768, but can in fact be smaller than this. //int numBlocks = (int) Math.Ceiling(data.Length/(double) 32768); //for (int block = 0; block < numBlocks; block++) //{ // int bs = 32768; // if (block == numBlocks - 1) bs = data.Length - block*32768; // f.Write(ToBytes((uint)bs), 0, 4); // length // f.Write(new byte[]{73, 68, 65, 84}, 0, 4); // IDAT // f.Write(data, block * 32768, bs); // Data Content // f.Write(ToBytes(Crc32.ComputeChecksum(data)), 0, 4); // CRC //} } /// <summary> /// Writes an in Big-endian Uint format. /// </summary> /// <param name="value"></param> public static byte[] ToBytesAsUInt32(long value) { uint temp = Convert.ToUInt32(value); byte[] arr = BitConverter.GetBytes(temp); if (BitConverter.IsLittleEndian) Array.Reverse(arr); return arr; } private static byte[] GetBytesFromImage(Bitmap image) { BitmapData bd = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); int len = image.Width * image.Height * 4; byte[] refImage = new byte[len]; Marshal.Copy(bd.Scan0, refImage, 0, len); image.UnlockBits(bd); return refImage; } private static void WriteSignature(Stream f) { f.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, 0, 8); } private static void WriteSrgb(Stream f) { f.Write(ToBytesAsUInt32(1), 0, 4); byte[] vals = new byte[] { 115, 82, 71, 66, 0 }; //sRGB and the value of 0 f.Write(vals, 0, 5); f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4); } private static void WriteEnd(Stream f) { f.Write(BitConverter.GetBytes(0), 0, 4); byte[] vals = new byte[] { 73, 69, 78, 68 }; // IEND f.Write(vals, 0, 4); f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4); } /// <summary> /// Many rows may be evaluated by this process, but the first value in the array should /// be aligned with the left side of the image. /// </summary> /// <param name="refData">The original bytes to apply the PaethPredictor to.</param> /// <param name="offset">The integer offset in the array where the filter should begin application. If this is 0, then /// it assumes that there is no previous scan-line to work with.</param> /// <param name="length">The number of bytes to filter, starting at the specified offset. This should be evenly divisible by the width.</param> /// <param name="width">The integer width of a scan-line for grabbing the c and b bytes</param> /// <returns>The entire length of bytes starting with the specified offset</returns> public static byte[] Filter(byte[] refData, int offset, int length, int width) { // the 'B' and 'C' values of the first row are considered to be 0. // the 'A' value of the first column is considered to be 0. if (refData.Length - offset < length) { throw new PngInsuficientLengthException(length, refData.Length, offset); } int numrows = length / width; // The output also consists of a byte before each line that specifies the Paeth prediction filter is being used byte[] result = new byte[numrows + length]; int source = offset; int dest = 0; for (int row = 0; row < numrows; row++) { result[dest] = 4; dest++; for (int col = 0; col < width; col++) { byte a = (col == 0) ? (byte)0 : refData[source - 1]; byte b = (row == 0 || col == 0) ? (byte)0 : refData[source - width - 1]; byte c = (row == 0) ? (byte)0 : refData[source - width]; result[dest] = (byte)((refData[source] - PaethPredictor(a, b, c)) % 256); source++; dest++; } } return result; } /// <summary> /// Unfilters the data in order to reconstruct the original values. /// </summary> /// <param name="filterStream">The filtered but decompressed bytes</param> /// <param name="offset">the integer offset where reconstruction should begin</param> /// <param name="length">The integer length of bytes to deconstruct</param> /// <param name="width">The integer width of a scan-line in bytes (not counting any filter type bytes.</param> /// <returns></returns> /// <exception cref="PngInsuficientLengthException"></exception> public byte[] UnFilter(byte[] filterStream, int offset, int length, int width) { // the 'B' and 'C' values of the first row are considered to be 0. // the 'A' value of the first column is considered to be 0. if (filterStream.Length - offset < length) { throw new PngInsuficientLengthException(length, filterStream.Length, offset); } int numrows = length / width; // The output also consists of a byte before each line that specifies the Paeth prediction filter is being used byte[] result = new byte[length - numrows]; int source = offset; int dest = 0; for (int row = 0; row < numrows; row++) { if (filterStream[source] == 0) { source++; // No filtering Array.Copy(filterStream, source, result, dest, width); source += width; dest += width; } else if (filterStream[source] == 1) { source++; for (int col = 0; col < width; col++) { byte a = (col == 0) ? (byte)0 : result[dest - 1]; result[dest] = (byte)((filterStream[dest] + a) % 256); source++; dest++; } } else if (filterStream[source] == 2) { source++; for (int col = 0; col < width; col++) { byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1]; result[dest] = (byte)((filterStream[dest] + b) % 256); source++; dest++; } } else if (filterStream[source] == 3) { source++; for (int col = 0; col < width; col++) { byte a = (col == 0) ? (byte)0 : result[dest - 1]; byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1]; result[dest] = (byte)((filterStream[dest] + (a + b) / 2) % 256); // integer division automatically does "floor" source++; dest++; } } else if (filterStream[source] == 4) { source++; for (int col = 0; col < width; col++) { byte a = (col == 0) ? (byte)0 : result[dest - 1]; byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1]; byte c = (row == 0) ? (byte)0 : result[dest - width]; result[dest] = (byte)((filterStream[dest] + PaethPredictor(a, b, c)) % 256); source++; dest++; } } } return result; } /// <summary> /// B C - For the current pixel X, use the best fit from B, C or A to predict X. /// A X /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <returns></returns> private static byte PaethPredictor(byte a, byte b, byte c) { byte pR; int p = a + b - c; int pa = Math.Abs(p - a); int pb = Math.Abs(p - b); int pc = Math.Abs(p - c); if (pa <= pb && pa <= pc) pR = a; else if (pb <= pc) pR = b; else pR = c; return pR; } #endregion #region Properties #endregion } }
using System; using UIKit; using CoreGraphics; using Foundation; using System.Collections.Generic; namespace JVMenuPopover { public class JVMenuPopoverView : UIView { #region Fields private UITableView _tableView; private string cellIdentifier = "Cell"; private List<JVMenuItem> _MenuItems; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JVMenuPopover.JVMenuPopoverView"/> class. /// </summary> public JVMenuPopoverView(List<JVMenuItem> items) : base() { _MenuItems = items; Setup(); } /// <summary> /// Initializes a new instance of the <see cref="JVMenuPopover.JVMenuPopoverView"/> class. /// </summary> /// <param name="frame">Frame.</param> public JVMenuPopoverView(List<JVMenuItem> items, CGRect frame) : base(frame) { _MenuItems = items; Setup(); } #endregion #region Properties /// <summary> /// Gets or sets the delegate. /// </summary> /// <value>The delegate.</value> internal IJVMenuPopoverDelegate Delegate { get; set;} /// <summary> /// Gets or sets the table view. /// </summary> /// <value>The table view.</value> public UITableView TableView { get { if(_tableView == null) { _tableView = new UITableView(new CGRect(0, 70, this.Frame.Size.Width, this.Frame.Size.Height),UITableViewStyle.Plain); //_tableView = new UITableView(new CGRect(0, 70, 320, 480),UITableViewStyle.Plain); _tableView.BackgroundColor = UIColor.Clear; _tableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; if (UIDevice.CurrentDevice.CheckSystemVersion (8,0)) { _tableView.LayoutMargins = UIEdgeInsets.Zero; } _tableView.Bounces = false; _tableView.ScrollEnabled = false; _tableView.WeakDelegate = this; _tableView.WeakDataSource = this; _tableView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; } return _tableView; } } /// <summary> /// Gets or sets the size of the screen. /// </summary> /// <value>The size of the screen.</value> private CGSize ScreenSize { get; set;} /// <summary> /// Gets or sets a value indicating whether this <see cref="JVMenuPopover.JVMenuPopoverView"/> done cell animations. /// </summary> /// <value><c>true</c> if done cell animations; otherwise, <c>false</c>.</value> private Boolean DoneCellAnimations { get; set;} /// <summary> /// Gets the menu items. /// </summary> /// <value>The menu items.</value> private List<JVMenuItem> MenuItems { get { if (_MenuItems == null) _MenuItems = new List<JVMenuItem>(); return _MenuItems; } } #endregion #region Methods /// <summary> /// Setup this instance. /// </summary> private void Setup() { if(this.Frame.Size.Width == 0) { this.ScreenSize = JVMenuHelper.GetScreenSize(); this.Frame = new CGRect(0, 0, ScreenSize.Width, ScreenSize.Height); } this.BackgroundColor = UIColor.Black.ColorWithAlpha(0.5f); this.Add(TableView); } /// <summary> /// Wills the move to window. /// </summary> /// <param name="newWindow">New window.</param> public override void WillMoveToWindow(UIWindow newWindow) { DoneCellAnimations = false; base.WillMoveToWindow(newWindow); } #endregion #region TableView Datasource and Delegate functions [Export("tableView:didEndDisplayingCell:forRowAtIndexPath:")] private void DidEndDisplayingCell(UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { // // // do something after display } [Export("tableView:willDisplayCell:forRowAtIndexPath:")] private void WillDisplayCell(UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { if (this.DoneCellAnimations) return; var oldFrame = cell.Frame; var newFrame = new CGRect(-cell.Frame.Size.Width, cell.Frame.Top, 0, cell.Frame.Size.Height); var velocity = cell.Frame.Size.Width/100; cell.Transform = CGAffineTransform.Scale(CGAffineTransform.MakeIdentity(), 0.95f, 0.0001f); cell.Frame = newFrame; UIView.AnimateNotify(0.3f/1.5f,0.05f * indexPath.Row, 0.67f, velocity,UIViewAnimationOptions.TransitionNone,()=> { cell.Frame = oldFrame; cell.Transform = CGAffineTransform.Scale(CGAffineTransform.MakeIdentity(), 1.0f, 1.0f); },(finished)=> { var rows = TableView.NumberOfRowsInSection(0); if (rows == indexPath.Row+1) DoneCellAnimations = true; }); } [Export("tableView:cellForRowAtIndexPath:")] private UITableViewCell CellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell(cellIdentifier); if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Default,cellIdentifier); if (TableView.RespondsToSelector(new ObjCRuntime.Selector("setLayoutMargins:"))) TableView.LayoutMargins = UIEdgeInsets.Zero; if (cell.RespondsToSelector(new ObjCRuntime.Selector("setSeparatorInset:"))) cell.SeparatorInset = UIEdgeInsets.Zero; if (cell.RespondsToSelector(new ObjCRuntime.Selector("setPreservesSuperviewLayoutMargins:"))) cell.PreservesSuperviewLayoutMargins = false; if (cell.RespondsToSelector(new ObjCRuntime.Selector("setLayoutMargins:"))) cell.LayoutMargins = UIEdgeInsets.Zero; // setups cell cell.SelectionStyle = UITableViewCellSelectionStyle.None; cell.BackgroundColor = UIColor.Clear; cell.TextLabel.BackgroundColor = UIColor.Clear; cell.TextLabel.Font = UIFont.FromName(JVMenuPopoverConfig.SharedInstance.FontName,JVMenuPopoverConfig.SharedInstance.FontSize); cell.TextLabel.TextColor = JVMenuPopoverConfig.SharedInstance.TintColor; cell.TextLabel.TextAlignment = UITextAlignment.Left; var item = MenuItems[indexPath.Row]; cell.ImageView.Image = item.Icon; cell.ImageView.TintColor = JVMenuPopoverConfig.SharedInstance.TintColor; cell.TextLabel.Text = item.Title; return cell; } [Export("tableView:didSelectRowAtIndexPath:")] private void DidSelectRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow(indexPath,true); if (Delegate != null) { Delegate.MenuPopOverRowSelected(this,indexPath); } } [Export("tableView:numberOfRowsInSection:")] private nint NumberOfRowsInSection(UITableView tableView, nint section) { return MenuItems.Count; } [Export("tableView:heightForRowAtIndexPath:")] private nfloat HeightForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) { return (nfloat)JVMenuPopoverConfig.SharedInstance.RowHeight; } [Export("tableView:viewForHeaderInSection:")] private UIView ViewForHeaderInSection(UITableView tableView, nint section) { return new UIView(CGRect.Empty); } [Export("tableView:heightForHeaderInSection:")] private nfloat HeightForHeaderInSection(UITableView tableView, nint section) { return 0; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal readonly partial struct ExpressionBinder { //////////////////////////////////////////////////////////////////////////////// // This table is used to implement the last set of 'better' conversion rules // when there are no implicit conversions between T1(down) and T2 (across) // Use all the simple types plus 1 more for Object // See CLR section 7.4.1.3 private static readonly byte[][] s_betterConversionTable = { // BYTE SHORT INT LONG FLOAT DOUBLE DECIMAL CHAR BOOL SBYTE USHORT UINT ULONG IPTR UIPTR OBJECT new byte[] /* BYTE*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3}, new byte[] /* SHORT*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3}, new byte[] /* INT*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3}, new byte[] /* LONG*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3}, new byte[] /* FLOAT*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* DOUBLE*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* DECIMAL*/{3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* CHAR*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* BOOL*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* SBYTE*/ {1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3}, new byte[] /* USHORT*/ {3, 2, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3}, new byte[] /* UINT*/ {3, 2, 2, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3}, new byte[] /* ULONG*/ {3, 2, 2, 2, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3}, new byte[] /* IPTR*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* UIPTR*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, new byte[] /* OBJECT*/ {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3} }; private static BetterType WhichMethodIsBetterTieBreaker( CandidateFunctionMember node1, CandidateFunctionMember node2, CType pTypeThrough, ArgInfos args) { MethPropWithInst mpwi1 = node1.mpwi; MethPropWithInst mpwi2 = node2.mpwi; // Same signatures. If they have different lifting numbers, the smaller number wins. // Otherwise, if one is generic and the other isn't then the non-generic wins. // Otherwise, if one is expanded and the other isn't then the non-expanded wins. // Otherwise, if one has fewer modopts than the other then it wins. if (node1.ctypeLift != node2.ctypeLift) { return node1.ctypeLift < node2.ctypeLift ? BetterType.Left : BetterType.Right; } // Non-generic wins. if (mpwi1.TypeArgs.Count != 0) { if (mpwi2.TypeArgs.Count == 0) { return BetterType.Right; } } else if (mpwi2.TypeArgs.Count != 0) { return BetterType.Left; } // Non-expanded wins if (node1.fExpanded) { if (!node2.fExpanded) { return BetterType.Right; } } else if (node2.fExpanded) { return BetterType.Left; } // See if one's parameter types (un-instantiated) are more specific. BetterType nT = CompareTypes( RearrangeNamedArguments(mpwi1.MethProp().Params, mpwi1, pTypeThrough, args), RearrangeNamedArguments(mpwi2.MethProp().Params, mpwi2, pTypeThrough, args)); if (nT == BetterType.Left || nT == BetterType.Right) { return nT; } // Fewer modopts wins. if (mpwi1.MethProp().modOptCount != mpwi2.MethProp().modOptCount) { return mpwi1.MethProp().modOptCount < mpwi2.MethProp().modOptCount ? BetterType.Left : BetterType.Right; } // Bona-fide tie. return BetterType.Neither; } private static BetterType CompareTypes(TypeArray ta1, TypeArray ta2) { if (ta1 == ta2) { return BetterType.Same; } if (ta1.Count != ta2.Count) { // The one with more parameters is more specific. return ta1.Count > ta2.Count ? BetterType.Left : BetterType.Right; } BetterType nTot = BetterType.Neither; for (int i = 0; i < ta1.Count; i++) { CType type1 = ta1[i]; CType type2 = ta2[i]; BetterType nParam = BetterType.Neither; LAgain: if (type1.TypeKind != type2.TypeKind) { if (type1 is TypeParameterType) { nParam = BetterType.Right; } else if (type2 is TypeParameterType) { nParam = BetterType.Left; } } else { switch (type1.TypeKind) { default: Debug.Fail("Bad kind in CompareTypes"); break; case TypeKind.TK_TypeParameterType: break; case TypeKind.TK_PointerType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: type1 = type1.BaseOrParameterOrElementType; type2 = type2.BaseOrParameterOrElementType; goto LAgain; case TypeKind.TK_AggregateType: nParam = CompareTypes(((AggregateType)type1).TypeArgsAll, ((AggregateType)type2).TypeArgsAll); break; } } if (nParam == BetterType.Right || nParam == BetterType.Left) { if (nTot == BetterType.Same || nTot == BetterType.Neither) { nTot = nParam; } else if (nParam != nTot) { return BetterType.Neither; } } } return nTot; } //////////////////////////////////////////////////////////////////////////////// // Find the index of a name on a list. // There is no failure case; we require that the name actually // be on the list private static int FindName(List<Name> names, Name name) { int index = names.IndexOf(name); Debug.Assert(index != -1); return index; } //////////////////////////////////////////////////////////////////////////////// // We need to rearange the method parameters so that the type of any specified named argument // appears in the same place as the named argument. Consider the example below: // Foo(int x = 4, string y = "", long l = 4) // Foo(string y = "", string x="", long l = 5) // and the call site: // Foo(y:"a") // After rearranging the parameter types we will have: // (string, int, long) and (string, string, long) // By rearranging the arguments as such we make sure that any specified named arguments appear in the same position for both // methods and we also maintain the relative order of the other parameters (the type long appears after int in the above example) private static TypeArray RearrangeNamedArguments(TypeArray pta, MethPropWithInst mpwi, CType pTypeThrough, ArgInfos args) { #if DEBUG // We never have a named argument that is in a position in the argument // list past the end of what would be the formal parameter list. for (int i = pta.Count; i < args.carg; i++) { Debug.Assert(!(args.prgexpr[i] is ExprNamedArgumentSpecification)); } #endif // If we've no args we can skip. If the last argument isn't named then either we // have no named arguments, and we can skip, or we have non-trailing named arguments // and we MUST skip! if (args.carg == 0 || !(args.prgexpr[args.carg - 1] is ExprNamedArgumentSpecification)) { return pta; } CType type = pTypeThrough != null ? pTypeThrough : mpwi.GetType(); CType[] typeList = new CType[pta.Count]; MethodOrPropertySymbol methProp = GroupToArgsBinder.FindMostDerivedMethod(mpwi.MethProp(), type); // We initialize the new type array with the parameters for the method. for (int iParam = 0; iParam < pta.Count; iParam++) { typeList[iParam] = pta[iParam]; } var prgexpr = args.prgexpr; // We then go over the specified arguments and put the type for any named argument in the right position in the array. for (int iParam = 0; iParam < args.carg; iParam++) { if (prgexpr[iParam] is ExprNamedArgumentSpecification named) { // We find the index of the type of the argument in the method parameter list and store that in a temp int index = FindName(methProp.ParameterNames, named.Name); CType tempType = pta[index]; // Starting from the current position in the type list up until the location of the type of the optional argument // We shift types by one: // before: (int, string, long) // after: (string, int, long) // We only touch the types between the current position and the position of the type we need to move for (int iShift = iParam; iShift < index; iShift++) { typeList[iShift + 1] = typeList[iShift]; } typeList[iParam] = tempType; } } return TypeArray.Allocate(typeList); } //////////////////////////////////////////////////////////////////////////////// // Determine which method is better for the purposes of overload resolution. // Better means: as least as good in all params, and better in at least one param. // Better w/r to a param means is an ordering, from best down: // 1) same type as argument // 2) implicit conversion from argument to formal type // Because of user defined conversion opers this relation is not transitive. // // If there is a tie because of identical signatures, the tie may be broken by the // following rules: // 1) If one is generic and the other isn't, the non-generic wins. // 2) Otherwise if one is expanded (params) and the other isn't, the non-expanded wins. // 3) Otherwise if one has more specific parameter types (at the declaration) it wins: // This occurs if at least on parameter type is more specific and no parameter type is // less specific. //* A type parameter is less specific than a non-type parameter. //* A constructed type is more specific than another constructed type if at least // one type argument is more specific and no type argument is less specific than // the corresponding type args in the other. // 4) Otherwise if one has more modopts than the other does, the smaller number of modopts wins. // // Returns Left if m1 is better, Right if m2 is better, or Neither/Same private BetterType WhichMethodIsBetter( CandidateFunctionMember node1, CandidateFunctionMember node2, CType pTypeThrough, ArgInfos args) { MethPropWithInst mpwi1 = node1.mpwi; MethPropWithInst mpwi2 = node2.mpwi; // Substitutions should have already been done on these! TypeArray pta1 = RearrangeNamedArguments(node1.@params, mpwi1, pTypeThrough, args); TypeArray pta2 = RearrangeNamedArguments(node2.@params, mpwi2, pTypeThrough, args); // If the parameter types for both candidate methods are identical, // use the tie breaking rules. if (pta1 == pta2) { return WhichMethodIsBetterTieBreaker(node1, node2, pTypeThrough, args); } // Otherwise, do a parameter-by-parameter comparison: // // Given an argument list A with a set of argument expressions {E1, ... En} and // two applicable function members Mp and Mq with parameter types {P1,... Pn} and // {Q1, ... Qn}, Mp is defined to be a better function member than Mq if: //* for each argument the implicit conversion from Ex to Qx is not better than // the implicit conversion from Ex to Px. //* for at least one argument, the conversion from Ex to Px is better than the // conversion from Ex to Qx. BetterType betterMethod = BetterType.Neither; int carg = args.carg; for (int i = 0; i < carg; i++) { Expr arg = args.prgexpr[i]; CType p1 = pta1[i]; CType p2 = pta2[i]; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // We need to consider conversions from the actual runtime type // since we could have private interfaces that we are converting CType argType = arg?.RuntimeObjectActualType ?? args.types[i]; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BetterType betterConversion = WhichConversionIsBetter(argType, p1, p2); if (betterMethod == BetterType.Right) { if (betterConversion == BetterType.Left) { betterMethod = BetterType.Neither; break; } } else if (betterMethod == BetterType.Left) { if (betterConversion == BetterType.Right) { betterMethod = BetterType.Neither; break; } } else { Debug.Assert(betterMethod == BetterType.Neither); if (betterConversion == BetterType.Right || betterConversion == BetterType.Left) { betterMethod = betterConversion; } } } // We may have different sizes if we had optional parameters. If thats the case, // the one with fewer parameters wins (ie less optional parameters) unless it is // expanded. If so, the one with more parameters wins (ie option beats expanded). if (pta1.Count != pta2.Count && betterMethod == BetterType.Neither) { if (node1.fExpanded) { if (!node2.fExpanded) { return BetterType.Right; } } else if (node2.fExpanded) { return BetterType.Left; } // Here, if both methods needed to use optionals to fill in the signatures, // then we are ambiguous. Otherwise, take the one that didn't need any // optionals. if (pta1.Count == carg) { return BetterType.Left; } if (pta2.Count == carg) { return BetterType.Right; } return BetterType.Neither; } return betterMethod; } private BetterType WhichConversionIsBetter(CType argType, CType p1, CType p2) { Debug.Assert(argType != null); Debug.Assert(p1 != null); Debug.Assert(p2 != null); // 7.4.2.3 Better Conversion From Expression // // Given an implicit conversion C1 that converts from an expression E to a type T1 // and an implicit conversion C2 that converts from an expression E to a type T2, the // better conversion of the two conversions is determined as follows: //* if T1 and T2 are the same type, neither conversion is better. //* If E has a type S and the conversion from S to T1 is better than the conversion from // S to T2 then C1 is the better conversion. //* If E has a type S and the conversion from S to T2 is better than the conversion from // S to T1 then C2 is the better conversion. //* If E is a lambda expression or anonymous method for which an inferred return type X // exists and T1 is a delegate type and T2 is a delegate type and T1 and T2 have identical // parameter lists: // * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the // conversion from X to Y1 is better than the conversion from X to Y2, then C1 is the // better return type. // * If T1 is a delegate of return type Y1 and T2 is a delegate of return type Y2 and the // conversion from X to Y2 is better than the conversion from X to Y1, then C2 is the // better return type. if (p1 == p2) { return BetterType.Same; } // 7.4.2.4 Better conversion from type // // Given a conversion C1 that converts from a type S to a type T1 and a conversion C2 // that converts from a type S to a type T2, the better conversion of the two conversions // is determined as follows: //* If T1 and T2 are the same type, neither conversion is better //* If S is T1, C1 is the better conversion. //* If S is T2, C2 is the better conversion. //* If an implicit conversion from T1 to T2 exists and no implicit conversion from T2 to // T1 exists, C1 is the better conversion. //* If an implicit conversion from T2 to T1 exists and no implicit conversion from T1 to // T2 exists, C2 is the better conversion. // // [Otherwise, see table above for better integral type conversions.] if (argType == p1) { return BetterType.Left; } if (argType == p2) { return BetterType.Right; } bool a2b = canConvert(p1, p2); bool b2a = canConvert(p2, p1); if (a2b != b2a) { return a2b ? BetterType.Left : BetterType.Right; } if (p1.IsPredefined && p2.IsPredefined) { PredefinedType pt1 = p1.PredefinedType; if (pt1 <= PredefinedType.PT_OBJECT) { PredefinedType pt2 = p2.PredefinedType; if (pt2 <= PredefinedType.PT_OBJECT) { return (BetterType)s_betterConversionTable[(int)pt1][(int)pt2]; } } } return BetterType.Neither; } //////////////////////////////////////////////////////////////////////////////// // Determine best method for overload resolution. Returns null if no best // method, in which case two tying methods are returned for error reporting. private CandidateFunctionMember FindBestMethod( List<CandidateFunctionMember> list, CType pTypeThrough, ArgInfos args, out CandidateFunctionMember methAmbig1, out CandidateFunctionMember methAmbig2) { Debug.Assert(list.Any()); Debug.Assert(list.First().mpwi != null); Debug.Assert(list.Count > 0); // select the best method: /* Effectively, we pick the best item from a set using a non-transitive ranking function So, pick the first item (candidate) and compare against next (contender), if there is no next, goto phase 2 If first is better, move to next contender, if none proceed to phase 2 If second is better, make the contender the candidate and make the item following contender into the new contender, if there is none, goto phase 2 If neither, make contender+1 into candidate and contender+2 into contender, if possible, otherwise, if contender was last, return null, otherwise if new candidate is last, goto phase 2 Phase 2: compare all items before candidate to candidate If candidate always better, return it, otherwise return null */ // Record two method that are ambiguous for error reporting. CandidateFunctionMember ambig1 = null; CandidateFunctionMember ambig2 = null; bool ambiguous = false; CandidateFunctionMember candidate = list[0]; for (int i = 1; i < list.Count; i++) { CandidateFunctionMember contender = list[i]; Debug.Assert(candidate != contender); switch (WhichMethodIsBetter(candidate, contender, pTypeThrough, args)) { case BetterType.Left: ambiguous = false; // (meaning m1 is better...) break; case BetterType.Right: ambiguous = false; candidate = contender; break; default: // in case of tie we don't want to bother with the contender who tied... ambig1 = candidate; ambig2 = contender; i++; if (i < list.Count) { contender = list[i]; candidate = contender; } else { ambiguous = true; } break; } } if (!ambiguous) { // Now, compare the candidate with items previous to it... foreach (CandidateFunctionMember contender in list) { if (contender == candidate) { // We hit our winner, so its good enough... methAmbig1 = null; methAmbig2 = null; return candidate; } switch (WhichMethodIsBetter(contender, candidate, pTypeThrough, args)) { case BetterType.Right: // meaning m2 is better continue; case BetterType.Same: case BetterType.Neither: ambig1 = candidate; ambig2 = contender; break; } break; } } // an ambiguous call. Return two of the ambiguous set. if (ambig1 != null & ambig2 != null) { methAmbig1 = ambig1; methAmbig2 = ambig2; } else { // For some reason, we have an ambiguity but never had a tie. // This can easily happen in a circular graph of candidate methods. methAmbig1 = list.First(); methAmbig2 = list.Skip(1).First(); } return null; } } }
#region Apache Notice /***************************************************************************** * $Revision: 663728 $ * $LastChangedDate: 2008-06-05 22:40:05 +0200 (jeu., 05 juin 2008) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * 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 #region Remarks // Inpspired from Spring.NET #endregion using System; //#if dotnet2 using System.Collections.Generic; //#endif using System.Reflection; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace IBatisNet.Common.Utilities.TypesResolver { /// <summary> /// Resolves a <see cref="System.Type"/> by name. /// </summary> /// <remarks> /// <p> /// The rationale behind the creation of this class is to centralise the /// resolution of type names to <see cref="System.Type"/> instances beyond that /// offered by the plain vanilla System.Type.GetType method call. /// </p> /// </remarks> /// <version>$Id: TypeResolver.cs,v 1.5 2004/09/28 07:51:47 springboy Exp $</version> public class TypeResolver : ITypeResolver { private const string NULLABLE_TYPE = "System.Nullable"; #region ITypeResolver Members /// <summary> /// Resolves the supplied <paramref name="typeName"/> to a /// <see cref="System.Type"/> instance. /// </summary> /// <param name="typeName"> /// The unresolved name of a <see cref="System.Type"/>. /// </param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> public virtual Type Resolve(string typeName) { //#if dotnet2 Type type = ResolveGenericType(typeName.Replace(" ", string.Empty)); if (type == null) { type = ResolveType(typeName.Replace(" ", string.Empty)); } return type; //#else // return ResolveType(typeName.Replace(" ", string.Empty)); //#endif } #endregion //#if dotnet2 /// <summary> /// Resolves the supplied generic <paramref name="typeName"/>, /// substituting recursively all its type parameters., /// to a <see cref="System.Type"/> instance. /// </summary> /// <param name="typeName"> /// The (possibly generic) name of a <see cref="System.Type"/>. /// </param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> private Type ResolveGenericType(string typeName) { #region Sanity Check if (typeName == null || typeName.Trim().Length == 0) { throw BuildTypeLoadException(typeName); } #endregion if (typeName.StartsWith(NULLABLE_TYPE)) { return null; } else { GenericArgumentsInfo genericInfo = new GenericArgumentsInfo(typeName); Type type = null; try { if (genericInfo.ContainsGenericArguments) { type = TypeUtils.ResolveType(genericInfo.GenericTypeName); if (!genericInfo.IsGenericDefinition) { string[] unresolvedGenericArgs = genericInfo.GetGenericArguments(); Type[] genericArgs = new Type[unresolvedGenericArgs.Length]; for (int i = 0; i < unresolvedGenericArgs.Length; i++) { genericArgs[i] = TypeUtils.ResolveType(unresolvedGenericArgs[i]); } type = type.MakeGenericType(genericArgs); } } } catch (Exception ex) { if (ex is TypeLoadException) { throw; } throw BuildTypeLoadException(typeName, ex); } return type; } } //#endif /// <summary> /// Resolves the supplied <paramref name="typeName"/> to a /// <see cref="System.Type"/> /// instance. /// </summary> /// <param name="typeName"> /// The (possibly partially assembly qualified) name of a /// <see cref="System.Type"/>. /// </param> /// <returns> /// A resolved <see cref="System.Type"/> instance. /// </returns> /// <exception cref="System.TypeLoadException"> /// If the supplied <paramref name="typeName"/> could not be resolved /// to a <see cref="System.Type"/>. /// </exception> private Type ResolveType(string typeName) { #region Sanity Check if (typeName == null || typeName.Trim().Length == 0) { throw BuildTypeLoadException(typeName); } #endregion TypeAssemblyInfo typeInfo = new TypeAssemblyInfo(typeName); Type type = null; try { type = (typeInfo.IsAssemblyQualified) ? LoadTypeDirectlyFromAssembly(typeInfo) : LoadTypeByIteratingOverAllLoadedAssemblies(typeInfo); } catch (Exception ex) { throw BuildTypeLoadException(typeName, ex); } if (type == null) { throw BuildTypeLoadException(typeName); } return type; } /// <summary> /// Uses <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> /// to load an <see cref="System.Reflection.Assembly"/> and then the attendant /// <see cref="System.Type"/> referred to by the <paramref name="typeInfo"/> /// parameter. /// </summary> /// <remarks> /// <p> /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> is /// deprecated in .NET 2.0, but is still used here (even when this class is /// compiled for .NET 2.0); /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> will /// still resolve (non-.NET Framework) local assemblies when given only the /// display name of an assembly (the behaviour for .NET Framework assemblies /// and strongly named assemblies is documented in the docs for the /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> method). /// </p> /// </remarks> /// <param name="typeInfo"> /// The assembly and type to be loaded. /// </param> /// <returns> /// A <see cref="System.Type"/>, or <see lang="null"/>. /// </returns> /// <exception cref="System.Exception"> /// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> /// </exception> private static Type LoadTypeDirectlyFromAssembly(TypeAssemblyInfo typeInfo) { Type type = null; // assembly qualified... load the assembly, then the Type Assembly assembly = null; //#if dotnet2 assembly = Assembly.Load(typeInfo.AssemblyName); //#else // assembly = Assembly.LoadWithPartialName (typeInfo.AssemblyName); //#endif if (assembly != null) { type = assembly.GetType(typeInfo.TypeName, true, true); } return type; } /// <summary> /// Check all assembly /// to load the attendant <see cref="System.Type"/> referred to by /// the <paramref name="typeInfo"/> parameter. /// </summary> /// <param name="typeInfo"> /// The type to be loaded. /// </param> /// <returns> /// A <see cref="System.Type"/>, or <see lang="null"/>. /// </returns> private static Type LoadTypeByIteratingOverAllLoadedAssemblies(TypeAssemblyInfo typeInfo) { Type type = null; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { type = assembly.GetType(typeInfo.TypeName, false, false); if (type != null) { break; } } return type; } private static TypeLoadException BuildTypeLoadException(string typeName) { return new TypeLoadException("Could not load type from string value '" + typeName + "'."); } private static TypeLoadException BuildTypeLoadException(string typeName, Exception ex) { return new TypeLoadException("Could not load type from string value '" + typeName + "'.", ex); } //#if dotnet2 #region Inner Class : GenericArgumentsInfo /// <summary> /// Holder for the generic arguments when using type parameters. /// </summary> /// <remarks> /// <p> /// Type parameters can be applied to classes, interfaces, /// structures, methods, delegates, etc... /// </p> /// </remarks> internal class GenericArgumentsInfo { #region Constants /// <summary> /// The generic arguments prefix. /// </summary> public const string GENERIC_ARGUMENTS_PREFIX = "[["; /// <summary> /// The generic arguments suffix. /// </summary> public const string GENERIC_ARGUMENTS_SUFFIX = "]]"; /// <summary> /// The character that separates a list of generic arguments. /// </summary> public const string GENERIC_ARGUMENTS_SEPARATOR = "],["; #endregion #region Fields private string _unresolvedGenericTypeName = string.Empty; private string[] _unresolvedGenericArguments = null; private readonly static Regex generic = new Regex(@"`\d*\[\[", RegexOptions.Compiled); #endregion #region Constructor (s) / Destructor /// <summary> /// Creates a new instance of the GenericArgumentsInfo class. /// </summary> /// <param name="value"> /// The string value to parse looking for a generic definition /// and retrieving its generic arguments. /// </param> public GenericArgumentsInfo(string value) { ParseGenericArguments(value); } #endregion #region Properties /// <summary> /// The (unresolved) generic type name portion /// of the original value when parsing a generic type. /// </summary> public string GenericTypeName { get { return _unresolvedGenericTypeName; } } /// <summary> /// Is the string value contains generic arguments ? /// </summary> /// <remarks> /// <p> /// A generic argument can be a type parameter or a type argument. /// </p> /// </remarks> public bool ContainsGenericArguments { get { return (_unresolvedGenericArguments != null && _unresolvedGenericArguments.Length > 0); } } /// <summary> /// Is generic arguments only contains type parameters ? /// </summary> public bool IsGenericDefinition { get { if (_unresolvedGenericArguments == null) return false; foreach (string arg in _unresolvedGenericArguments) { if (arg.Length > 0) return false; } return true; } } #endregion #region Methods /// <summary> /// Returns an array of unresolved generic arguments types. /// </summary> /// <remarks> /// <p> /// A empty string represents a type parameter that /// did not have been substituted by a specific type. /// </p> /// </remarks> /// <returns> /// An array of strings that represents the unresolved generic /// arguments types or an empty array if not generic. /// </returns> public string[] GetGenericArguments() { if (_unresolvedGenericArguments == null) { return new string[] { }; } return _unresolvedGenericArguments; } private void ParseGenericArguments(string originalString) { // Check for match bool isMatch = generic.IsMatch(originalString); if (!isMatch) { _unresolvedGenericTypeName = originalString; } else { int argsStartIndex = originalString.IndexOf(GENERIC_ARGUMENTS_PREFIX); int argsEndIndex = originalString.LastIndexOf(GENERIC_ARGUMENTS_SUFFIX); if (argsEndIndex != -1) { SplitGenericArguments(originalString.Substring( argsStartIndex + 1, argsEndIndex - argsStartIndex)); _unresolvedGenericTypeName = originalString.Remove(argsStartIndex, argsEndIndex - argsStartIndex + 2); } } } private void SplitGenericArguments(string originalArgs) { IList<string> arguments = new List<string>(); if (originalArgs.Contains(GENERIC_ARGUMENTS_SEPARATOR)) { arguments = Parse(originalArgs); } else { string argument = originalArgs.Substring(1, originalArgs.Length - 2).Trim(); arguments.Add(argument); } _unresolvedGenericArguments = new string[arguments.Count]; arguments.CopyTo(_unresolvedGenericArguments, 0); } private IList<string> Parse(string args) { StringBuilder argument = new StringBuilder(); IList<string> arguments = new List<string>(); TextReader input = new StringReader(args); int nbrOfRightDelimiter = 0; bool findRight = false; do { char ch = (char)input.Read(); if (ch == '[') { nbrOfRightDelimiter++; findRight = true; } else if (ch == ']') { nbrOfRightDelimiter--; } argument.Append(ch); //Find one argument if (findRight && nbrOfRightDelimiter == 0) { string arg = argument.ToString(); arg = arg.Substring(1, arg.Length - 2); arguments.Add(arg); input.Read(); argument = new StringBuilder(); } } while (input.Peek() != -1); return arguments; } #endregion } #endregion //#endif #region Inner Class : TypeAssemblyInfo /// <summary> /// Holds data about a <see cref="System.Type"/> and it's /// attendant <see cref="System.Reflection.Assembly"/>. /// </summary> internal class TypeAssemblyInfo { #region Constants /// <summary> /// The string that separates a <see cref="System.Type"/> name /// from the name of it's attendant <see cref="System.Reflection.Assembly"/> /// in an assembly qualified type name. /// </summary> public const string TYPE_ASSEMBLY_SEPARATOR = ","; public const string NULLABLE_TYPE = "System.Nullable"; public const string NULLABLE_TYPE_ASSEMBLY_SEPARATOR = "]],"; #endregion #region Fields private string _unresolvedAssemblyName = string.Empty; private string _unresolvedTypeName = string.Empty; #endregion #region Constructor (s) / Destructor /// <summary> /// Creates a new instance of the TypeAssemblyInfo class. /// </summary> /// <param name="unresolvedTypeName"> /// The unresolved name of a <see cref="System.Type"/>. /// </param> public TypeAssemblyInfo(string unresolvedTypeName) { SplitTypeAndAssemblyNames(unresolvedTypeName); } #endregion #region Properties /// <summary> /// The (unresolved) type name portion of the original type name. /// </summary> public string TypeName { get { return _unresolvedTypeName; } } /// <summary> /// The (unresolved, possibly partial) name of the attandant assembly. /// </summary> public string AssemblyName { get { return _unresolvedAssemblyName; } } /// <summary> /// Is the type name being resolved assembly qualified? /// </summary> public bool IsAssemblyQualified { get { return HasText(AssemblyName); } } #endregion #region Methods private bool HasText(string target) { if (target == null) { return false; } else { return HasLength(target.Trim()); } } private bool HasLength(string target) { return (target != null && target.Length > 0); } private void SplitTypeAndAssemblyNames(string originalTypeName) { if (originalTypeName.StartsWith(NULLABLE_TYPE)) { int typeAssemblyIndex = originalTypeName.IndexOf(NULLABLE_TYPE_ASSEMBLY_SEPARATOR); if (typeAssemblyIndex < 0) { _unresolvedTypeName = originalTypeName; } else { _unresolvedTypeName = originalTypeName.Substring(0, typeAssemblyIndex + 2).Trim(); _unresolvedAssemblyName = originalTypeName.Substring(typeAssemblyIndex + 3).Trim(); } } else { int typeAssemblyIndex = originalTypeName.IndexOf(TYPE_ASSEMBLY_SEPARATOR); if (typeAssemblyIndex < 0) { _unresolvedTypeName = originalTypeName; } else { _unresolvedTypeName = originalTypeName.Substring(0, typeAssemblyIndex).Trim(); _unresolvedAssemblyName = originalTypeName.Substring(typeAssemblyIndex + 1).Trim(); } } } #endregion } #endregion } }
using DotVVM.Framework.Binding; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Hosting; using DotVVM.Framework.Utils; using System; using Newtonsoft.Json; using System.Collections.Generic; namespace DotVVM.Framework.Controls { /// <summary> /// Renders a HTML text input control. /// </summary> [ControlMarkupOptions(AllowContent = false)] public class TextBox : HtmlGenericControl { private FormatValueType resolvedValueType; private string? implicitFormatString; /// <summary> /// Gets or sets a value indicating whether the control is enabled and can be modified. /// </summary> public bool Enabled { get { return (bool)GetValue(EnabledProperty)!; } set { SetValue(EnabledProperty, value); } } public static readonly DotvvmProperty EnabledProperty = DotvvmPropertyWithFallback.Register<bool, TextBox>(nameof(Enabled), FormControls.EnabledProperty); /// <summary> /// Gets or sets a format of presentation of value to client. /// </summary> [MarkupOptions(AllowBinding = false)] public string? FormatString { get { return (string?)GetValue(FormatStringProperty); } set { SetValue(FormatStringProperty, value); } } public static readonly DotvvmProperty FormatStringProperty = DotvvmProperty.Register<string?, TextBox>(t => t.FormatString); /// <summary> /// Gets or sets the command that will be triggered when the onchange event is fired. /// </summary> public Command? Changed { get { return (Command?)GetValue(ChangedProperty); } set { SetValue(ChangedProperty, value); } } public static readonly DotvvmProperty ChangedProperty = DotvvmProperty.Register<Command?, TextBox>(t => t.Changed, null); /// <summary> /// Gets or sets the command that will be triggered when the user is typing in the field. /// Be careful when using this event - triggering frequent postbacks can make bad user experience. Consider using static commands or a throttling postback handler. /// </summary> public Command? TextInput { get { return (Command?)GetValue(TextInputProperty); } set { SetValue(TextInputProperty, value); } } public static readonly DotvvmProperty TextInputProperty = DotvvmProperty.Register<Command?, TextBox>(t => t.TextInput, null); /// <summary> /// Gets or sets whether all text inside the TextBox becomes selected when the element gets focused. /// </summary> public bool SelectAllOnFocus { get { return (bool)GetValue(SelectAllOnFocusProperty)!; } set { SetValue(SelectAllOnFocusProperty, value); } } public static readonly DotvvmProperty SelectAllOnFocusProperty = DotvvmProperty.Register<bool, TextBox>(t => t.SelectAllOnFocus, false); /// <summary> /// Gets or sets the text in the control. /// </summary> [MarkupOptions(Required = true)] public string Text { get { return Convert.ToString(GetValue(TextProperty)).NotNull(); } set { SetValue(TextProperty, value); } } public static readonly DotvvmProperty TextProperty = DotvvmProperty.Register<object, TextBox>(t => t.Text, ""); /// <summary> /// Gets or sets the mode of the text field. /// </summary> [MarkupOptions(AllowBinding = false)] public TextBoxType Type { get { return (TextBoxType)GetValue(TypeProperty)!; } set { SetValue(TypeProperty, value); } } public static readonly DotvvmProperty TypeProperty = DotvvmProperty.Register<TextBoxType, TextBox>(c => c.Type, TextBoxType.Normal); /// <summary> /// Gets or sets whether the viewmodel property will be updated immediately after change. /// By default, the viewmodel is updated after the control loses its focus. /// </summary> [MarkupOptions(AllowBinding = false)] public bool UpdateTextOnInput { get { return (bool)GetValue(UpdateTextOnInputProperty)!; } set { SetValue(UpdateTextOnInputProperty, value); } } public static readonly DotvvmProperty UpdateTextOnInputProperty = DotvvmProperty.Register<bool, TextBox>( nameof(UpdateTextOnInput), isValueInherited: true); public static FormatValueType ResolveValueType(IValueBinding? binding) { if (binding?.ResultType == typeof(DateTime) || binding?.ResultType == typeof(DateTime?)) { return FormatValueType.DateTime; } else if (binding != null && (binding.ResultType.IsNumericType() || Nullable.GetUnderlyingType(binding.ResultType)?.IsNumericType() == true)) { return FormatValueType.Number; } return FormatValueType.Text; } protected internal override void OnPreRender(IDotvvmRequestContext context) { var isTypeImplicitlyFormatted = Type.TryGetFormatString(out implicitFormatString); if (!string.IsNullOrEmpty(FormatString) && isTypeImplicitlyFormatted) { throw new NotSupportedException($"Property FormatString cannot be used with Type set to '{ Type }'." + $" In this case browsers localize '{ Type }' themselves."); } if (!isTypeImplicitlyFormatted || implicitFormatString != null) { resolvedValueType = ResolveValueType(GetValueBinding(TextProperty)); } if (resolvedValueType != FormatValueType.Text) { context.ResourceManager.AddCurrentCultureGlobalizationResource(); } base.OnPreRender(context); } /// <summary> /// Adds all attributes that should be added to the control begin tag. /// </summary> protected override void AddAttributesToRender(IHtmlWriter writer, IDotvvmRequestContext context) { AddEnabledPropertyToRender(writer); AddTypeAttributeToRender(writer); AddChangedPropertyToRender(writer, context); AddSelectAllOnFocusPropertyToRender(writer, context); AddBindingToRender(writer); } /// <summary> /// Renders the contents inside the control begin and end tags. /// </summary> protected override void RenderContents(IHtmlWriter writer, IDotvvmRequestContext context) { if (Type == TextBoxType.MultiLine && GetValueBinding(TextProperty) == null) { writer.WriteText(Text); } } private void AddEnabledPropertyToRender(IHtmlWriter writer) { switch (this.GetValueRaw(EnabledProperty)) { case bool value: if (!value) writer.AddAttribute("disabled", "disabled"); break; case IValueBinding binding: writer.AddKnockoutDataBind("enable", binding.GetKnockoutBindingExpression(this)); break; default: if (!Enabled) writer.AddAttribute("disabled", "disabled"); break; } } private void AddBindingToRender(IHtmlWriter writer) { // if format is set then use different value binding which supports the format writer.AddKnockoutDataBind("dotvvm-textbox-text", this, TextProperty, () => { if (Type != TextBoxType.MultiLine) { writer.AddAttribute("value", Text); } }, UpdateTextOnInput ? "input" : null, renderEvenInServerRenderingMode: true); if (resolvedValueType != FormatValueType.Text) { var formatString = FormatString; if (string.IsNullOrEmpty(formatString)) { formatString = implicitFormatString ?? "G"; } writer.AddAttribute("data-dotvvm-format", formatString); if (resolvedValueType == FormatValueType.DateTime) { writer.AddAttribute("data-dotvvm-value-type", "datetime"); } else if (resolvedValueType == FormatValueType.Number) { writer.AddAttribute("data-dotvvm-value-type", "number"); } } } private void AddChangedPropertyToRender(IHtmlWriter writer, IDotvvmRequestContext context) { // prepare changed event attribute var changedBinding = GetCommandBinding(ChangedProperty); var textInputBinding = GetCommandBinding(TextInputProperty); base.AddAttributesToRender(writer, context); if (changedBinding != null) { writer.AddAttribute("onchange", KnockoutHelper.GenerateClientPostBackScript(nameof(Changed), changedBinding, this, useWindowSetTimeout: true, isOnChange: true), true, ";"); } if (textInputBinding != null) { writer.AddAttribute("oninput", KnockoutHelper.GenerateClientPostBackScript(nameof(TextInput), textInputBinding, this, useWindowSetTimeout: true, isOnChange: true), true, ";"); } } private void AddSelectAllOnFocusPropertyToRender(IHtmlWriter writer, IDotvvmRequestContext context) { const string KoBindingName = "dotvvm-textbox-select-all-on-focus"; switch (this.GetValueRaw(SelectAllOnFocusProperty)) { case false: break; case IValueBinding valueBinding: writer.AddKnockoutDataBind(KoBindingName, valueBinding.GetKnockoutBindingExpression(this)); break; case object _ when SelectAllOnFocus: writer.AddKnockoutDataBind(KoBindingName, "true"); break; } } private void AddTypeAttributeToRender(IHtmlWriter writer) { var type = this.Type; if (type.TryGetTagName(out var tagName)) { TagName = tagName; // do not overwrite type attribute if (type == TextBoxType.Normal && !Attributes.ContainsKey("type")) { writer.AddAttribute("type", "text"); } return; } if (type.TryGetInputType(out var inputType)) { writer.AddAttribute("type", inputType); TagName = "input"; return; } throw new NotSupportedException($"TextBox Type '{ type }' not supported"); } } }
//--------------------------------------------------------------------------- // // <copyright file="ContentPresenter.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: ContentPresenter class // // Specs: http://avalon/connecteddata/M5%20General%20Docs/Data%20Styling.mht // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.ComponentModel; using System.Reflection; using System.Windows.Threading; using System.Windows.Shapes; using System.Windows.Media; using System.Windows.Data; using System.Windows.Markup; using MS.Internal; using MS.Internal.Data; using MS.Internal.KnownBoxes; using System.Windows.Documents; using MS.Utility; using MS.Internal.PresentationFramework; using System.Collections.Specialized; namespace System.Windows.Controls { /// <summary> /// ContentPresenter is used within the template of a content control to denote the /// place in the control's visual tree (control template) where the content /// is to be added. /// </summary> [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] public class ContentPresenter : FrameworkElement { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static ContentPresenter() { DataTemplate template; FrameworkElementFactory text; Binding binding; // Default template for strings when hosted in ContentPresener with RecognizesAccessKey=true template = new DataTemplate(); text = CreateAccessTextFactory(); text.SetValue(AccessText.TextProperty, new TemplateBindingExtension(ContentProperty)); template.VisualTree = text; template.Seal(); s_AccessTextTemplate = template; // Default template for strings template = new DataTemplate(); text = CreateTextBlockFactory(); text.SetValue(TextBlock.TextProperty, new TemplateBindingExtension(ContentProperty)); template.VisualTree = text; template.Seal(); s_StringTemplate = template; // Default template for XmlNodes template = new DataTemplate(); text = CreateTextBlockFactory(); binding = new Binding(); binding.XPath = "."; text.SetBinding(TextBlock.TextProperty, binding); template.VisualTree = text; template.Seal(); s_XmlNodeTemplate = template; // Default template for UIElements template = new UseContentTemplate(); template.Seal(); s_UIElementTemplate = template; // Default template for everything else template = new DefaultTemplate(); template.Seal(); s_DefaultTemplate = template; // Default template selector s_DefaultTemplateSelector = new DefaultSelector(); } /// <summary> /// Default constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public ContentPresenter() : base() { Initialize(); } void Initialize() { // Initialize the _templateCache to the default value for TemplateProperty. // If the default value is non-null then wire it to the current instance. PropertyMetadata metadata = TemplateProperty.GetMetadata(DependencyObjectType); DataTemplate defaultValue = (DataTemplate) metadata.DefaultValue; if (defaultValue != null) { OnTemplateChanged(this, new DependencyPropertyChangedEventArgs(TemplateProperty, metadata, null, defaultValue)); } DataContext = null; // this presents a uniform view: CP always has local DC } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The DependencyProperty for the RecognizesAccessKey property. /// Flags: None /// Default Value: false /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty RecognizesAccessKeyProperty = DependencyProperty.Register( "RecognizesAccessKey", typeof(bool), typeof(ContentPresenter), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Determine if ContentPresenter should use AccessText in its style /// </summary> public bool RecognizesAccessKey { get { return (bool) GetValue(RecognizesAccessKeyProperty); } set { SetValue(RecognizesAccessKeyProperty, BooleanBoxes.Box(value)); } } /// <summary> /// The DependencyProperty for the Content property. /// Flags: None /// Default Value: null /// </summary> // Any change in Content properties affectes layout measurement since // a new template may be used. On measurement, // ApplyTemplate will be invoked leading to possible application // of a new template. [CommonDependencyProperty] public static readonly DependencyProperty ContentProperty = ContentControl.ContentProperty.AddOwner( typeof(ContentPresenter), new FrameworkPropertyMetadata( (object)null, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnContentChanged))); /// <summary> /// Content is the data used to generate the child elements of this control. /// </summary> public object Content { get { return GetValue(ContentControl.ContentProperty); } set { SetValue(ContentControl.ContentProperty, value); } } /// <summary> /// Called when ContentProperty is invalidated on "d." /// </summary> private static void OnContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentPresenter ctrl = (ContentPresenter)d; // if we're already marked to reselect the template, there's nothing more to do if (!ctrl._templateIsCurrent) return; bool mismatch; if (e.NewValue == BindingExpressionBase.DisconnectedItem) { mismatch = false; // do not change templates when disconnecting } else if (ctrl.ContentTemplate != null) { mismatch = false; // explicit template - matches by fiat } else if (ctrl.ContentTemplateSelector != null) { mismatch = true; // template selector - always re-select } else if (ctrl.Template == UIElementContentTemplate) { mismatch = true; // direct template - always re-apply ctrl.Template = null; // and release the old content so it can be re-used elsewhere } else if (ctrl.Template == DefaultContentTemplate) { mismatch = true; // default template - always re-apply } else { // implicit template - matches if data types agree Type type; // unused object oldDataType = DataTypeForItem(e.OldValue, ctrl, out type); object newDataType = DataTypeForItem(e.NewValue, ctrl, out type); mismatch = (oldDataType != newDataType); // but mismatch if we're displaying strings via a default template // and the presence of an AccessKey changes if (!mismatch && ctrl.RecognizesAccessKey && Object.ReferenceEquals(typeof(String), newDataType) && ctrl.IsUsingDefaultStringTemplate) { String oldString = (String)e.OldValue; String newString = (String)e.NewValue; bool oldHasAccessKey = (oldString.IndexOf(AccessText.AccessKeyMarker) > -1); bool newHasAccessKey = (newString.IndexOf(AccessText.AccessKeyMarker) > -1); if (oldHasAccessKey != newHasAccessKey) { mismatch = true; } } } // if the content and (old) template don't match, reselect the template if (mismatch) { ctrl._templateIsCurrent = false; } // keep the DataContext in [....] with Content if (ctrl._templateIsCurrent && ctrl.Template != UIElementContentTemplate) { ctrl.DataContext = e.NewValue; } } /// <summary> /// The DependencyProperty for the ContentTemplate property. /// Flags: None /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty ContentTemplateProperty = ContentControl.ContentTemplateProperty.AddOwner( typeof(ContentPresenter), new FrameworkPropertyMetadata( (DataTemplate)null, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnContentTemplateChanged))); /// <summary> /// ContentTemplate is the template used to display the content of the control. /// </summary> public DataTemplate ContentTemplate { get { return (DataTemplate) GetValue(ContentControl.ContentTemplateProperty); } set { SetValue(ContentControl.ContentTemplateProperty, value); } } /// <summary> /// Called when ContentTemplateProperty is invalidated on "d." /// </summary> private static void OnContentTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentPresenter ctrl = (ContentPresenter)d; ctrl._templateIsCurrent = false; ctrl.OnContentTemplateChanged((DataTemplate) e.OldValue, (DataTemplate) e.NewValue); } /// <summary> /// This method is invoked when the ContentTemplate property changes. /// </summary> /// <param name="oldContentTemplate">The old value of the ContentTemplate property.</param> /// <param name="newContentTemplate">The new value of the ContentTemplate property.</param> protected virtual void OnContentTemplateChanged(DataTemplate oldContentTemplate, DataTemplate newContentTemplate) { Helper.CheckTemplateAndTemplateSelector("Content", ContentTemplateProperty, ContentTemplateSelectorProperty, this); // if ContentTemplate is really changing, remove the old template this.Template = null; } /// <summary> /// The DependencyProperty for the ContentTemplateSelector property. /// Flags: None /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty ContentTemplateSelectorProperty = ContentControl.ContentTemplateSelectorProperty.AddOwner( typeof(ContentPresenter), new FrameworkPropertyMetadata( (DataTemplateSelector)null, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnContentTemplateSelectorChanged))); /// <summary> /// ContentTemplateSelector allows the application writer to provide custom logic /// for choosing the template used to display the content of the control. /// </summary> /// <remarks> /// This property is ignored if <seealso cref="ContentTemplate"/> is set. /// </remarks> public DataTemplateSelector ContentTemplateSelector { get { return (DataTemplateSelector) GetValue(ContentControl.ContentTemplateSelectorProperty); } set { SetValue(ContentControl.ContentTemplateSelectorProperty, value); } } /// <summary> /// This method is used by TypeDescriptor to determine if this property should /// be serialized. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeContentTemplateSelector() { return false; } /// <summary> /// Called when ContentTemplateSelectorProperty is invalidated on "d." /// </summary> private static void OnContentTemplateSelectorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentPresenter ctrl = (ContentPresenter) d; ctrl._templateIsCurrent = false; ctrl.OnContentTemplateSelectorChanged((DataTemplateSelector) e.OldValue, (DataTemplateSelector) e.NewValue); } /// <summary> /// This method is invoked when the ContentTemplateSelector property changes. /// </summary> /// <param name="oldContentTemplateSelector">The old value of the ContentTemplateSelector property.</param> /// <param name="newContentTemplateSelector">The new value of the ContentTemplateSelector property.</param> protected virtual void OnContentTemplateSelectorChanged(DataTemplateSelector oldContentTemplateSelector, DataTemplateSelector newContentTemplateSelector) { Helper.CheckTemplateAndTemplateSelector("Content", ContentTemplateProperty, ContentTemplateSelectorProperty, this); // if ContentTemplateSelector is really changing (and in use), remove the old template this.Template = null; } /// <summary> /// The DependencyProperty for the ContentStringFormat property. /// Flags: None /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty ContentStringFormatProperty = DependencyProperty.Register( "ContentStringFormat", typeof(String), typeof(ContentPresenter), new FrameworkPropertyMetadata( (String) null, new PropertyChangedCallback(OnContentStringFormatChanged))); /// <summary> /// ContentStringFormat is the format used to display the content of /// the control as a string. This arises only when no template is /// available. /// </summary> [Bindable(true), CustomCategory("Content")] public String ContentStringFormat { get { return (String) GetValue(ContentStringFormatProperty); } set { SetValue(ContentStringFormatProperty, value); } } /// <summary> /// Called when ContentStringFormatProperty is invalidated on "d." /// </summary> private static void OnContentStringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentPresenter ctrl = (ContentPresenter)d; ctrl.OnContentStringFormatChanged((String) e.OldValue, (String) e.NewValue); } /// <summary> /// This method is invoked when the ContentStringFormat property changes. /// </summary> /// <param name="oldContentStringFormat">The old value of the ContentStringFormat property.</param> /// <param name="newContentStringFormat">The new value of the ContentStringFormat property.</param> protected virtual void OnContentStringFormatChanged(String oldContentStringFormat, String newContentStringFormat) { // force on-demand regeneration of the formatting templates for XML and String content XMLFormattingTemplateField.ClearValue(this); StringFormattingTemplateField.ClearValue(this); AccessTextFormattingTemplateField.ClearValue(this); } /// <summary> /// The DependencyProperty for the ContentSource property. /// Flags: None /// Default Value: Content /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty ContentSourceProperty = DependencyProperty.Register( "ContentSource", typeof(string), typeof(ContentPresenter), new FrameworkPropertyMetadata("Content")); /// <summary> /// ContentSource is the base name to use during automatic aliasing. /// When a template contains a ContentPresenter with ContentSource="Abc", /// its Content, ContentTemplate, ContentTemplateSelector, and ContentStringFormat /// properties are automatically aliased to Abc, AbcTemplate, AbcTemplateSelector, /// and AbcStringFormat respectively. The two most useful values for /// ContentSource are "Content" and "Header"; the default is "Content". /// </summary> /// <remarks> /// This property only makes sense in a template. It should not be set on /// an actual ContentPresenter; there will be no effect. /// </remarks> public string ContentSource { get { return GetValue(ContentSourceProperty) as string; } set { SetValue(ContentSourceProperty, value); } } //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ /// <summary> /// Called when the Template's tree is about to be generated /// </summary> internal override void OnPreApplyTemplate() { base.OnPreApplyTemplate(); // If we're inflating our visual tree but our TemplatedParent is null, // we might have been removed from the visual tree but not have had // our ContentProperty invalidated. This would mean that when we go // to reparent our content, we'll be looking at a stale cache. Make // sure to invalidate the Content property in this case. if (TemplatedParent == null) { // call GetValueCore to get this value from its TemplatedParent InvalidateProperty(ContentProperty); } // If the ContentPresenter is using "default expansion", the result // depends on the Language property. There is no notification when it // changes (i.e. no virtual OnLanguageChanged method), but it is marked // as AffectsMeasure, so the CP will be re-measured and will call into // OnPreApplyTemplate. At this point, if Language has changed (and if // we're actually using it), invalidate the template. This will cause // DoDefaultExpansion to run again with the new language. if (_language != null && _language != this.Language) { _templateIsCurrent = false; } if (!_templateIsCurrent) { EnsureTemplate(); _templateIsCurrent = true; } } /// <summary> /// Updates DesiredSize of the ContentPresenter. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <remarks> /// ContentPresenter determines a desired size it needs from the child's sizing properties, margin, and requested size. /// </remarks> /// <param name="constraint">Constraint size is an "upper limit" that the return value should not exceed.</param> /// <returns>The ContentPresenter's desired size.</returns> protected override Size MeasureOverride(Size constraint) { return Helper.MeasureElementWithSingleChild(this, constraint); } /// <summary> /// ContentPresenter computes the position of its single child inside child's Margin and calls Arrange /// on the child. /// </summary> /// <param name="arrangeSize">Size the ContentPresenter will assume.</param> protected override Size ArrangeOverride(Size arrangeSize) { return Helper.ArrangeElementWithSingleChild(this, arrangeSize); } /// <summary> /// Return the template to use. This may depend on the Content, or /// other properties. /// </summary> /// <remarks> /// The base class implements the following rules: /// (a) If ContentTemplate is set, use it. /// (b) If ContentTemplateSelector is set, call its /// SelectTemplate method. If the result is not null, use it. /// (c) Look for a DataTemplate whose DataType matches the /// Content among the resources known to the ContentPresenter /// (including application, theme, and system resources). /// If one is found, use it. /// (d) If the type of Content is "common", use a standard template. /// The common types are String, XmlNode, UIElement. /// (e) Otherwise, use a default template that essentially converts /// Content to a string and displays it in a TextBlock. /// Derived classes can override these rules and implement their own. /// </remarks> protected virtual DataTemplate ChooseTemplate() { DataTemplate template = null; object content = Content; // ContentTemplate has first stab template = ContentTemplate; // no ContentTemplate set, try ContentTemplateSelector if (template == null) { if (ContentTemplateSelector != null) { template = ContentTemplateSelector.SelectTemplate(content, this); } } // if that failed, try the default TemplateSelector if (template == null) { template = DefaultTemplateSelector.SelectTemplate(content, this); } return template; } //------------------------------------------------------ // // Internal properties // //------------------------------------------------------ internal static DataTemplate AccessTextContentTemplate { get { return s_AccessTextTemplate; } } internal static DataTemplate StringContentTemplate { get { return s_StringTemplate; } } // Internal Helper so the FrameworkElement could see this property internal override FrameworkTemplate TemplateInternal { get { return Template; } } // Internal Helper so the FrameworkElement could see the template cache internal override FrameworkTemplate TemplateCache { get { return _templateCache; } set { _templateCache = (DataTemplate)value; } } internal bool TemplateIsCurrent { get { return _templateIsCurrent; } } //------------------------------------------------------ // // Internal methods // //------------------------------------------------------ /// <summary> /// Prepare to display the item. /// </summary> internal void PrepareContentPresenter(object item, DataTemplate itemTemplate, DataTemplateSelector itemTemplateSelector, string stringFormat) { if (item != this) { // copy templates from parent ItemsControl if (_contentIsItem || !HasNonDefaultValue(ContentProperty)) { Content = item; _contentIsItem = true; } if (itemTemplate != null) SetValue(ContentTemplateProperty, itemTemplate); if (itemTemplateSelector != null) SetValue(ContentTemplateSelectorProperty, itemTemplateSelector); if (stringFormat != null) SetValue(ContentStringFormatProperty, stringFormat); } } /// <summary> /// Undo the effect of PrepareContentPresenter. /// </summary> internal void ClearContentPresenter(object item) { if (item != this) { if (_contentIsItem) { Content = BindingExpressionBase.DisconnectedItem; } } } internal static object DataTypeForItem(object item, DependencyObject target, out Type type) { if (item == null) { type = null; return null; } object dataType; type = ReflectionHelper.GetReflectionType(item); if (SystemXmlLinqHelper.IsXElement(item)) { dataType = SystemXmlLinqHelper.GetXElementTagName(item); type = null; } else if (SystemXmlHelper.IsXmlNode(item)) { dataType = SystemXmlHelper.GetXmlTagName(item, target); type = null; } else if (type == typeof(Object)) { dataType = null; // don't search for Object - perf } else { dataType = type; } return dataType; } //------------------------------------------------------ // // Private properties // //------------------------------------------------------ static DataTemplate XmlNodeContentTemplate { get { return s_XmlNodeTemplate; } } static DataTemplate UIElementContentTemplate { get { return s_UIElementTemplate; } } static DataTemplate DefaultContentTemplate { get { return s_DefaultTemplate; } } static DefaultSelector DefaultTemplateSelector { get { return s_DefaultTemplateSelector; } } DataTemplate FormattingAccessTextContentTemplate { get { DataTemplate template = AccessTextFormattingTemplateField.GetValue(this); if (template == null) { Binding binding = new Binding(); binding.StringFormat = ContentStringFormat; FrameworkElementFactory text = CreateAccessTextFactory(); text.SetBinding(AccessText.TextProperty, binding); template = new DataTemplate(); template.VisualTree = text; template.Seal(); AccessTextFormattingTemplateField.SetValue(this, template); } return template; } } DataTemplate FormattingStringContentTemplate { get { DataTemplate template = StringFormattingTemplateField.GetValue(this); if (template == null) { Binding binding = new Binding(); binding.StringFormat = ContentStringFormat; FrameworkElementFactory text = CreateTextBlockFactory(); text.SetBinding(TextBlock.TextProperty, binding); template = new DataTemplate(); template.VisualTree = text; template.Seal(); StringFormattingTemplateField.SetValue(this, template); } return template; } } DataTemplate FormattingXmlNodeContentTemplate { get { DataTemplate template = XMLFormattingTemplateField.GetValue(this); if (template == null) { Binding binding = new Binding(); binding.XPath = "."; binding.StringFormat = ContentStringFormat; FrameworkElementFactory text = CreateTextBlockFactory(); text.SetBinding(TextBlock.TextProperty, binding); template = new DataTemplate(); template.VisualTree = text; template.Seal(); XMLFormattingTemplateField.SetValue(this, template); } return template; } } /// <summary> /// TemplateProperty /// </summary> internal static readonly DependencyProperty TemplateProperty = DependencyProperty.Register( "Template", typeof(DataTemplate), typeof(ContentPresenter), new FrameworkPropertyMetadata( (DataTemplate) null, // default value FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnTemplateChanged))); /// <summary> /// Template Property /// </summary> private DataTemplate Template { get { return _templateCache; } set { SetValue(TemplateProperty, value); } } // Internal helper so FrameworkElement could see call the template changed virtual internal override void OnTemplateChangedInternal(FrameworkTemplate oldTemplate, FrameworkTemplate newTemplate) { OnTemplateChanged((DataTemplate)oldTemplate, (DataTemplate)newTemplate); } // Property invalidation callback invoked when TemplateProperty is invalidated private static void OnTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ContentPresenter c = (ContentPresenter) d; StyleHelper.UpdateTemplateCache(c, (FrameworkTemplate) e.OldValue, (FrameworkTemplate) e.NewValue, TemplateProperty); } /// <summary> /// Template has changed /// </summary> /// <remarks> /// When a Template changes, the VisualTree is removed. The new Template's /// VisualTree will be created when ApplyTemplate is called /// </remarks> /// <param name="oldTemplate">The old Template</param> /// <param name="newTemplate">The new Template</param> protected virtual void OnTemplateChanged(DataTemplate oldTemplate, DataTemplate newTemplate) { } //------------------------------------------------------ // // Private methods // //------------------------------------------------------ private void EnsureTemplate() { DataTemplate oldTemplate = Template; DataTemplate newTemplate = null; for (_templateIsCurrent = false; !_templateIsCurrent; ) { // normally this loop will execute exactly once. The only exception // is when setting the DataContext causes the ContentTemplate or // ContentTemplateSelector to change, presumably because they are // themselves data-bound (see bug 128119). In that case, we need // to call ChooseTemplate again, to pick up the new template. // We detect this case because _templateIsCurrent is reset to false // in OnContentTemplate[Selector]Changed, causing a second iteration // of the loop. _templateIsCurrent = true; newTemplate = ChooseTemplate(); // if the template is changing, it's important that the code that cleans // up the old template runs while the CP's DataContext is still set to // the old Content. The way to get this effect is: // a. change the template to null // b. change the data context // c. change the template to the new value if (oldTemplate != newTemplate) { Template = null; } if (newTemplate != UIElementContentTemplate) { // set data context to the content, so that the template can bind to // properties of the content. this.DataContext = Content; } else { // If we're using the content directly, clear the data context. // The content expects to inherit. this.ClearValue(DataContextProperty); } } Template = newTemplate; // if the template didn't change, we still need to force the content for the template to be regenerated; // so call StyleHelper's DoTemplateInvalidations directly if (oldTemplate == newTemplate) { StyleHelper.DoTemplateInvalidations(this, oldTemplate); } } // Select a template for string content DataTemplate SelectTemplateForString(string s) { DataTemplate template; string format = ContentStringFormat; if (this.RecognizesAccessKey && s.IndexOf(AccessText.AccessKeyMarker) > -1) { template = (String.IsNullOrEmpty(format)) ? AccessTextContentTemplate : FormattingAccessTextContentTemplate; } else { template = (String.IsNullOrEmpty(format)) ? StringContentTemplate : FormattingStringContentTemplate; } return template; } // return true if the template was chosen by SelectTemplateForString bool IsUsingDefaultStringTemplate { get { if (Template == StringContentTemplate || Template == AccessTextContentTemplate) { return true; } DataTemplate template; template = StringFormattingTemplateField.GetValue(this); if (template != null && template == Template) { return true; } template = AccessTextFormattingTemplateField.GetValue(this); if (template != null && template == Template) { return true; } return false; } } // Select a template for XML content DataTemplate SelectTemplateForXML() { return (String.IsNullOrEmpty(ContentStringFormat)) ? XmlNodeContentTemplate : FormattingXmlNodeContentTemplate; } // ContentPresenter often has occasion to display text. The TextBlock it uses // should get the values for various text-related properties (foreground, fonts, // decoration, trimming) from the governing ContentControl. The following // two methods accomplish this - first for the case where the TextBlock appears // in a true template, then for the case where the TextBlock is created on // demand via BuildVisualTree. // Create a FEF for a AccessText, to be used in a default template internal static FrameworkElementFactory CreateAccessTextFactory() { FrameworkElementFactory text = new FrameworkElementFactory(typeof(AccessText)); return text; } // Create a FEF for a TextBlock, to be used in a default template internal static FrameworkElementFactory CreateTextBlockFactory() { FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock)); return text; } // Create a TextBlock, to be used in a default "template" (via BuildVisualTree) static TextBlock CreateTextBlock(ContentPresenter container) { TextBlock text = new TextBlock(); return text; } // Cache the Language property when it's used by DoDefaultExpansion, so // that we can detect changes. (This could also be done by a virtual // OnLanguageChanged method, if FrameworkElement ever defines one.) private void CacheLanguage(XmlLanguage language) { _language = language; } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 28; } } //------------------------------------------------------ // // Private nested classes // //------------------------------------------------------ // Template for displaying UIElements - use the UIElement itself private class UseContentTemplate : DataTemplate { public UseContentTemplate() { // We need to preserve the treeState cache on a container node // even after all its logical children have been added. This is so the // construction of the template visual tree nodes can consume the cache. // This member helps us know whether we should retain the cache for // special scenarios when the visual tree is being built via BuildVisualTree CanBuildVisualTree = true; } internal override bool BuildVisualTree(FrameworkElement container) { object content = ((ContentPresenter)container).Content; UIElement e = content as UIElement; if (e == null) { TypeConverter tc = TypeDescriptor.GetConverter(ReflectionHelper.GetReflectionType(content)); Debug.Assert(tc.CanConvertTo(typeof(UIElement))); e = (UIElement) tc.ConvertTo(content, typeof(UIElement)); } StyleHelper.AddCustomTemplateRoot( container, e ); return true; } } // template for displaying content when all else fails private class DefaultTemplate : DataTemplate { public DefaultTemplate() { // We need to preserve the treeState cache on a container node // even after all its logical children have been added. This is so the // construction of the template visual tree nodes can consume the cache. // This member helps us know whether we should retain the cache for // special scenarios when the visual tree is being built via BuildVisualTree CanBuildVisualTree = true; } //[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647 internal override bool BuildVisualTree(FrameworkElement container) { bool tracingEnabled = EventTrace.IsEnabled(EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info); if (tracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringBegin, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, "ContentPresenter.BuildVisualTree"); } try { ContentPresenter cp = (ContentPresenter)container; Visual result = DefaultExpansion(cp.Content, cp); return (result != null); } finally { if (tracingEnabled) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientStringEnd, EventTrace.Keyword.KeywordGeneral, EventTrace.Level.Info, String.Format(System.Globalization.CultureInfo.InvariantCulture, "ContentPresenter.BuildVisualTree for CP {0}", container.GetHashCode())); } } } private UIElement DefaultExpansion(object content, ContentPresenter container) { if (content == null) return null; TextBlock textBlock = CreateTextBlock(container); textBlock.IsContentPresenterContainer = true; // this is done so that the TextBlock does not steal away the logical child if( container != null ) { StyleHelper.AddCustomTemplateRoot( container, textBlock, false, // Do not need to check for existing visual parent since we just created it true); // set treeState cache on the Text instance created } DoDefaultExpansion(textBlock, content, container); return textBlock; } private void DoDefaultExpansion(TextBlock textBlock, object content, ContentPresenter container) { Debug.Assert(!(content is String) && !(content is UIElement)); // these are handled by different templates Inline inline; if ((inline = content as Inline) != null) { textBlock.Inlines.Add(inline); } else { bool succeeded = false; string stringFormat; XmlLanguage language = container.Language; System.Globalization.CultureInfo culture = language.GetSpecificCulture(); container.CacheLanguage(language); if ((stringFormat = container.ContentStringFormat) != null) { try { stringFormat = Helper.GetEffectiveStringFormat(stringFormat); textBlock.Text = String.Format(culture, stringFormat, content); succeeded = true; } catch (FormatException) { } } if (!succeeded) { TypeConverter tc = TypeDescriptor.GetConverter(ReflectionHelper.GetReflectionType(content)); TypeContext context = new TypeContext(content); if (tc != null && (tc.CanConvertTo(context, typeof(String)))) { textBlock.Text = (string)tc.ConvertTo(context, culture, content, typeof(string)); } else { Debug.Assert(!(tc != null && tc.CanConvertTo(typeof(UIElement)))); // this is handled by a different template textBlock.Text = String.Format(culture, "{0}", content); } } } } // Some type converters need the actual object that will be converted // in order to answer the CanConvertTo question. (WPF's own CommandConverter // is an example - see Dev11 486918.) We make this object available // via ITypeDescriptorContext.Instance. private class TypeContext : ITypeDescriptorContext { object _instance; public TypeContext(object instance) { _instance = instance; } IContainer ITypeDescriptorContext.Container { get { return null; } } object ITypeDescriptorContext.Instance { get { return _instance; } } PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor { get { return null; } } void ITypeDescriptorContext.OnComponentChanged() {} bool ITypeDescriptorContext.OnComponentChanging() { return false; } object IServiceProvider.GetService(Type serviceType) { return null; } } } private class DefaultSelector : DataTemplateSelector { /// <summary> /// Override this method to return an app specific <seealso cref="Template"/>. /// </summary> /// <param name="item">The data content</param> /// <param name="container">The container in which the content is to be displayed</param> /// <returns>a app specific template to apply.</returns> public override DataTemplate SelectTemplate(object item, DependencyObject container) { DataTemplate template = null; // Lookup template for typeof(Content) in resource dictionaries. if (item != null) { template = (DataTemplate)FrameworkElement.FindTemplateResourceInternal(container, item, typeof(DataTemplate)); } // default templates for well known types: if (template == null) { TypeConverter tc = null; string s; if ((s = item as string) != null) template = ((ContentPresenter)container).SelectTemplateForString(s); else if (item is UIElement) template = UIElementContentTemplate; else if (SystemXmlHelper.IsXmlNode(item)) template = ((ContentPresenter)container).SelectTemplateForXML(); else if (item is Inline) template = DefaultContentTemplate; else if (item != null && (tc = TypeDescriptor.GetConverter(ReflectionHelper.GetReflectionType(item))) != null && tc.CanConvertTo(typeof(UIElement))) template = UIElementContentTemplate; else template = DefaultContentTemplate; } return template; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private DataTemplate _templateCache; private bool _templateIsCurrent; private bool _contentIsItem; private XmlLanguage _language; private static DataTemplate s_AccessTextTemplate; private static DataTemplate s_StringTemplate; private static DataTemplate s_XmlNodeTemplate; private static DataTemplate s_UIElementTemplate; private static DataTemplate s_DefaultTemplate; private static DefaultSelector s_DefaultTemplateSelector; private static readonly UncommonField<DataTemplate> XMLFormattingTemplateField = new UncommonField<DataTemplate>(); private static readonly UncommonField<DataTemplate> StringFormattingTemplateField = new UncommonField<DataTemplate>(); private static readonly UncommonField<DataTemplate> AccessTextFormattingTemplateField = new UncommonField<DataTemplate>(); } }
using System; using System.Collections; using System.Runtime.InteropServices; using System.Windows.Forms; using GuruComponents.Netrix; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.WebEditing; using GuruComponents.Netrix.WebEditing.Elements; using System.Web.UI.WebControls; namespace GuruComponents.Netrix.WebEditing.DragDrop { /// <summary> /// Handles incoming drop events. Caller should prepare objects to insert elements, otherwise text /// will inserted as plain ascii into HTML. /// </summary> /// <remarks> /// Rev II: JK /// </remarks> internal class DropTarget : Interop.IOleDropTarget { private HtmlEditor htmlEditor; private Interop.IOleDropTarget _originalDropTarget; private DropInfo _dropInfo; private DataObject _currentDataObj; private IntPtr dataObjectPtr; private DragDropCommands dragData; private static Hashtable DragIcons; private static Hashtable DragCursor; private int DragPointX, DragPointY; private IElement nativeElement = null; private static Guid guid = new Guid("0000010E-0000-0000-C000-000000000046"); internal DropTarget(HtmlEditor htmlEditor, DataObjectConverter dataObjectConverter, Interop.IOleDropTarget pDropTarget) { this.htmlEditor = htmlEditor; _originalDropTarget = pDropTarget; _dropInfo = new DropInfo(); _dropInfo.Converter = dataObjectConverter; if (DragIcons == null) { DragIcons = new Hashtable(21); DragIcons.Add(DragDropCommands.Anchor, "WSIconAnchor.ico"); DragIcons.Add(DragDropCommands.Break, "WSIconBreak.ico"); DragIcons.Add(DragDropCommands.Button, "WSIconButton.ico"); DragIcons.Add(DragDropCommands.Div, "WSIconDIV.ico"); DragIcons.Add(DragDropCommands.Form, "WSIconForm.ico"); DragIcons.Add(DragDropCommands.HorizontalRule, "WSIconHRule.ico"); DragIcons.Add(DragDropCommands.Textbox, "WSIconInputText.ico"); DragIcons.Add(DragDropCommands.Checkbox, "WSIconInputCheckBox.ico"); DragIcons.Add(DragDropCommands.RadioButton, "WSIconInputRadioButton.ico"); DragIcons.Add(DragDropCommands.SubmitButton, "WSIconOKButton.ico"); DragIcons.Add(DragDropCommands.ListBox, "WSIconSelectList.ico"); DragIcons.Add(DragDropCommands.DropDown, "WSIconDropDownList.ico"); DragIcons.Add(DragDropCommands.Paragraph, "WSIconParagraph.ico"); DragIcons.Add(DragDropCommands.FileButton, "WSIconFileButton.ico"); DragIcons.Add(DragDropCommands.Password, "WSIconInputPassW.ico"); DragIcons.Add(DragDropCommands.ResetButton, "WSIconButton.ico"); DragIcons.Add(DragDropCommands.ImageButton, "WSIconInputImage.ico"); DragIcons.Add(DragDropCommands.HiddenField, "WSIconInputHidden.ico"); DragIcons.Add(DragDropCommands.Span, "WSIconSpan.ico"); DragIcons.Add(DragDropCommands.Image, "WSIconImage.ico"); DragIcons.Add(DragDropCommands.Table, "WSIconTable.ico"); DragIcons.Add(DragDropCommands.TextArea, "WSIconTextArea.ico"); } DragCursor = new Hashtable(); System.IO.Stream st; string s = "GuruComponents.Netrix.Resources.DragCursors."; st = this.GetType().Assembly.GetManifestResourceStream(String.Concat(s, "DefaultNot.ico")); DragCursor.Add("DefaultNot.ico", new System.Windows.Forms.Cursor(st)); st = this.GetType().Assembly.GetManifestResourceStream(String.Concat(s, "DefaultMove.ico")); DragCursor.Add("DefaultMove.ico", new System.Windows.Forms.Cursor(st)); st = this.GetType().Assembly.GetManifestResourceStream(String.Concat(s, "DefaultCopy.ico")); DragCursor.Add("DefaultCopy.ico", new System.Windows.Forms.Cursor(st)); } private void GetMouseCursor(DragDropCommands element) { string s = "GuruComponents.Netrix.Resources.DragCursors."; switch (element) { case DragDropCommands.DefaultNot: this.htmlEditor.Cursor = (Cursor) DragCursor["DefaultNot.ico"]; this.htmlEditor.Exec(Interop.IDM.OVERRIDE_CURSOR, true); break; case DragDropCommands.DefaultMove: this.htmlEditor.Cursor = (Cursor) DragCursor["DefaultMove.ico"]; this.htmlEditor.Exec(Interop.IDM.OVERRIDE_CURSOR, true); break; case DragDropCommands.DefaultCopy: this.htmlEditor.Cursor = (Cursor) DragCursor["DefaultCopy.ico"]; this.htmlEditor.Exec(Interop.IDM.OVERRIDE_CURSOR, true); break; default: s = String.Concat(s, DragIcons[element].ToString()); if (DragIcons.ContainsKey(element)) { SetCursorFromRessource(s); } break; } } private void SetCursorFromRessource(string s) { System.IO.Stream st = this.GetType().Assembly.GetManifestResourceStream(s); this.htmlEditor.Cursor = new System.Windows.Forms.Cursor(st); this.htmlEditor.Exec(Interop.IDM.OVERRIDE_CURSOR, true); } #region IOleDropTarget Member public int OleDragLeave() { this._dropInfo.ConverterInfo = DataObjectConverterInfo.Disabled; int result = Interop.S_OK; if (this._currentDataObj != null) { this._currentDataObj = null; if (!dataObjectPtr.Equals(IntPtr.Zero)) { Marshal.Release(this.dataObjectPtr); } this.dataObjectPtr = IntPtr.Zero; result = this._originalDropTarget.OleDragLeave(); } this.htmlEditor.OnDragLeave(); return result; } public int OleDragEnter(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect) { // check for AllowDrop if (this.htmlEditor.AllowDrop == false) return Interop.S_FALSE; int left = (int) (pt & 0xFFFF); int top = (int) (pt >> 32) & 0xFFFF; this.DragPointX = left; this.DragPointY = top; int result = Interop.S_OK; object o = Marshal.GetObjectForIUnknown(pDataObj); _currentDataObj = new DataObject(o); IntPtr cptr; this._dropInfo.ConverterInfo = this._dropInfo.Converter.CanConvertToHtml(_currentDataObj); switch (this._dropInfo.ConverterInfo) { case DataObjectConverterInfo.Native: nativeElement = GetElementFromData(); if (nativeElement == null) { this._dropInfo.ConverterInfo = DataObjectConverterInfo.Unhandled; goto case DataObjectConverterInfo.Unhandled; } // let's drop HTML but keep the serialized element DataObject foolcurrentDataObj = new DataObject(DataFormats.Html, nativeElement.OuterHtml); IntPtr fooldataObjectPtr = Marshal.GetIUnknownForObject(foolcurrentDataObj); Marshal.QueryInterface(fooldataObjectPtr, ref guid, out cptr); Marshal.Release(fooldataObjectPtr); result = this._originalDropTarget.OleDragEnter(cptr, grfKeyState, pt, ref pdwEffect); break; case DataObjectConverterInfo.CanConvert: object data = _currentDataObj.GetData(DataFormats.Serializable); dragData = (DragDropCommands) data; GetMouseCursor(dragData); this._currentDataObj = new DataObject(DataFormats.Html, String.Empty); dataObjectPtr = Marshal.GetIUnknownForObject(this._currentDataObj); Marshal.QueryInterface(dataObjectPtr, ref guid, out cptr); Marshal.Release(dataObjectPtr); result = this._originalDropTarget.OleDragEnter(cptr, grfKeyState, pt, ref pdwEffect); break; case DataObjectConverterInfo.Disabled: result = Interop.S_FALSE; break; case DataObjectConverterInfo.Text: case DataObjectConverterInfo.Unhandled: try { result = this._originalDropTarget.OleDragEnter(pDataObj, grfKeyState, pt, ref pdwEffect); System.Diagnostics.Debug.WriteLine(_currentDataObj.GetData(DataFormats.Html)); } catch { } break; case DataObjectConverterInfo.Externally: result = Interop.S_OK; break; } DragEventArgs drgevent = CreateEventArgs(grfKeyState, left, top, (DragDropEffects)pdwEffect, (DragDropEffects)pdwEffect); this.htmlEditor.OnDragEnter(drgevent); return result; } public int OleDragOver(int grfKeyState, long pt, ref int pdwEffect) { int result = Interop.S_OK; int x = (int) (pt & 0xFFFF); int y = (int) (pt >> 32) & 0xFFFF; // supress flicker if (x != this.DragPointX || y != this.DragPointY) { GetMouseCursor(dragData); this.DragPointX = x; this.DragPointY = y; switch (this._dropInfo.ConverterInfo) { case DataObjectConverterInfo.Native: case DataObjectConverterInfo.CanConvert: long pt2 = (x - 4) + ((long)(y - 16) << 32); result = this._originalDropTarget.OleDragOver(grfKeyState, pt2, ref pdwEffect); break; case DataObjectConverterInfo.Text: case DataObjectConverterInfo.Unhandled: { this.htmlEditor.Focus(); result = this._originalDropTarget.OleDragOver(grfKeyState, pt, ref pdwEffect); break; } case DataObjectConverterInfo.Externally: result = Interop.S_OK; this.htmlEditor.Exec(Interop.IDM.OVERRIDE_CURSOR, false); break; } } DragEventArgs drgevent = CreateEventArgs(grfKeyState, x, y, (DragDropEffects)pdwEffect, (DragDropEffects)pdwEffect); pdwEffect = (int)drgevent.AllowedEffect; this.htmlEditor.OnDragOver(drgevent); return result; } public int OleDrop(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect) { int result = Interop.S_OK; Control hostControl; Form hostForm; hostControl = this.htmlEditor; while (hostControl != null) { hostControl = hostControl.Parent; hostForm = hostControl as Form; if (hostForm == null) continue; hostForm.BringToFront(); break; } int left = (int)(pt & 0xFFFF); int top = (int)(pt >> 32) & 0xFFFF; long pt2; object o = Marshal.GetObjectForIUnknown(pDataObj); _currentDataObj = new DataObject(o); IntPtr cptr; switch (this._dropInfo.ConverterInfo) { case DataObjectConverterInfo.Native: // Create new DataObject if (nativeElement == null) { this._dropInfo.ConverterInfo = DataObjectConverterInfo.Unhandled; goto case DataObjectConverterInfo.Unhandled; } string id = nativeElement.GetAttribute("id") as string; string tempId = Guid.NewGuid().ToString(); nativeElement.SetAttribute("id", tempId); DataObject foolcurrentDataObj = new DataObject(DataFormats.Html, nativeElement.OuterHtml); IntPtr fooldataObjectPtr = Marshal.GetIUnknownForObject(foolcurrentDataObj); Marshal.QueryInterface(fooldataObjectPtr, ref guid, out cptr); Marshal.Release(fooldataObjectPtr); pt2 = (left - 4) + ((long)(top - 16) << 32); result = this._originalDropTarget.OleDrop(cptr, grfKeyState, pt, ref pdwEffect); nativeElement = htmlEditor.GetElementById(tempId); nativeElement.SetAttribute("id", id); break; case DataObjectConverterInfo.CanConvert: object data = _currentDataObj.GetData(DataFormats.Serializable); dragData = (DragDropCommands)data; this._currentDataObj = new DataObject(DataFormats.Html, String.Empty); pDataObj = Marshal.GetIUnknownForObject(this._currentDataObj); Marshal.QueryInterface(dataObjectPtr, ref guid, out cptr); Marshal.Release(dataObjectPtr); pt2 = (left - 4) + ((long)(top - 16) << 32); result = this._originalDropTarget.OleDrop(cptr, grfKeyState, pt2, ref pdwEffect); break; case DataObjectConverterInfo.Text: case DataObjectConverterInfo.Unhandled: result = this._originalDropTarget.OleDrop(pDataObj, grfKeyState, pt, ref pdwEffect); break; case DataObjectConverterInfo.Externally: result = Interop.S_OK; break; } if (nativeElement != null) { SetElementPositioning(nativeElement, left, top); _currentDataObj.SetData(typeof(IElement), nativeElement); } DragEventArgs drgevent = CreateEventArgs(grfKeyState, left, top, (DragDropEffects)pdwEffect, (DragDropEffects)pdwEffect); this.htmlEditor.OnDragDrop(drgevent); pdwEffect = (int)drgevent.AllowedEffect; return result; } private DragEventArgs CreateEventArgs(int grfKeyState, int left, int top, DragDropEffects pdw1, DragDropEffects pdw2) { DragEventArgs drgevent = new DragEventArgs(_currentDataObj, grfKeyState, left, top, pdw1, pdw2); return drgevent; } #endregion //private int SetCaretToPointer(int grfKeyState, int x, int y, ref int pdwEffect) //{ // if (IsInAbsolutePositionMode) return Interop.S_OK; // // Set caret only if not in absolute position mode... // // Keystate: 4 = SHFT, 8 = CTRL, 32 = ALT, Bit 1 is set Left Mouse, 2 is Right Mouse // // if ((grfKeyState & 0x4) == 0x4) // // { // // pdwEffect = (int) Interop.DROPEFFECTS.DROPEFFECT_COPY; // // } // // else // // { // // pdwEffect = (int) Interop.DROPEFFECTS.DROPEFFECT_MOVE; // // } // Interop.IDisplayServices ds = (Interop.IDisplayServices)this.htmlEditor.GetActiveDocument(true); // Interop.IDisplayPointer pDispPointer; // Interop.IHTMLElement pElement; // ds.CreateDisplayPointer(out pDispPointer); // Interop.POINT ptPoint = new GuruComponents.Netrix.ComInterop.Interop.POINT(); // ptPoint.x = x - 4; // ptPoint.y = y - 16; // uint res; // try // { // pDispPointer.MoveToPoint(ptPoint, Interop.COORD_SYSTEM.COORD_SYSTEM_CONTAINER, null, 0, out res); // } // catch // { // // Need to catch cause some regions fail // } // Interop.IHTMLCaret cr; // ds.GetCaret(out cr); // cr.MoveDisplayPointerToCaret(pDispPointer); // pDispPointer.GetFlowElement(out pElement); // Interop.IHTMLElement3 p3Element = (Interop.IHTMLElement3)pElement; // if (p3Element.contentEditable.Equals("false") || !p3Element.canHaveHTML) // { // return Interop.S_FALSE; // } // cr.MoveCaretToPointerEx(pDispPointer, true, true, Interop.CARET_DIRECTION.CARET_DIRECTION_SAME); // cr.Show(true); // return Interop.S_OK; //} ///// <summary> ///// Fires the Drop event with the current selection. ///// </summary> //private void OnDragDrop(IntPtr pDataObj, int grfKeyState, long pt, ref int pdwEffect) //{ // Interop.IHTMLSelectionObject selectionObj = htmlEditor.GetActiveDocument(false).GetSelection(); // object currentSelection = null; // //DataObject iData = null; // try // { // currentSelection = selectionObj.CreateRange(); // } // catch // { // currentSelection = null; // } // // extract the xy coordinates from the screen pointer parameter // int left = (int) (pt & 0xFFFF); // int top = (int) (pt >> 32) & 0xFFFF; // if (currentSelection != null && this._converterInfo != DataObjectConverterInfo.Externally) // { // Interop.IHTMLElement el; // if (currentSelection is Interop.IHTMLControlRange) // { // GuruComponents.Netrix.WebEditing.Elements.IElement droppedElement = null; // Interop.IHTMLControlRange ctrRange = (Interop.IHTMLControlRange) currentSelection; // if (ctrRange.length == 1) // { // el = (Interop.IHTMLElement) ctrRange.item(0); // droppedElement = (IElement) htmlEditor.GenericElementFactory.CreateElement(el); // SetElementPositioning(droppedElement, left, top); // _currentDataObj = new DataObject("GuruComponents.Netrix.WebEditing.Elements.IElement", droppedElement); // } // } // if (currentSelection is Interop.IHTMLTxtRange) // { // Interop.IHTMLTxtRange textRange = (Interop.IHTMLTxtRange) currentSelection; // Interop.IHTMLElement textElement = textRange.ParentElement(); // if (textElement != null && textElement.GetTagName().ToLower().Equals("body") || textElement == null) // { // string txt = textRange.GetText(); // string html = textRange.GetHtmlText(); // //if (IsInAbsolutePositionMode) // //{ // // iData = new DataObject(DataFormats.Html, html); // //} // //else // //{ // // iData = new DataObject(DataFormats.Text, txt); // //} // } // else // { // IElement droppedTextElement = (IElement) htmlEditor.GenericElementFactory.CreateElement(textElement); // SetElementPositioning(droppedTextElement, left, top); // _currentDataObj = new DataObject("GuruComponents.Netrix.WebEditing.Elements.IElement", droppedTextElement); // } // } // } // //else // //{ // // object pDataPtr = Marshal.GetObjectForIUnknown(pDataObj); // // iData = new DataObject(pDataPtr); // //} // DragEventArgs drgevent = new DragEventArgs(_currentDataObj, grfKeyState, left, top, (DragDropEffects)pdwEffect, (DragDropEffects)pdwEffect); // this.htmlEditor.OnDragDrop(drgevent); // pdwEffect = (int) drgevent.AllowedEffect; //} private IElement GetElementFromData() { IElement element; foreach (string format in _currentDataObj.GetFormats()) { switch (format) { case "GuruComponents.Netrix.WebEditing.Elements.IElement": element = (IElement)_currentDataObj.GetData("GuruComponents.Netrix.WebEditing.Elements.IElement"); return element; default: return null; } } return null; } private void SetElementPositioning(IElement droppedElement, int left, int top) { if (droppedElement == null) { IElement newElement = htmlEditor.Selection.Element; if (htmlEditor.AbsolutePositioningEnabled) { htmlEditor.AbsolutePositioningEnabled = false; htmlEditor.AbsolutePositioningEnabled = true; if (newElement != null) { newElement.SetStyleAttribute("position", "absolute"); System.Drawing.Point dropPoint = htmlEditor.PointToScreen(System.Drawing.Point.Empty); newElement.CurrentStyle.left = Unit.Pixel(left - dropPoint.X); newElement.CurrentStyle.top = Unit.Pixel(top - dropPoint.Y); } } else { if (newElement != null) { newElement.RemoveStyleAttribute("position"); } } } else { // if absolute positioning is enabled if (htmlEditor.AbsolutePositioningEnabled) { IElement element = droppedElement; element.SetStyleAttribute("position", "absolute"); // offset from screen System.Drawing.Point dropPoint = htmlEditor.PointToScreen(System.Drawing.Point.Empty); // set element to drop position element.CurrentStyle.left = Unit.Pixel(left - dropPoint.X); element.CurrentStyle.top = Unit.Pixel(top - dropPoint.Y); } else { ((IElement)droppedElement).RemoveStyleAttribute("position"); } } } } }
// 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; #if CAP_TypeOfPointer namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess01.arrayaccess01; // <Area> dynamic in unsafe code </Area> // <Title>pointer operator</Title> // <Description> // member access // </Description> // <RelatedBug>564384</RelatedBug> //<Expects Status=success></Expects> // <Code> [TestClass] unsafe public class Test { [Test] [Priority(Priority.Priority0)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); } public static int MainMethod(string[] args) { int* ptr = stackalloc int[10]; for (int i = 0; i < 10; i++) { *(ptr + i) = i; } dynamic d = 5; int x = ptr[d]; if (x != 5) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.arrayaccess02.arrayaccess02; // <Area> dynamic with pointer indexer </Area> // <Title>pointer operator</Title> // <Description> // member access // </Description> // <RelatedBug></RelatedBug> //<Expects Status=success></Expects> // <Code> [TestClass] unsafe public class Test { [Test] [Priority(Priority.Priority0)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); } public static int MainMethod(string[] args) { int* ptr = stackalloc int[10]; for (int i = 0; i < 10; i++) { *(ptr + i) = i; } int test = 0, success = 0; dynamic d; int x; test++; d = (uint)5; x = ptr[d]; if (x == 5) success++; test++; d = (ulong)5; x = ptr[d]; if (x == 5) success++; test++; d = (long)5; x = ptr[d]; if (x == 5) success++; return test == success ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.sizeof01.sizeof01; // <Area> dynamic in unsafe code </Area> // <Title>pointer operator</Title> // <Description> // sizeof operator // </Description> // <RelatedBug></RelatedBug> //<Expects Status=success></Expects> // <Code> [TestClass] unsafe public class Test { [Test] [Priority(Priority.Priority1)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = sizeof(int); return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.stackalloc01.stackalloc01; // <Area> dynamic in unsafe code </Area> // <Title>pointer operator</Title> // <Description> // stackalloc // </Description> // <RelatedBug></RelatedBug> //<Expects Status=success></Expects> // <Code> [TestClass] unsafe public class Test { [Test] [Priority(Priority.Priority1)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 10; int* ptr = stackalloc int[d]; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.unsfe.PointegeregererOperator.pointegeregerertype01.pointegeregerertype01; // <Area> dynamic in unsafe code </Area> // <Title>Regression</Title> // <Description> // VerificationException thrown when dynamically dispatching a method call with out/ref arguments which are pointer types // </Description> // <RelatedBug></RelatedBug> // <Expects Status=success></Expects> // <Code> using System; using System.Security; [TestClass] public class TestClass { public unsafe void Method(out int* arg) { arg = (int*)5; } } struct Driver { [Test] [Priority(Priority.Priority2)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); } public static unsafe int MainMethod() { int* ptr = null; dynamic tc = new TestClass(); try { tc.Method(out ptr); } catch (VerificationException e) { return 0; //this was won't fix } return 1; } } // </Code> } #endif
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; namespace WebsitePanel.Providers.Mail { public class Tree { private TreeNodeCollection childNodes; public TreeNodeCollection ChildNodes { get { return childNodes; } } public Tree() { childNodes = new TreeNodeCollection(); } public void Serialize(StringBuilder builder) { foreach(TreeNode node in childNodes.ToArray()) node.Serialize(builder); } } public class TreeNodeCollection : ICollection<TreeNode> { private List<TreeNode> _collection; private Dictionary<string, TreeNode> _searchIndex; public TreeNode this[string keyName] { get { if (_searchIndex.ContainsKey(keyName)) return _searchIndex[keyName]; return null; } } public TreeNodeCollection() { _collection = new List<TreeNode>(); _searchIndex = new Dictionary<string, TreeNode>(); } public void Add(TreeNode node) { string keyName = node.NodeName; _collection.Add(node); if (keyName != TreeNode.Unnamed) _searchIndex.Add(keyName, node); } public TreeNode[] ToArray() { return _collection.ToArray(); } #region ICollection<TreeNode> Members public void Clear() { _collection.Clear(); } public bool Contains(TreeNode item) { return _collection.Contains(item); } public void CopyTo(TreeNode[] array, int arrayIndex) { _collection.CopyTo(array, arrayIndex); } public int Count { get { return _collection.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(TreeNode item) { return _collection.Remove(item); } #endregion #region IEnumerable<TreeNode> Members public IEnumerator<TreeNode> GetEnumerator() { return _collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _collection.GetEnumerator(); } #endregion } public class TreeNode { private Tree root; private TreeNode parent; private TreeNodeCollection childNodes; private string nodeName; private string nodeValue; public const string Unnamed = "-"; public TreeNodeCollection ChildNodes { get { EnsureChildControlsCreated(); return childNodes; } } public bool IsUnnamed { get { return nodeName == Unnamed; } } public Tree Root { get { return root; } set { root = value; } } public TreeNode Parent { get { return parent; } set { parent = value; } } public string NodeName { get { return nodeName; } set { nodeName = value; } } public string NodeValue { get { return nodeValue; } set { nodeValue = value; } } public string this[string keyName] { get { EnsureChildControlsCreated(); TreeNode keyNode = childNodes[keyName]; if (keyNode != null) return keyNode.NodeValue; return null; } set { EnsureChildControlsCreated(); TreeNode keyNode = childNodes[keyName]; if (keyNode == null) { keyNode = new TreeNode(this); keyNode.NodeName = keyName; childNodes.Add(keyNode); } keyNode.NodeValue = value; } } public TreeNode(TreeNode parent) : this() { this.parent = parent; } public TreeNode() { this.nodeName = Unnamed; } private void EnsureChildControlsCreated() { if (childNodes == null) childNodes = new TreeNodeCollection(); } public virtual void Serialize(StringBuilder builder) { if (childNodes != null) { builder.AppendLine(string.Concat("{ ", nodeName)); foreach (TreeNode node in childNodes) node.Serialize(builder); builder.AppendLine("}"); } else { builder.AppendLine(string.Concat(nodeName, "=", nodeValue)); } } } }
// Unity built-in shader source. Copyright (c) 2016 Unity Technologies. MIT license (see license.txt) using System; using UnityEngine; namespace UnityEditor { internal class PbrShaderGUI : ShaderGUI { private enum WorkflowMode { SpecularGlossiness, MetallicRoughness, Unlit } public enum BlendMode { Opaque, Mask, Blend } private static class Styles { public static GUIContent albedoText = new GUIContent("Base Color", "Albedo (RGB) and Transparency (A)"); public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff"); public static GUIContent specularMapText = new GUIContent("Spec Gloss", "Specular (RGB) and Glossiness (A)"); public static GUIContent metallicMapText = new GUIContent("Metal Rough", "Metallic (B) and Roughness (G)"); public static GUIContent metallicText = new GUIContent("Metallic", "Metallic value"); public static GUIContent metallicScaleText = new GUIContent("Metallic", "Metallic scale factor"); public static GUIContent roughnessText = new GUIContent("Roughness", "Roughness value"); public static GUIContent roughnessScaleText = new GUIContent("Roughness", "Roughness scale factor"); public static GUIContent glossinessText = new GUIContent("Glossiness", "Glossiness value"); public static GUIContent glossinessScaleText = new GUIContent("Glossiness", "Glossiness scale factor"); public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map"); public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (R)"); public static GUIContent emissionText = new GUIContent("Emissive", "Emissive (RGB)"); public static string primaryMapsText = "Main Maps"; public static string renderingMode = "Rendering Mode"; public static GUIContent emissiveWarning = new GUIContent("Emissive value is animated but the material has not been configured to support emissive. Please make sure the material itself has some amount of emissive."); public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode)); } MaterialProperty blendMode = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty specularMap = null; MaterialProperty specularColor = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty occlusionStrength = null; MaterialProperty occlusionMap = null; MaterialProperty emissionColor = null; MaterialProperty emissionMap = null; MaterialEditor m_MaterialEditor; WorkflowMode m_WorkflowMode = WorkflowMode.MetallicRoughness; bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); specularMap = FindProperty("_SpecGlossMap", props, false); specularColor = FindProperty("_SpecColor", props, false); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); if (specularMap != null && specularColor != null) m_WorkflowMode = WorkflowMode.SpecularGlossiness; else if (metallicMap != null && metallic != null) m_WorkflowMode = WorkflowMode.MetallicRoughness; else m_WorkflowMode = WorkflowMode.Unlit; smoothness = FindProperty("_Glossiness", props); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); occlusionStrength = FindProperty("_OcclusionStrength", props); occlusionMap = FindProperty("_OcclusionMap", props); emissionColor = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; // Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing // material to a standard shader. // Do this before any GUI code has been issued to prevent layout issues in subsequent GUILayout statements (case 780071) if (m_FirstTimeApply) { MaterialChanged(material, m_WorkflowMode); m_FirstTimeApply = false; } ShaderPropertiesGUI(material); } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { BlendModePopup(); // Primary properties GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null); DoEmissionArea(material); EditorGUILayout.Space(); } if (EditorGUI.EndChangeCheck()) { foreach (var obj in blendMode.targets) MaterialChanged((Material)obj, m_WorkflowMode); } } internal void DetermineWorkflow(MaterialProperty[] props) { if (FindProperty("_SpecGlossMap", props, false) != null && FindProperty("_SpecColor", props, false) != null) m_WorkflowMode = WorkflowMode.SpecularGlossiness; else if (FindProperty("_MetallicGlossMap", props, false) != null && FindProperty("_Metallic", props, false) != null) m_WorkflowMode = WorkflowMode.MetallicRoughness; else m_WorkflowMode = WorkflowMode.Unlit; } void BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Mask)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1); } } void DoEmissionArea(Material material) { bool hadEmissionTexture = emissionMap.textureValue != null; // Texture and HDR color controls m_MaterialEditor.TexturePropertySingleLine(Styles.emissionText, emissionMap, emissionColor); // If texture was assigned and color was black set color to white float brightness = emissionColor.colorValue.maxColorComponent; if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f) emissionColor.colorValue = Color.white; } void DoSpecularMetallicArea() { bool hasGlossMap = false; if (m_WorkflowMode == WorkflowMode.SpecularGlossiness) { hasGlossMap = specularMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specularMap, hasGlossMap ? null : specularColor); m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.glossinessScaleText : Styles.glossinessText, 2); } else if (m_WorkflowMode == WorkflowMode.MetallicRoughness) { hasGlossMap = metallicMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap); m_MaterialEditor.ShaderProperty(metallic, hasGlossMap ? Styles.metallicScaleText : Styles.metallicText, 2); m_MaterialEditor.ShaderProperty(smoothness, hasGlossMap ? Styles.roughnessScaleText : Styles.roughnessText, 2); } } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode, float alphaCutoff) { switch (blendMode) { case BlendMode.Opaque: material.SetOverrideTag("RenderType", "Opaque"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry; break; case BlendMode.Mask: material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; material.SetFloat("_Cutoff", alphaCutoff); break; case BlendMode.Blend: material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; } material.SetFloat("_Mode", (float)blendMode); } static void SetMaterialKeywords(Material material, WorkflowMode workflowMode) { // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap")); if (workflowMode == WorkflowMode.SpecularGlossiness) SetKeyword(material, "_SPECGLOSSMAP", material.GetTexture("_SpecGlossMap")); else if (workflowMode == WorkflowMode.MetallicRoughness) SetKeyword(material, "_METALLICGLOSSMAP", material.GetTexture("_MetallicGlossMap")); bool shouldEmissionBeEnabled = material.GetColor("_EmissionColor") != Color.black; SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled); } static void MaterialChanged(Material material, WorkflowMode workflowMode) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), material.GetFloat("_Cutoff")); SetMaterialKeywords(material, workflowMode); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } // namespace UnityEditor
// // Copyright (c) 2004-2017 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. // #if !NETSTANDARD #define DISABLE_FILE_INTERNAL_LOGGING namespace NLog.UnitTests.Targets { using System; using System.Diagnostics; using System.IO; using System.Threading; using NLog.Config; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; using Xunit.Extensions; public class ConcurrentFileTargetTests : NLogTestBase { private ILogger logger = LogManager.GetLogger("NLog.UnitTests.Targets.ConcurrentFileTargetTests"); private void ConfigureSharedFile(string mode, string fileName) { var modes = mode.Split('|'); FileTarget ft = new FileTarget(); ft.FileName = fileName; ft.Layout = "${message}"; ft.KeepFileOpen = true; ft.OpenFileCacheTimeout = 10; ft.OpenFileCacheSize = 1; ft.LineEnding = LineEndingMode.LF; ft.KeepFileOpen = Array.IndexOf(modes, "retry") >= 0 ? false : true; ft.ForceMutexConcurrentWrites = Array.IndexOf(modes, "mutex") >= 0 ? true : false; ft.ArchiveAboveSize = Array.IndexOf(modes, "archive") >= 0 ? 50 : -1; if (ft.ArchiveAboveSize > 0) { string archivePath = Path.Combine(Path.GetDirectoryName(fileName), "Archive"); ft.ArchiveFileName = Path.Combine(archivePath, "{####}_" + Path.GetFileName(fileName)); ft.MaxArchiveFiles = 10000; } var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper"; switch (modes[0]) { case "async": SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow) { Name = name, TimeToSleepBetweenBatches = 10 }, LogLevel.Debug); break; case "buffered": SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100) { Name = name }, LogLevel.Debug); break; case "buffered_timed_flush": SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10) { Name = name }, LogLevel.Debug); break; default: SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); break; } } #pragma warning disable xUnit1013 // Needed for test public void Process(string processIndex, string fileName, string numLogsString, string mode) #pragma warning restore xUnit1013 { Thread.CurrentThread.Name = processIndex; int numLogs = Convert.ToInt32(numLogsString); int idxProcess = Convert.ToInt32(processIndex); ConfigureSharedFile(mode, fileName); string format = processIndex + " {0}"; // Having the internal logger enabled would just slow things down, reducing the // likelyhood for uncovering racing conditions. Uncomment #define DISABLE_FILE_INTERNAL_LOGGING #if !DISABLE_FILE_INTERNAL_LOGGING var logWriter = new StringWriter { NewLine = Environment.NewLine }; NLog.Common.InternalLogger.LogLevel = LogLevel.Trace; NLog.Common.InternalLogger.LogFile = Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)); NLog.Common.InternalLogger.LogWriter = logWriter; NLog.Common.InternalLogger.LogToConsole = true; try #endif { Thread.Sleep(Math.Max((10 - idxProcess), 1) * 5); // Delay to wait for the other processes for (int i = 0; i < numLogs; ++i) { logger.Debug(format, i); } LogManager.Configuration = null; // Flush + Close } #if !DISABLE_FILE_INTERNAL_LOGGING catch (Exception ex) { using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)))) { textWriter.WriteLine(ex.ToString()); textWriter.WriteLine(logWriter.GetStringBuilder().ToString()); } throw; } using (var textWriter = File.AppendText(Path.Combine(Path.GetDirectoryName(fileName), string.Format("Internal_{0}.txt", processIndex)))) { textWriter.WriteLine(logWriter.GetStringBuilder().ToString()); } #endif } private string MakeFileName(int numProcesses, int numLogs, string mode) { // Having separate filenames for the various tests makes debugging easier. return $"test_{numProcesses}_{numLogs}_{mode.Replace('|', '_')}.txt"; } private void DoConcurrentTest(int numProcesses, int numLogs, string mode) { string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archivePath = Path.Combine(tempPath, "Archive"); try { Directory.CreateDirectory(tempPath); Directory.CreateDirectory(archivePath); string logFile = Path.Combine(tempPath, MakeFileName(numProcesses, numLogs, mode)); if (File.Exists(logFile)) File.Delete(logFile); Process[] processes = new Process[numProcesses]; for (int i = 0; i < numProcesses; ++i) { processes[i] = ProcessRunner.SpawnMethod( GetType(), "Process", i.ToString(), logFile, numLogs.ToString(), mode); } // In case we'd like to capture stdout, we would need to drain it continuously. // StandardOutput.ReadToEnd() wont work, since the other processes console only has limited buffer. for (int i = 0; i < numProcesses; ++i) { processes[i].WaitForExit(); Assert.Equal(0, processes[i].ExitCode); processes[i].Dispose(); processes[i] = null; } var files = new System.Collections.Generic.List<string>(Directory.GetFiles(archivePath)); files.Add(logFile); bool verifyFileSize = files.Count > 1; int[] maxNumber = new int[numProcesses]; //Console.WriteLine("Verifying output file {0}", logFile); foreach (var file in files) { using (StreamReader sr = File.OpenText(file)) { string line; while ((line = sr.ReadLine()) != null) { string[] tokens = line.Split(' '); Assert.Equal(2, tokens.Length); try { int thread = Convert.ToInt32(tokens[0]); int number = Convert.ToInt32(tokens[1]); Assert.True(thread >= 0); Assert.True(thread < numProcesses); Assert.Equal(maxNumber[thread], number); maxNumber[thread]++; } catch (Exception ex) { throw new InvalidOperationException($"Error when parsing line '{line}' in file {file}", ex); } } if (verifyFileSize) { if (sr.BaseStream.Length > 100) throw new InvalidOperationException( $"Error when reading file {file}, size {sr.BaseStream.Length} is too large"); else if (sr.BaseStream.Length < 35 && files[files.Count - 1] != file) throw new InvalidOperationException( $"Error when reading file {file}, size {sr.BaseStream.Length} is too small"); } } } } finally { try { if (Directory.Exists(archivePath)) Directory.Delete(archivePath, true); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } catch { } } } [Theory] [InlineData(2, 10000, "none")] [InlineData(5, 4000, "none")] [InlineData(10, 2000, "none")] #if !MONO // MONO Doesn't work well with global mutex, and it is needed for succesful concurrent archive operations [InlineData(2, 500, "none|archive")] [InlineData(2, 500, "none|mutex|archive")] [InlineData(2, 10000, "none|mutex")] [InlineData(5, 4000, "none|mutex")] [InlineData(10, 2000, "none|mutex")] #endif public void SimpleConcurrentTest(int numProcesses, int numLogs, string mode) { DoConcurrentTest(numProcesses, numLogs, mode); } [Theory] [InlineData("async")] #if !MONO [InlineData("async|mutex")] #endif public void AsyncConcurrentTest(string mode) { // Before 2 processes are running into concurrent writes, // the first process typically already has written couple thousend events. // Thus to have a meaningful test, at least 10K events are required. // Due to the buffering it makes no big difference in runtime, whether we // have 2 process writing 10K events each or couple more processes with even more events. // Runtime is mostly defined by Runner.exe compilation and JITing the first. DoConcurrentTest(5, 1000, mode); } [Theory] [InlineData("buffered")] #if !MONO [InlineData("buffered|mutex")] #endif public void BufferedConcurrentTest(string mode) { DoConcurrentTest(5, 1000, mode); } [Theory] [InlineData("buffered_timed_flush")] #if !MONO [InlineData("buffered_timed_flush|mutex")] #endif public void BufferedTimedFlushConcurrentTest(string mode) { DoConcurrentTest(5, 1000, mode); } } } #endif
using System; using System.Collections.Generic; using Bedrock.Logging; using Bedrock.Modularity; using Bedrock.Tests.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Bedrock.Tests.Modularity { [TestClass] public class ModuleManagerFixture { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void NullLoaderThrows() { new ModuleManager(null, new MockModuleCatalog(), new MockLogger()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void NullCatalogThrows() { new ModuleManager(new MockModuleInitializer(), null, new MockLogger()); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void NullLoggerThrows() { new ModuleManager(new MockModuleInitializer(), new MockModuleCatalog(), null); } [TestMethod] public void ShouldInvokeRetrieverForModules() { var loader = new MockModuleInitializer(); var moduleInfo = CreateModuleInfo("needsRetrieval", InitializationMode.WhenAvailable); var catalog = new MockModuleCatalog { Modules = { moduleInfo } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); Assert.IsTrue(moduleTypeLoader.LoadedModules.Contains(moduleInfo)); } [TestMethod] public void ShouldInitializeModulesOnRetrievalCompleted() { var loader = new MockModuleInitializer(); var backgroungModuleInfo = CreateModuleInfo("NeedsRetrieval", InitializationMode.WhenAvailable); var catalog = new MockModuleCatalog { Modules = { backgroungModuleInfo } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; Assert.IsFalse(loader.InitializeCalled); manager.Run(); Assert.IsTrue(loader.InitializeCalled); Assert.AreEqual(1, loader.InitializedModules.Count); Assert.AreEqual(backgroungModuleInfo, loader.InitializedModules[0]); } [TestMethod] public void ShouldInitializeModuleOnDemand() { var loader = new MockModuleInitializer(); var onDemandModule = CreateModuleInfo("NeedsRetrieval", InitializationMode.OnDemand); var catalog = new MockModuleCatalog { Modules = { onDemandModule } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleRetriever = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleRetriever }; manager.Run(); Assert.IsFalse(loader.InitializeCalled); Assert.AreEqual(0, moduleRetriever.LoadedModules.Count); manager.LoadModule("NeedsRetrieval"); Assert.AreEqual(1, moduleRetriever.LoadedModules.Count); Assert.IsTrue(loader.InitializeCalled); Assert.AreEqual(1, loader.InitializedModules.Count); Assert.AreEqual(onDemandModule, loader.InitializedModules[0]); } [TestMethod] [ExpectedException(typeof(ModuleNotFoundException))] public void InvalidOnDemandModuleNameThrows() { var loader = new MockModuleInitializer(); var catalog = new MockModuleCatalog { Modules = new List<ModuleInfo> { CreateModuleInfo("Missing", InitializationMode.OnDemand) } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); manager.LoadModule("NonExistent"); } [TestMethod] [ExpectedException(typeof(ModuleNotFoundException))] public void EmptyOnDemandModuleReturnedThrows() { var loader = new MockModuleInitializer(); var catalog = new MockModuleCatalog { CompleteListWithDependencies = modules => new List<ModuleInfo>() }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleRetriever = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleRetriever }; manager.Run(); manager.LoadModule("NullModule"); } [TestMethod] public void ShouldNotLoadTypeIfModuleInitialized() { var loader = new MockModuleInitializer(); var alreadyPresentModule = CreateModuleInfo(typeof(MockModule), InitializationMode.WhenAvailable); alreadyPresentModule.State = ModuleState.ReadyForInitialization; var catalog = new MockModuleCatalog { Modules = { alreadyPresentModule } }; var manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); Assert.IsFalse(moduleTypeLoader.LoadedModules.Contains(alreadyPresentModule)); Assert.IsTrue(loader.InitializeCalled); Assert.AreEqual(1, loader.InitializedModules.Count); Assert.AreEqual(alreadyPresentModule, loader.InitializedModules[0]); } [TestMethod] public void ShouldNotLoadSameModuleTwice() { var loader = new MockModuleInitializer(); var onDemandModule = CreateModuleInfo(typeof(MockModule), InitializationMode.OnDemand); var catalog = new MockModuleCatalog { Modules = { onDemandModule } }; var manager = new ModuleManager(loader, catalog, new MockLogger()); manager.Run(); manager.LoadModule("MockModule"); loader.InitializeCalled = false; manager.LoadModule("MockModule"); Assert.IsFalse(loader.InitializeCalled); } [TestMethod] public void ShouldNotLoadModuleThatNeedsRetrievalTwice() { var loader = new MockModuleInitializer(); var onDemandModule = CreateModuleInfo("ModuleThatNeedsRetrieval", InitializationMode.OnDemand); var catalog = new MockModuleCatalog { Modules = { onDemandModule } }; var manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); manager.LoadModule("ModuleThatNeedsRetrieval"); moduleTypeLoader.RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(onDemandModule, null)); loader.InitializeCalled = false; manager.LoadModule("ModuleThatNeedsRetrieval"); Assert.IsFalse(loader.InitializeCalled); } [TestMethod] public void ShouldCallValidateCatalogBeforeGettingGroupsFromCatalog() { var loader = new MockModuleInitializer(); var catalog = new MockModuleCatalog(); var manager = new ModuleManager(loader, catalog, new MockLogger()); bool validateCatalogCalled = false; bool getModulesCalledBeforeValidate = false; catalog.ValidateCatalog = () => validateCatalogCalled = true; catalog.CompleteListWithDependencies = f => { if (!validateCatalogCalled) { getModulesCalledBeforeValidate = true; } return null; }; manager.Run(); Assert.IsTrue(validateCatalogCalled); Assert.IsFalse(getModulesCalledBeforeValidate); } [TestMethod] public void ShouldNotInitializeIfDependenciesAreNotMet() { var loader = new MockModuleInitializer(); var requiredModule = CreateModuleInfo("ModuleThatNeedsRetrieval1", InitializationMode.WhenAvailable); requiredModule.ModuleName = "RequiredModule"; var dependantModuleInfo = CreateModuleInfo("ModuleThatNeedsRetrieval2", InitializationMode.WhenAvailable, "RequiredModule"); var catalog = new MockModuleCatalog { Modules = { requiredModule, dependantModuleInfo } }; catalog.GetDependentModules = m => new[] { requiredModule }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); moduleTypeLoader.RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(dependantModuleInfo, null)); Assert.IsFalse(loader.InitializeCalled); Assert.AreEqual(0, loader.InitializedModules.Count); } [TestMethod] public void ShouldInitializeIfDependenciesAreMet() { var initializer = new MockModuleInitializer(); var requiredModule = CreateModuleInfo("ModuleThatNeedsRetrieval1", InitializationMode.WhenAvailable); requiredModule.ModuleName = "RequiredModule"; var dependantModuleInfo = CreateModuleInfo("ModuleThatNeedsRetrieval2", InitializationMode.WhenAvailable, "RequiredModule"); var catalog = new MockModuleCatalog { Modules = { requiredModule, dependantModuleInfo } }; catalog.GetDependentModules = delegate(ModuleInfo module) { if (module == dependantModuleInfo) return new[] { requiredModule }; else return null; }; ModuleManager manager = new ModuleManager(initializer, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; manager.Run(); Assert.IsTrue(initializer.InitializeCalled); Assert.AreEqual(2, initializer.InitializedModules.Count); } [TestMethod] public void ShouldThrowOnRetrieverErrorAndWrapException() { var loader = new MockModuleInitializer(); var moduleInfo = CreateModuleInfo("NeedsRetrieval", InitializationMode.WhenAvailable); var catalog = new MockModuleCatalog { Modules = { moduleInfo } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); var moduleTypeLoader = new MockModuleTypeLoader(); Exception retrieverException = new Exception(); moduleTypeLoader.LoadCompletedError = retrieverException; manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; Assert.IsFalse(loader.InitializeCalled); try { manager.Run(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(ModuleTypeLoadingException)); Assert.AreEqual(moduleInfo.ModuleName, ((ModularityException)ex).ModuleName); StringAssert.Contains(ex.Message, moduleInfo.ModuleName); Assert.AreSame(retrieverException, ex.InnerException); return; } Assert.Fail("Exception not thrown."); } [TestMethod] [ExpectedException(typeof(ModuleTypeLoaderNotFoundException))] public void ShouldThrowIfNoRetrieverCanRetrieveModule() { var loader = new MockModuleInitializer(); var catalog = new MockModuleCatalog { Modules = { CreateModuleInfo("ModuleThatNeedsRetrieval", InitializationMode.WhenAvailable) } }; ModuleManager manager = new ModuleManager(loader, catalog, new MockLogger()); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { new MockModuleTypeLoader() { canLoadModuleTypeReturnValue = false } }; manager.Run(); } [TestMethod] public void ShouldLogMessageOnModuleRetrievalError() { var loader = new MockModuleInitializer(); var moduleInfo = CreateModuleInfo("ModuleThatNeedsRetrieval", InitializationMode.WhenAvailable); var catalog = new MockModuleCatalog { Modules = { moduleInfo } }; var logger = new MockLogger(); ModuleManager manager = new ModuleManager(loader, catalog, logger); var moduleTypeLoader = new MockModuleTypeLoader(); moduleTypeLoader.LoadCompletedError = new Exception(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { moduleTypeLoader }; try { manager.Run(); } catch { // Ignore all errors to make sure logger is called even if errors thrown. } Assert.IsNotNull(logger.LastMessage); StringAssert.Contains(logger.LastMessage, "ModuleThatNeedsRetrieval"); Assert.AreEqual<Category>(Category.Exception, logger.LastMessageCategory); } [TestMethod] public void ShouldWorkIfModuleLoadsAnotherOnDemandModuleWhenInitializing() { var initializer = new StubModuleInitializer(); var onDemandModule = CreateModuleInfo(typeof(MockModule), InitializationMode.OnDemand); onDemandModule.ModuleName = "OnDemandModule"; var moduleThatLoadsOtherModule = CreateModuleInfo(typeof(MockModule), InitializationMode.WhenAvailable); var catalog = new MockModuleCatalog { Modules = { moduleThatLoadsOtherModule, onDemandModule } }; ModuleManager manager = new ModuleManager(initializer, catalog, new MockLogger()); bool onDemandModuleWasInitialized = false; initializer.Initialize = m => { if (m == moduleThatLoadsOtherModule) { manager.LoadModule("OnDemandModule"); } else if (m == onDemandModule) { onDemandModuleWasInitialized = true; } }; manager.Run(); Assert.IsTrue(onDemandModuleWasInitialized); } [TestMethod] public void ModuleManagerIsDisposable() { Mock<IModuleInitializer> mockInit = new Mock<IModuleInitializer>(); var moduleInfo = CreateModuleInfo("needsRetrieval", InitializationMode.WhenAvailable); var catalog = new Mock<IModuleCatalog>(); ModuleManager manager = new ModuleManager(mockInit.Object, catalog.Object, new MockLogger()); IDisposable disposableManager = manager as IDisposable; Assert.IsNotNull(disposableManager); } [TestMethod] public void DisposeDoesNotThrowWithNonDisposableTypeLoaders() { Mock<IModuleInitializer> mockInit = new Mock<IModuleInitializer>(); var moduleInfo = CreateModuleInfo("needsRetrieval", InitializationMode.WhenAvailable); var catalog = new Mock<IModuleCatalog>(); ModuleManager manager = new ModuleManager(mockInit.Object, catalog.Object, new MockLogger()); var mockTypeLoader = new Mock<IModuleTypeLoader>(); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> {mockTypeLoader.Object}; try { manager.Dispose(); } catch(Exception) { Assert.Fail(); } } [TestMethod] public void DisposeCleansUpDisposableTypeLoaders() { Mock<IModuleInitializer> mockInit = new Mock<IModuleInitializer>(); var moduleInfo = CreateModuleInfo("needsRetrieval", InitializationMode.WhenAvailable); var catalog = new Mock<IModuleCatalog>(); ModuleManager manager = new ModuleManager(mockInit.Object, catalog.Object, new MockLogger()); var mockTypeLoader = new Mock<IModuleTypeLoader>(); var disposableMockTypeLoader = mockTypeLoader.As<IDisposable>(); disposableMockTypeLoader.Setup(loader => loader.Dispose()); manager.ModuleTypeLoaders = new List<IModuleTypeLoader> { mockTypeLoader.Object }; manager.Dispose(); disposableMockTypeLoader.Verify(loader => loader.Dispose(), Times.Once()); } [TestMethod] public void DisposeDoesNotThrowWithMixedTypeLoaders() { Mock<IModuleInitializer> mockInit = new Mock<IModuleInitializer>(); var moduleInfo = CreateModuleInfo("needsRetrieval", InitializationMode.WhenAvailable); var catalog = new Mock<IModuleCatalog>(); ModuleManager manager = new ModuleManager(mockInit.Object, catalog.Object, new MockLogger()); var mockTypeLoader1 = new Mock<IModuleTypeLoader>(); var mockTypeLoader = new Mock<IModuleTypeLoader>(); var disposableMockTypeLoader = mockTypeLoader.As<IDisposable>(); disposableMockTypeLoader.Setup(loader => loader.Dispose()); manager.ModuleTypeLoaders = new List<IModuleTypeLoader>() { mockTypeLoader1.Object, mockTypeLoader.Object }; try { manager.Dispose(); } catch (Exception) { Assert.Fail(); } disposableMockTypeLoader.Verify(loader => loader.Dispose(), Times.Once()); } private static ModuleInfo CreateModuleInfo(string name, InitializationMode initializationMode, params string[] dependsOn) { ModuleInfo moduleInfo = new ModuleInfo(name, name); moduleInfo.InitializationMode = initializationMode; moduleInfo.DependsOn.AddRange(dependsOn); return moduleInfo; } private static ModuleInfo CreateModuleInfo(Type type, InitializationMode initializationMode, params string[] dependsOn) { ModuleInfo moduleInfo = new ModuleInfo(type.Name, type.AssemblyQualifiedName); moduleInfo.InitializationMode = initializationMode; moduleInfo.DependsOn.AddRange(dependsOn); return moduleInfo; } } internal class MockModule : IModule { public void Initialize() { throw new System.NotImplementedException(); } } internal class MockModuleCatalog : IModuleCatalog { public List<ModuleInfo> Modules = new List<ModuleInfo>(); public Func<ModuleInfo, IEnumerable<ModuleInfo>> GetDependentModules; public Func<IEnumerable<ModuleInfo>, IEnumerable<ModuleInfo>> CompleteListWithDependencies; public Action ValidateCatalog; public void Initialize() { if (this.ValidateCatalog != null) { this.ValidateCatalog(); } } IEnumerable<ModuleInfo> IModuleCatalog.Modules { get { return this.Modules; } } IEnumerable<ModuleInfo> IModuleCatalog.GetDependentModules(ModuleInfo moduleInfo) { if (GetDependentModules == null) return new List<ModuleInfo>(); return GetDependentModules(moduleInfo); } IEnumerable<ModuleInfo> IModuleCatalog.CompleteListWithDependencies(IEnumerable<ModuleInfo> modules) { if (CompleteListWithDependencies != null) return CompleteListWithDependencies(modules); return modules; } public void AddModule(ModuleInfo moduleInfo) { this.Modules.Add(moduleInfo); } } internal class MockModuleInitializer : IModuleInitializer { public bool InitializeCalled; public List<ModuleInfo> InitializedModules = new List<ModuleInfo>(); public void Initialize(ModuleInfo moduleInfo) { InitializeCalled = true; this.InitializedModules.Add(moduleInfo); } } internal class StubModuleInitializer : IModuleInitializer { public Action<ModuleInfo> Initialize; void IModuleInitializer.Initialize(ModuleInfo moduleInfo) { this.Initialize(moduleInfo); } } internal class MockDelegateModuleInitializer : IModuleInitializer { public Action<ModuleInfo> LoadBody; public void Initialize(ModuleInfo moduleInfo) { LoadBody(moduleInfo); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; // using log4net; // using System.Reflection; /***************************************************** * * WorldCommModule * * * Holding place for world comms - basically llListen * function implementation. * * lLListen(integer channel, string name, key id, string msg) * The name, id, and msg arguments specify the filtering * criteria. You can pass the empty string * (or NULL_KEY for id) for these to set a completely * open filter; this causes the listen() event handler to be * invoked for all chat on the channel. To listen only * for chat spoken by a specific object or avatar, * specify the name and/or id arguments. To listen * only for a specific command, specify the * (case-sensitive) msg argument. If msg is not empty, * listener will only hear strings which are exactly equal * to msg. You can also use all the arguments to establish * the most restrictive filtering criteria. * * It might be useful for each listener to maintain a message * digest, with a list of recent messages by UUID. This can * be used to prevent in-world repeater loops. However, the * linden functions do not have this capability, so for now * thats the way it works. * Instead it blocks messages originating from the same prim. * (not Object!) * * For LSL compliance, note the following: * (Tested again 1.21.1 on May 2, 2008) * 1. 'id' has to be parsed into a UUID. None-UUID keys are * to be replaced by the ZeroID key. (Well, TryParse does * that for us. * 2. Setting up an listen event from the same script, with the * same filter settings (including step 1), returns the same * handle as the original filter. * 3. (TODO) handles should be script-local. Starting from 1. * Might be actually easier to map the global handle into * script-local handle in the ScriptEngine. Not sure if its * worth the effort tho. * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.WorldComm { public class WorldCommModule : IRegionModule, IWorldComm { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ListenerManager m_listenerManager; private Queue m_pending; private Queue m_pendingQ; private Scene m_scene; private int m_whisperdistance = 10; private int m_saydistance = 30; private int m_shoutdistance = 100; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { // wrap this in a try block so that defaults will work if // the config file doesn't specify otherwise. int maxlisteners = 1000; int maxhandles = 64; try { m_whisperdistance = config.Configs["Chat"].GetInt("whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt("say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt("shout_distance", m_shoutdistance); maxlisteners = config.Configs["LL-Functions"].GetInt("max_listens_per_region", maxlisteners); maxhandles = config.Configs["LL-Functions"].GetInt("max_listens_per_script", maxhandles); } catch (Exception) { } if (maxlisteners < 1) maxlisteners = int.MaxValue; if (maxhandles < 1) maxhandles = int.MaxValue; m_scene = scene; m_scene.RegisterModuleInterface<IWorldComm>(this); m_listenerManager = new ListenerManager(maxlisteners, maxhandles); m_scene.EventManager.OnChatFromClient += DeliverClientMessage; m_scene.EventManager.OnChatBroadcast += DeliverClientMessage; m_pendingQ = new Queue(); m_pending = Queue.Synchronized(m_pendingQ); } public void PostInitialise() { } public void Close() { } public string Name { get { return "WorldCommModule"; } } public bool IsSharedModule { get { return false; } } #endregion #region IWorldComm Members /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id">key to filter on (user given, could be totally faked)</param> /// <param name="msg">msg to filter on</param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg); } /// <summary> /// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE). /// The handle used is returned from Listen() /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> /// <param name="active">temp. activate or deactivate the Listen()</param> public void ListenControl(UUID itemID, int handle, int active) { if (active == 1) m_listenerManager.Activate(itemID, handle); else if (active == 0) m_listenerManager.Dectivate(itemID, handle); } /// <summary> /// Removes the listen event callback with handle /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> public void ListenRemove(UUID itemID, int handle) { m_listenerManager.Remove(itemID, handle); } /// <summary> /// Removes all listen event callbacks for the given itemID /// (script engine) /// </summary> /// <param name="itemID">UUID of the script engine</param> public void DeleteListener(UUID itemID) { m_listenerManager.DeleteListener(itemID); } protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20); public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg) { Vector3 position; SceneObjectPart source; ScenePresence avatar; if ((source = m_scene.GetSceneObjectPart(id)) != null) position = source.AbsolutePosition; else if ((avatar = m_scene.GetScenePresence(id)) != null) position = avatar.AbsolutePosition; else if (ChatTypeEnum.Region == type) position = CenterOfRegion; else return; DeliverMessage(type, channel, name, id, msg, position); } /// <summary> /// This method scans over the objects which registered an interest in listen callbacks. /// For everyone it finds, it checks if it fits the given filter. If it does, then /// enqueue the message for delivery to the objects listen event handler. /// The enqueued ListenerInfo no longer has filter values, but the actually trigged values. /// Objects that do an llSay have their messages delivered here and for nearby avatars, /// the OnChatFromClient event is used. /// </summary> /// <param name="type">type of delvery (whisper,say,shout or regionwide)</param> /// <param name="channel">channel to sent on</param> /// <param name="name">name of sender (object or avatar)</param> /// <param name="id">key of sender (object or avatar)</param> /// <param name="msg">msg to sent</param> public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg, Vector3 position) { // m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}", // type, channel, name, id, msg); // Determine which listen event filters match the given set of arguments, this results // in a limited set of listeners, each belonging a host. If the host is in range, add them // to the pending queue. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { // Dont process if this message is from yourself! if (li.GetHostID().Equals(id)) continue; SceneObjectPart sPart = m_scene.GetSceneObjectPart(li.GetHostID()); if (sPart == null) continue; double dis = Util.GetDistanceTo(sPart.AbsolutePosition, position); switch (type) { case ChatTypeEnum.Whisper: if (dis < m_whisperdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Say: if (dis < m_saydistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Shout: if (dis < m_shoutdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Region: QueueMessage(new ListenerInfo(li, name, id, msg)); break; } } } protected void QueueMessage(ListenerInfo li) { lock (m_pending.SyncRoot) { m_pending.Enqueue(li); } } /// <summary> /// Are there any listen events ready to be dispatched? /// </summary> /// <returns>boolean indication</returns> public bool HasMessages() { return (m_pending.Count > 0); } /// <summary> /// Pop the first availlable listen event from the queue /// </summary> /// <returns>ListenerInfo with filter filled in</returns> public IWorldCommListenerInfo GetNextMessage() { ListenerInfo li = null; lock (m_pending.SyncRoot) { li = (ListenerInfo)m_pending.Dequeue(); } return li; } #endregion /******************************************************************** * * Listener Stuff * * *****************************************************************/ private void DeliverClientMessage(Object sender, OSChatMessage e) { if (null != e.Sender) DeliverMessage(e.Type, e.Channel, e.Sender.Name, e.Sender.AgentId, e.Message, e.Position); else DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero, e.Message, e.Position); } public Object[] GetSerializationData(UUID itemID) { return m_listenerManager.GetSerializationData(itemID); } public void CreateFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { m_listenerManager.AddFromData(localID, itemID, hostID, data); } } public class ListenerManager { private Dictionary<int, List<ListenerInfo>> m_listeners = new Dictionary<int, List<ListenerInfo>>(); private int m_maxlisteners; private int m_maxhandles; private int m_curlisteners; public ListenerManager(int maxlisteners, int maxhandles) { m_maxlisteners = maxlisteners; m_maxhandles = maxhandles; m_curlisteners = 0; } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { // do we already have a match on this particular filter event? List<ListenerInfo> coll = GetListeners(itemID, channel, name, id, msg); if (coll.Count > 0) { // special case, called with same filter settings, return same handle // (2008-05-02, tested on 1.21.1 server, still holds) return coll[0].GetHandle(); } if (m_curlisteners < m_maxlisteners) { lock (m_listeners) { int newHandle = GetNewHandle(itemID); if (newHandle > 0) { ListenerInfo li = new ListenerInfo(newHandle, localID, itemID, hostID, channel, name, id, msg); List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel,out listeners)) { listeners = new List<ListenerInfo>(); m_listeners.Add(channel, listeners); } listeners.Add(li); m_curlisteners++; return newHandle; } } } return -1; } public void Remove(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle().Equals(handle)) { lis.Value.Remove(li); if (lis.Value.Count == 0) { m_listeners.Remove(lis.Key); m_curlisteners--; } // there should be only one, so we bail out early return; } } } } } public void DeleteListener(UUID itemID) { List<int> emptyChannels = new List<int>(); List<ListenerInfo> removedListeners = new List<ListenerInfo>(); lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) { // store them first, else the enumerated bails on us removedListeners.Add(li); } } foreach (ListenerInfo li in removedListeners) { lis.Value.Remove(li); m_curlisteners--; } removedListeners.Clear(); if (lis.Value.Count == 0) { // again, store first, remove later emptyChannels.Add(lis.Key); } } foreach (int channel in emptyChannels) { m_listeners.Remove(channel); } } } public void Activate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Activate(); // only one, bail out return; } } } } } public void Dectivate(UUID itemID, int handle) { lock (m_listeners) { foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Deactivate(); // only one, bail out return; } } } } } // non-locked access, since its always called in the context of the lock private int GetNewHandle(UUID itemID) { List<int> handles = new List<int>(); // build a list of used keys for this specific itemID... foreach (KeyValuePair<int,List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) handles.Add(li.GetHandle()); } } // Note: 0 is NOT a valid handle for llListen() to return for (int i = 1; i <= m_maxhandles; i++) { if (!handles.Contains(i)) return i; } return -1; } // Theres probably a more clever and efficient way to // do this, maybe with regex. // PM2008: Ha, one could even be smart and define a specialized Enumerator. public List<ListenerInfo> GetListeners(UUID itemID, int channel, string name, UUID id, string msg) { List<ListenerInfo> collection = new List<ListenerInfo>(); lock (m_listeners) { List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel,out listeners)) { return collection; } foreach (ListenerInfo li in listeners) { if (!li.IsActive()) { continue; } if (!itemID.Equals(UUID.Zero) && !li.GetItemID().Equals(itemID)) { continue; } if (li.GetName().Length > 0 && !li.GetName().Equals(name)) { continue; } if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id)) { continue; } if (li.GetMessage().Length > 0 && !li.GetMessage().Equals(msg)) { continue; } collection.Add(li); } } return collection; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); lock (m_listeners) { foreach (List<ListenerInfo> list in m_listeners.Values) { foreach (ListenerInfo l in list) { if (l.GetItemID() == itemID) data.AddRange(l.GetSerializationData()); } } } return (Object[])data.ToArray(); } public void AddFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { int idx = 0; Object[] item = new Object[6]; while (idx < data.Length) { Array.Copy(data, idx, item, 0, 6); ListenerInfo info = ListenerInfo.FromData(localID, itemID, hostID, item); lock (m_listeners) { if (!m_listeners.ContainsKey((int)item[2])) m_listeners.Add((int)item[2], new List<ListenerInfo>()); m_listeners[(int)item[2]].Add(info); } idx+=6; } } } public class ListenerInfo: IWorldCommListenerInfo { private bool m_active; // Listener is active or not private int m_handle; // Assigned handle of this listener private uint m_localID; // Local ID from script engine private UUID m_itemID; // ID of the host script engine private UUID m_hostID; // ID of the host/scene part private int m_channel; // Channel private UUID m_id; // ID to filter messages from private string m_name; // Object name to filter messages from private string m_message; // The message public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message); } private void Initialise(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { m_active = true; m_handle = handle; m_localID = localID; m_itemID = ItemID; m_hostID = hostID; m_channel = channel; m_name = name; m_id = id; m_message = message; } public Object[] GetSerializationData() { Object[] data = new Object[6]; data[0] = m_active; data[1] = m_handle; data[2] = m_channel; data[3] = m_name; data[4] = m_id; data[5] = m_message; return data; } public static ListenerInfo FromData(uint localID, UUID ItemID, UUID hostID, Object[] data) { ListenerInfo linfo = new ListenerInfo((int)data[1], localID, ItemID, hostID, (int)data[2], (string)data[3], (UUID)data[4], (string)data[5]); linfo.m_active=(bool)data[0]; return linfo; } public UUID GetItemID() { return m_itemID; } public UUID GetHostID() { return m_hostID; } public int GetChannel() { return m_channel; } public uint GetLocalID() { return m_localID; } public int GetHandle() { return m_handle; } public string GetMessage() { return m_message; } public string GetName() { return m_name; } public bool IsActive() { return m_active; } public void Deactivate() { m_active = false; } public void Activate() { m_active = true; } public UUID GetID() { return m_id; } } }
//----------------------------------------------------------------------- // This file is part of Microsoft Robotics Developer Studio Code Samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // // $File: EarthCoordinates.cs $ $Revision: 1 $ //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.ComponentModel; using Microsoft.Dss.Core.Attributes; namespace Microsoft.Robotics.Services.Sensors.Gps { /// <summary> /// Convert Gps Latitude, Longitude and Altitude to Earth Coordinates in meters /// <remarks> /// Based on an algorithm published by C. Gregg Carlson, South Dakota State University /// "Reading and understanding a Gps receiver" /// http://plantsci.sdstate.edu/precisionfarm/paper/papers/EARTHMOD.pdf /// </remarks> /// </summary> [DataContract] public class EarthCoordinates { #region Private Members private const double _equatorialRadius = 6378137.0000; private const double _polarRadius = 6356752.3142; private double _trueLatitudeAngle; private double _earthLatitudeRadius; private double _polarAxisMeters; private double _equatorialPlaneMeters; private double _latitude; private double _longitude; private double _altitudeMeters; private DateTime _dateTime; private double _horizontalDilutionOfPrecision; private double _verticalDilutionOfPrecision; #endregion /// <summary> /// Latitude /// </summary> [DataMember] [Description("Indicates the latitude.")] public double Latitude { get { return _latitude; } set { _latitude = value; } } /// <summary> /// Longitude /// </summary> [DataMember] [Description("Indicates the longitude.")] public double Longitude { get { return _longitude; } set { _longitude = value; } } /// <summary> /// Altitude in Meters /// </summary> [DataMember] [Description("Indicates the altitude (m).")] public double AltitudeMeters { get { return _altitudeMeters; } set { _altitudeMeters = value; } } /// <summary> /// Latitude and Longitude Dilution Of Precision /// </summary> [DataMember] [Description("Indicates the latitude and longitude dilution of precision.")] public double HorizontalDilutionOfPrecision { get { return _horizontalDilutionOfPrecision; } set { _horizontalDilutionOfPrecision = value; } } /// <summary> /// Altitude Dilution Of Precision /// </summary> [Description("Indicates the altitude dilution of precision.")] [DataMember] public double VerticalDilutionOfPrecision { get { return _verticalDilutionOfPrecision; } set { _verticalDilutionOfPrecision = value; } } /// <summary> /// Time of reading /// </summary> [DataMember] [Description("Indicates the time of the reading.")] public DateTime DateTime { get { return _dateTime; } set { _dateTime = value; } } /// <summary> /// Distance in meters between two Earth Coordinates. /// </summary> /// <param name="start"></param> /// <returns></returns> public double DistanceFromStart(EarthCoordinates start) { // Distance between start and end (Latitude and Altitude) in meters double x = Pythagorean(start._polarAxisMeters - this._polarAxisMeters, start._equatorialPlaneMeters - this._equatorialPlaneMeters); // Distance between start and end Longitude in meters. double y = 2.0 * Math.PI * ((((start._polarAxisMeters + this._polarAxisMeters) / 2.0)) / 360.0) * (start.Longitude - this.Longitude); // Distance between start and end return Pythagorean(x,y); } /// <summary> /// Returns three dimensional cartesian coordinates for this EarthCoordinate /// with vertical orientation to the center of the earth /// and horizontal orientation to the polar coordinates /// <remarks> /// X is meters -East/+West from the start /// Y is meters -South/+North from the start /// Z is meters -Below/+Above the start /// </remarks> /// </summary> /// <param name="start"></param> /// <returns></returns> public Point3 OffsetFromStart(EarthCoordinates start) { // Distance between start and end Longitude in meters. double y = 2.0 * Math.PI * ((((start._polarAxisMeters + this._polarAxisMeters) / 2.0)) / 360.0) * (start.Longitude - this.Longitude); // Difference in altitude double z = (this.AltitudeMeters - start.AltitudeMeters); // To calculate the difference in Latitude, // find the Longitude and Altitude midpoints double midLongitude = (start.Longitude + this.Longitude) / 2.0; double midAltitude = (start.AltitudeMeters + this.AltitudeMeters) / 2.0; EarthCoordinates lat1; if ((Math.Abs(midAltitude) > 20.0) || (Math.Abs(midLongitude) > 0.0001)) { // The points are spread apart, // so plot two new points at the starting and ending Latitude // and using the midpoints of Longitude and Altitude. lat1 = new EarthCoordinates(start.Latitude, midLongitude, midAltitude, start.DateTime, start.HorizontalDilutionOfPrecision, start.VerticalDilutionOfPrecision); } else { // The points are near the same Longitude and Altitude, // so calculate Latitude using the start Longitude and Altitude. lat1 = start; midLongitude = start.Longitude; midAltitude = start.AltitudeMeters; } EarthCoordinates lat2 = new EarthCoordinates(this.Latitude, midLongitude, midAltitude, this.DateTime, this.HorizontalDilutionOfPrecision, this.VerticalDilutionOfPrecision); // Finally, measure the distance between these points. double x = lat2.DistanceFromStart(lat1); return new Point3(x, y, z); } #region Intermediate Calculations /// <summary> /// Calculate the true latitude angle based on ellipsoid model of the earth. /// <remarks>WGS-84 Spheroid model (National Imagery and Mapping Agency, 1997)</remarks> /// </summary> /// <param name="latitude"></param> /// <returns></returns> private static double TrueLatitudeAngle(double latitude) { return (Math.Atan(Math.Pow(_polarRadius, 2.0) / Math.Pow(_equatorialRadius, 2.0) * Math.Tan(latitude * Math.PI / 180.0))) * 180.0 / Math.PI; } /// <summary> /// Calculate the latitudinal radius of the earth /// at the specified angle from the equator /// and taking into consideration the altitude /// measured in meters above sea level. /// </summary> /// <param name="trueAngle"></param> /// <param name="altitudeMeters"></param> /// <returns></returns> private static double EarthLatitudeRadius(double trueAngle, double altitudeMeters) { return Math.Pow((1 / (Math.Pow((Math.Cos(trueAngle * Math.PI / 180.0)), 2.0) / Math.Pow(_equatorialRadius, 2.0) + Math.Pow((Math.Sin(trueAngle * Math.PI / 180.0)), 2.0) / Math.Pow(_polarRadius, 2.0))), 0.5) + altitudeMeters; } /// <summary> /// Calculate the hypotenuse of a right triangle. /// </summary> /// <param name="side1"></param> /// <param name="side2"></param> /// <returns></returns> private static double Pythagorean(double side1, double side2) { return Math.Pow(Math.Pow(side1, 2.0) + Math.Pow(side2, 2.0), 0.5); } #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> public EarthCoordinates() { } /// <summary> /// Initialization Constructor /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <param name="altitudeMeters"></param> public EarthCoordinates(double latitude, double longitude, double altitudeMeters) { Initialize(latitude, longitude, altitudeMeters, DateTime.Now, 0.0, 0.0); } /// <summary> /// Initialization Constructor /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <param name="altitudeMeters"></param> /// <param name="dateTime"></param> /// <param name="horizontalDilutionOfPrecision"></param> /// <param name="verticalDilutionOfPrecision"></param> public EarthCoordinates(double latitude, double longitude, double altitudeMeters, DateTime dateTime, double horizontalDilutionOfPrecision, double verticalDilutionOfPrecision) { Initialize(latitude, longitude, altitudeMeters, dateTime, horizontalDilutionOfPrecision, verticalDilutionOfPrecision); } /// <summary> /// Initialize earth coordinates /// </summary> /// <param name="latitude"></param> /// <param name="longitude"></param> /// <param name="altitudeMeters"></param> /// <param name="dateTime"></param> /// <param name="horizontalDilutionOfPrecision"></param> /// <param name="verticalDilutionOfPrecision"></param> private void Initialize(double latitude, double longitude, double altitudeMeters, DateTime dateTime, double horizontalDilutionOfPrecision, double verticalDilutionOfPrecision) { this._latitude = latitude; this._longitude = longitude; this._altitudeMeters = altitudeMeters; this._dateTime = dateTime; this._horizontalDilutionOfPrecision = horizontalDilutionOfPrecision; this._verticalDilutionOfPrecision = verticalDilutionOfPrecision; this._trueLatitudeAngle = TrueLatitudeAngle(latitude); this._earthLatitudeRadius = EarthLatitudeRadius(_trueLatitudeAngle, altitudeMeters); // Meters from the Polar Axis this._polarAxisMeters = this._earthLatitudeRadius * Math.Cos(_trueLatitudeAngle * Math.PI / 180.0); // Meters from the Equatorial plane this._equatorialPlaneMeters = this._earthLatitudeRadius * Math.Sin(_trueLatitudeAngle * Math.PI / 180.0); } #endregion } }
/* * Copyright 2021 Google LLC All Rights Reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/metric.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/metric.proto</summary> public static partial class MetricReflection { #region Descriptor /// <summary>File descriptor for google/api/metric.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MetricReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chdnb29nbGUvYXBpL21ldHJpYy5wcm90bxIKZ29vZ2xlLmFwaRoWZ29vZ2xl", "L2FwaS9sYWJlbC5wcm90bxodZ29vZ2xlL2FwaS9sYXVuY2hfc3RhZ2UucHJv", "dG8aHmdvb2dsZS9wcm90b2J1Zi9kdXJhdGlvbi5wcm90byKfBgoQTWV0cmlj", "RGVzY3JpcHRvchIMCgRuYW1lGAEgASgJEgwKBHR5cGUYCCABKAkSKwoGbGFi", "ZWxzGAIgAygLMhsuZ29vZ2xlLmFwaS5MYWJlbERlc2NyaXB0b3ISPAoLbWV0", "cmljX2tpbmQYAyABKA4yJy5nb29nbGUuYXBpLk1ldHJpY0Rlc2NyaXB0b3Iu", "TWV0cmljS2luZBI6Cgp2YWx1ZV90eXBlGAQgASgOMiYuZ29vZ2xlLmFwaS5N", "ZXRyaWNEZXNjcmlwdG9yLlZhbHVlVHlwZRIMCgR1bml0GAUgASgJEhMKC2Rl", "c2NyaXB0aW9uGAYgASgJEhQKDGRpc3BsYXlfbmFtZRgHIAEoCRJHCghtZXRh", "ZGF0YRgKIAEoCzI1Lmdvb2dsZS5hcGkuTWV0cmljRGVzY3JpcHRvci5NZXRy", "aWNEZXNjcmlwdG9yTWV0YWRhdGESLQoMbGF1bmNoX3N0YWdlGAwgASgOMhcu", "Z29vZ2xlLmFwaS5MYXVuY2hTdGFnZRIgChhtb25pdG9yZWRfcmVzb3VyY2Vf", "dHlwZXMYDSADKAkasAEKGE1ldHJpY0Rlc2NyaXB0b3JNZXRhZGF0YRIxCgxs", "YXVuY2hfc3RhZ2UYASABKA4yFy5nb29nbGUuYXBpLkxhdW5jaFN0YWdlQgIY", "ARIwCg1zYW1wbGVfcGVyaW9kGAIgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1", "cmF0aW9uEi8KDGluZ2VzdF9kZWxheRgDIAEoCzIZLmdvb2dsZS5wcm90b2J1", "Zi5EdXJhdGlvbiJPCgpNZXRyaWNLaW5kEhsKF01FVFJJQ19LSU5EX1VOU1BF", "Q0lGSUVEEAASCQoFR0FVR0UQARIJCgVERUxUQRACEg4KCkNVTVVMQVRJVkUQ", "AyJxCglWYWx1ZVR5cGUSGgoWVkFMVUVfVFlQRV9VTlNQRUNJRklFRBAAEggK", "BEJPT0wQARIJCgVJTlQ2NBACEgoKBkRPVUJMRRADEgoKBlNUUklORxAEEhAK", "DERJU1RSSUJVVElPThAFEgkKBU1PTkVZEAYidQoGTWV0cmljEgwKBHR5cGUY", "AyABKAkSLgoGbGFiZWxzGAIgAygLMh4uZ29vZ2xlLmFwaS5NZXRyaWMuTGFi", "ZWxzRW50cnkaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVl", "GAIgASgJOgI4AUJfCg5jb20uZ29vZ2xlLmFwaUILTWV0cmljUHJvdG9QAVo3", "Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvbWV0", "cmljO21ldHJpY6ICBEdBUEliBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.LabelReflection.Descriptor, global::Google.Api.LaunchStageReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MetricDescriptor), global::Google.Api.MetricDescriptor.Parser, new[]{ "Name", "Type", "Labels", "MetricKind", "ValueType", "Unit", "Description", "DisplayName", "Metadata", "LaunchStage", "MonitoredResourceTypes" }, null, new[]{ typeof(global::Google.Api.MetricDescriptor.Types.MetricKind), typeof(global::Google.Api.MetricDescriptor.Types.ValueType) }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata), global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata.Parser, new[]{ "LaunchStage", "SamplePeriod", "IngestDelay" }, null, null, null, null)}), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Metric), global::Google.Api.Metric.Parser, new[]{ "Type", "Labels" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) })); } #endregion } #region Messages /// <summary> /// Defines a metric type and its schema. Once a metric descriptor is created, /// deleting or altering it stops data collection and makes the metric type's /// existing data unusable. /// </summary> public sealed partial class MetricDescriptor : pb::IMessage<MetricDescriptor> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MetricDescriptor> _parser = new pb::MessageParser<MetricDescriptor>(() => new MetricDescriptor()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MetricDescriptor> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MetricReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptor() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptor(MetricDescriptor other) : this() { name_ = other.name_; type_ = other.type_; labels_ = other.labels_.Clone(); metricKind_ = other.metricKind_; valueType_ = other.valueType_; unit_ = other.unit_; description_ = other.description_; displayName_ = other.displayName_; metadata_ = other.metadata_ != null ? other.metadata_.Clone() : null; launchStage_ = other.launchStage_; monitoredResourceTypes_ = other.monitoredResourceTypes_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptor Clone() { return new MetricDescriptor(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The resource name of the metric descriptor. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 8; private string type_ = ""; /// <summary> /// The metric type, including its DNS name prefix. The type is not /// URL-encoded. All user-defined metric types have the DNS name /// `custom.googleapis.com` or `external.googleapis.com`. Metric types should /// use a natural hierarchical grouping. For example: /// /// "custom.googleapis.com/invoice/paid/amount" /// "external.googleapis.com/prometheus/up" /// "appengine.googleapis.com/http/server/response_latencies" /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "labels" field.</summary> public const int LabelsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.LabelDescriptor> _repeated_labels_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.LabelDescriptor.Parser); private readonly pbc::RepeatedField<global::Google.Api.LabelDescriptor> labels_ = new pbc::RepeatedField<global::Google.Api.LabelDescriptor>(); /// <summary> /// The set of labels that can be used to describe a specific /// instance of this metric type. For example, the /// `appengine.googleapis.com/http/server/response_latencies` metric /// type has a label for the HTTP response code, `response_code`, so /// you can look at latencies for successful responses or just /// for responses that failed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.LabelDescriptor> Labels { get { return labels_; } } /// <summary>Field number for the "metric_kind" field.</summary> public const int MetricKindFieldNumber = 3; private global::Google.Api.MetricDescriptor.Types.MetricKind metricKind_ = global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified; /// <summary> /// Whether the metric records instantaneous values, changes to a value, etc. /// Some combinations of `metric_kind` and `value_type` might not be supported. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.MetricDescriptor.Types.MetricKind MetricKind { get { return metricKind_; } set { metricKind_ = value; } } /// <summary>Field number for the "value_type" field.</summary> public const int ValueTypeFieldNumber = 4; private global::Google.Api.MetricDescriptor.Types.ValueType valueType_ = global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified; /// <summary> /// Whether the measurement is an integer, a floating-point number, etc. /// Some combinations of `metric_kind` and `value_type` might not be supported. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.MetricDescriptor.Types.ValueType ValueType { get { return valueType_; } set { valueType_ = value; } } /// <summary>Field number for the "unit" field.</summary> public const int UnitFieldNumber = 5; private string unit_ = ""; /// <summary> /// The units in which the metric value is reported. It is only applicable /// if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The `unit` /// defines the representation of the stored metric values. /// /// Different systems might scale the values to be more easily displayed (so a /// value of `0.02kBy` _might_ be displayed as `20By`, and a value of /// `3523kBy` _might_ be displayed as `3.5MBy`). However, if the `unit` is /// `kBy`, then the value of the metric is always in thousands of bytes, no /// matter how it might be displayed. /// /// If you want a custom metric to record the exact number of CPU-seconds used /// by a job, you can create an `INT64 CUMULATIVE` metric whose `unit` is /// `s{CPU}` (or equivalently `1s{CPU}` or just `s`). If the job uses 12,005 /// CPU-seconds, then the value is written as `12005`. /// /// Alternatively, if you want a custom metric to record data in a more /// granular way, you can create a `DOUBLE CUMULATIVE` metric whose `unit` is /// `ks{CPU}`, and then write the value `12.005` (which is `12005/1000`), /// or use `Kis{CPU}` and write `11.723` (which is `12005/1024`). /// /// The supported units are a subset of [The Unified Code for Units of /// Measure](https://unitsofmeasure.org/ucum.html) standard: /// /// **Basic units (UNIT)** /// /// * `bit` bit /// * `By` byte /// * `s` second /// * `min` minute /// * `h` hour /// * `d` day /// * `1` dimensionless /// /// **Prefixes (PREFIX)** /// /// * `k` kilo (10^3) /// * `M` mega (10^6) /// * `G` giga (10^9) /// * `T` tera (10^12) /// * `P` peta (10^15) /// * `E` exa (10^18) /// * `Z` zetta (10^21) /// * `Y` yotta (10^24) /// /// * `m` milli (10^-3) /// * `u` micro (10^-6) /// * `n` nano (10^-9) /// * `p` pico (10^-12) /// * `f` femto (10^-15) /// * `a` atto (10^-18) /// * `z` zepto (10^-21) /// * `y` yocto (10^-24) /// /// * `Ki` kibi (2^10) /// * `Mi` mebi (2^20) /// * `Gi` gibi (2^30) /// * `Ti` tebi (2^40) /// * `Pi` pebi (2^50) /// /// **Grammar** /// /// The grammar also includes these connectors: /// /// * `/` division or ratio (as an infix operator). For examples, /// `kBy/{email}` or `MiBy/10ms` (although you should almost never /// have `/s` in a metric `unit`; rates should always be computed at /// query time from the underlying cumulative or delta value). /// * `.` multiplication or composition (as an infix operator). For /// examples, `GBy.d` or `k{watt}.h`. /// /// The grammar for a unit is as follows: /// /// Expression = Component { "." Component } { "/" Component } ; /// /// Component = ( [ PREFIX ] UNIT | "%" ) [ Annotation ] /// | Annotation /// | "1" /// ; /// /// Annotation = "{" NAME "}" ; /// /// Notes: /// /// * `Annotation` is just a comment if it follows a `UNIT`. If the annotation /// is used alone, then the unit is equivalent to `1`. For examples, /// `{request}/s == 1/s`, `By{transmitted}/s == By/s`. /// * `NAME` is a sequence of non-blank printable ASCII characters not /// containing `{` or `}`. /// * `1` represents a unitary [dimensionless /// unit](https://en.wikipedia.org/wiki/Dimensionless_quantity) of 1, such /// as in `1/s`. It is typically used when none of the basic units are /// appropriate. For example, "new users per day" can be represented as /// `1/d` or `{new-users}/d` (and a metric value `5` would mean "5 new /// users). Alternatively, "thousands of page views per day" would be /// represented as `1000/d` or `k1/d` or `k{page_views}/d` (and a metric /// value of `5.3` would mean "5300 page views per day"). /// * `%` represents dimensionless value of 1/100, and annotates values giving /// a percentage (so the metric values are typically in the range of 0..100, /// and a metric value `3` means "3 percent"). /// * `10^2.%` indicates a metric contains a ratio, typically in the range /// 0..1, that will be multiplied by 100 and displayed as a percentage /// (so a metric value `0.03` means "3 percent"). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Unit { get { return unit_; } set { unit_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 6; private string description_ = ""; /// <summary> /// A detailed description of the metric, which can be used in documentation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "display_name" field.</summary> public const int DisplayNameFieldNumber = 7; private string displayName_ = ""; /// <summary> /// A concise name for the metric, which can be displayed in user interfaces. /// Use sentence case without an ending period, for example "Request count". /// This field is optional but it is recommended to be set for any metrics /// associated with user-visible concepts, such as Quota. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DisplayName { get { return displayName_; } set { displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "metadata" field.</summary> public const int MetadataFieldNumber = 10; private global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata metadata_; /// <summary> /// Optional. Metadata which can be used to guide usage of the metric. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata Metadata { get { return metadata_; } set { metadata_ = value; } } /// <summary>Field number for the "launch_stage" field.</summary> public const int LaunchStageFieldNumber = 12; private global::Google.Api.LaunchStage launchStage_ = global::Google.Api.LaunchStage.Unspecified; /// <summary> /// Optional. The launch stage of the metric definition. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.LaunchStage LaunchStage { get { return launchStage_; } set { launchStage_ = value; } } /// <summary>Field number for the "monitored_resource_types" field.</summary> public const int MonitoredResourceTypesFieldNumber = 13; private static readonly pb::FieldCodec<string> _repeated_monitoredResourceTypes_codec = pb::FieldCodec.ForString(106); private readonly pbc::RepeatedField<string> monitoredResourceTypes_ = new pbc::RepeatedField<string>(); /// <summary> /// Read-only. If present, then a [time /// series][google.monitoring.v3.TimeSeries], which is identified partially by /// a metric type and a [MonitoredResourceDescriptor][google.api.MonitoredResourceDescriptor], that is associated /// with this metric type can only be associated with one of the monitored /// resource types listed here. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> MonitoredResourceTypes { get { return monitoredResourceTypes_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MetricDescriptor); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MetricDescriptor other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Type != other.Type) return false; if(!labels_.Equals(other.labels_)) return false; if (MetricKind != other.MetricKind) return false; if (ValueType != other.ValueType) return false; if (Unit != other.Unit) return false; if (Description != other.Description) return false; if (DisplayName != other.DisplayName) return false; if (!object.Equals(Metadata, other.Metadata)) return false; if (LaunchStage != other.LaunchStage) return false; if(!monitoredResourceTypes_.Equals(other.monitoredResourceTypes_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Type.Length != 0) hash ^= Type.GetHashCode(); hash ^= labels_.GetHashCode(); if (MetricKind != global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified) hash ^= MetricKind.GetHashCode(); if (ValueType != global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified) hash ^= ValueType.GetHashCode(); if (Unit.Length != 0) hash ^= Unit.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode(); if (metadata_ != null) hash ^= Metadata.GetHashCode(); if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) hash ^= LaunchStage.GetHashCode(); hash ^= monitoredResourceTypes_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } labels_.WriteTo(output, _repeated_labels_codec); if (MetricKind != global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) MetricKind); } if (ValueType != global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) ValueType); } if (Unit.Length != 0) { output.WriteRawTag(42); output.WriteString(Unit); } if (Description.Length != 0) { output.WriteRawTag(50); output.WriteString(Description); } if (DisplayName.Length != 0) { output.WriteRawTag(58); output.WriteString(DisplayName); } if (Type.Length != 0) { output.WriteRawTag(66); output.WriteString(Type); } if (metadata_ != null) { output.WriteRawTag(82); output.WriteMessage(Metadata); } if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(96); output.WriteEnum((int) LaunchStage); } monitoredResourceTypes_.WriteTo(output, _repeated_monitoredResourceTypes_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } labels_.WriteTo(ref output, _repeated_labels_codec); if (MetricKind != global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified) { output.WriteRawTag(24); output.WriteEnum((int) MetricKind); } if (ValueType != global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified) { output.WriteRawTag(32); output.WriteEnum((int) ValueType); } if (Unit.Length != 0) { output.WriteRawTag(42); output.WriteString(Unit); } if (Description.Length != 0) { output.WriteRawTag(50); output.WriteString(Description); } if (DisplayName.Length != 0) { output.WriteRawTag(58); output.WriteString(DisplayName); } if (Type.Length != 0) { output.WriteRawTag(66); output.WriteString(Type); } if (metadata_ != null) { output.WriteRawTag(82); output.WriteMessage(Metadata); } if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(96); output.WriteEnum((int) LaunchStage); } monitoredResourceTypes_.WriteTo(ref output, _repeated_monitoredResourceTypes_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } size += labels_.CalculateSize(_repeated_labels_codec); if (MetricKind != global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) MetricKind); } if (ValueType != global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ValueType); } if (Unit.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Unit); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (DisplayName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName); } if (metadata_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata); } if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) LaunchStage); } size += monitoredResourceTypes_.CalculateSize(_repeated_monitoredResourceTypes_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MetricDescriptor other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Type.Length != 0) { Type = other.Type; } labels_.Add(other.labels_); if (other.MetricKind != global::Google.Api.MetricDescriptor.Types.MetricKind.Unspecified) { MetricKind = other.MetricKind; } if (other.ValueType != global::Google.Api.MetricDescriptor.Types.ValueType.Unspecified) { ValueType = other.ValueType; } if (other.Unit.Length != 0) { Unit = other.Unit; } if (other.Description.Length != 0) { Description = other.Description; } if (other.DisplayName.Length != 0) { DisplayName = other.DisplayName; } if (other.metadata_ != null) { if (metadata_ == null) { Metadata = new global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata(); } Metadata.MergeFrom(other.Metadata); } if (other.LaunchStage != global::Google.Api.LaunchStage.Unspecified) { LaunchStage = other.LaunchStage; } monitoredResourceTypes_.Add(other.monitoredResourceTypes_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 18: { labels_.AddEntriesFrom(input, _repeated_labels_codec); break; } case 24: { MetricKind = (global::Google.Api.MetricDescriptor.Types.MetricKind) input.ReadEnum(); break; } case 32: { ValueType = (global::Google.Api.MetricDescriptor.Types.ValueType) input.ReadEnum(); break; } case 42: { Unit = input.ReadString(); break; } case 50: { Description = input.ReadString(); break; } case 58: { DisplayName = input.ReadString(); break; } case 66: { Type = input.ReadString(); break; } case 82: { if (metadata_ == null) { Metadata = new global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata(); } input.ReadMessage(Metadata); break; } case 96: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } case 106: { monitoredResourceTypes_.AddEntriesFrom(input, _repeated_monitoredResourceTypes_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 18: { labels_.AddEntriesFrom(ref input, _repeated_labels_codec); break; } case 24: { MetricKind = (global::Google.Api.MetricDescriptor.Types.MetricKind) input.ReadEnum(); break; } case 32: { ValueType = (global::Google.Api.MetricDescriptor.Types.ValueType) input.ReadEnum(); break; } case 42: { Unit = input.ReadString(); break; } case 50: { Description = input.ReadString(); break; } case 58: { DisplayName = input.ReadString(); break; } case 66: { Type = input.ReadString(); break; } case 82: { if (metadata_ == null) { Metadata = new global::Google.Api.MetricDescriptor.Types.MetricDescriptorMetadata(); } input.ReadMessage(Metadata); break; } case 96: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } case 106: { monitoredResourceTypes_.AddEntriesFrom(ref input, _repeated_monitoredResourceTypes_codec); break; } } } } #endif #region Nested types /// <summary>Container for nested types declared in the MetricDescriptor message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// The kind of measurement. It describes how the data is reported. /// For information on setting the start time and end time based on /// the MetricKind, see [TimeInterval][google.monitoring.v3.TimeInterval]. /// </summary> public enum MetricKind { /// <summary> /// Do not use this default value. /// </summary> [pbr::OriginalName("METRIC_KIND_UNSPECIFIED")] Unspecified = 0, /// <summary> /// An instantaneous measurement of a value. /// </summary> [pbr::OriginalName("GAUGE")] Gauge = 1, /// <summary> /// The change in a value during a time interval. /// </summary> [pbr::OriginalName("DELTA")] Delta = 2, /// <summary> /// A value accumulated over a time interval. Cumulative /// measurements in a time series should have the same start time /// and increasing end times, until an event resets the cumulative /// value to zero and sets a new start time for the following /// points. /// </summary> [pbr::OriginalName("CUMULATIVE")] Cumulative = 3, } /// <summary> /// The value type of a metric. /// </summary> public enum ValueType { /// <summary> /// Do not use this default value. /// </summary> [pbr::OriginalName("VALUE_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The value is a boolean. /// This value type can be used only if the metric kind is `GAUGE`. /// </summary> [pbr::OriginalName("BOOL")] Bool = 1, /// <summary> /// The value is a signed 64-bit integer. /// </summary> [pbr::OriginalName("INT64")] Int64 = 2, /// <summary> /// The value is a double precision floating point number. /// </summary> [pbr::OriginalName("DOUBLE")] Double = 3, /// <summary> /// The value is a text string. /// This value type can be used only if the metric kind is `GAUGE`. /// </summary> [pbr::OriginalName("STRING")] String = 4, /// <summary> /// The value is a [`Distribution`][google.api.Distribution]. /// </summary> [pbr::OriginalName("DISTRIBUTION")] Distribution = 5, /// <summary> /// The value is money. /// </summary> [pbr::OriginalName("MONEY")] Money = 6, } /// <summary> /// Additional annotations that can be used to guide the usage of a metric. /// </summary> public sealed partial class MetricDescriptorMetadata : pb::IMessage<MetricDescriptorMetadata> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<MetricDescriptorMetadata> _parser = new pb::MessageParser<MetricDescriptorMetadata>(() => new MetricDescriptorMetadata()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MetricDescriptorMetadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MetricDescriptor.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptorMetadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptorMetadata(MetricDescriptorMetadata other) : this() { launchStage_ = other.launchStage_; samplePeriod_ = other.samplePeriod_ != null ? other.samplePeriod_.Clone() : null; ingestDelay_ = other.ingestDelay_ != null ? other.ingestDelay_.Clone() : null; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MetricDescriptorMetadata Clone() { return new MetricDescriptorMetadata(this); } /// <summary>Field number for the "launch_stage" field.</summary> public const int LaunchStageFieldNumber = 1; private global::Google.Api.LaunchStage launchStage_ = global::Google.Api.LaunchStage.Unspecified; /// <summary> /// Deprecated. Must use the [MetricDescriptor.launch_stage][google.api.MetricDescriptor.launch_stage] instead. /// </summary> [global::System.ObsoleteAttribute] [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.LaunchStage LaunchStage { get { return launchStage_; } set { launchStage_ = value; } } /// <summary>Field number for the "sample_period" field.</summary> public const int SamplePeriodFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration samplePeriod_; /// <summary> /// The sampling period of metric data points. For metrics which are written /// periodically, consecutive data points are stored at this time interval, /// excluding data loss due to errors. Metrics with a higher granularity have /// a smaller sampling period. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration SamplePeriod { get { return samplePeriod_; } set { samplePeriod_ = value; } } /// <summary>Field number for the "ingest_delay" field.</summary> public const int IngestDelayFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Duration ingestDelay_; /// <summary> /// The delay of data points caused by ingestion. Data points older than this /// age are guaranteed to be ingested and available to be read, excluding /// data loss due to errors. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration IngestDelay { get { return ingestDelay_; } set { ingestDelay_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MetricDescriptorMetadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MetricDescriptorMetadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (LaunchStage != other.LaunchStage) return false; if (!object.Equals(SamplePeriod, other.SamplePeriod)) return false; if (!object.Equals(IngestDelay, other.IngestDelay)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) hash ^= LaunchStage.GetHashCode(); if (samplePeriod_ != null) hash ^= SamplePeriod.GetHashCode(); if (ingestDelay_ != null) hash ^= IngestDelay.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) LaunchStage); } if (samplePeriod_ != null) { output.WriteRawTag(18); output.WriteMessage(SamplePeriod); } if (ingestDelay_ != null) { output.WriteRawTag(26); output.WriteMessage(IngestDelay); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { output.WriteRawTag(8); output.WriteEnum((int) LaunchStage); } if (samplePeriod_ != null) { output.WriteRawTag(18); output.WriteMessage(SamplePeriod); } if (ingestDelay_ != null) { output.WriteRawTag(26); output.WriteMessage(IngestDelay); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (LaunchStage != global::Google.Api.LaunchStage.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) LaunchStage); } if (samplePeriod_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SamplePeriod); } if (ingestDelay_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(IngestDelay); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MetricDescriptorMetadata other) { if (other == null) { return; } if (other.LaunchStage != global::Google.Api.LaunchStage.Unspecified) { LaunchStage = other.LaunchStage; } if (other.samplePeriod_ != null) { if (samplePeriod_ == null) { SamplePeriod = new global::Google.Protobuf.WellKnownTypes.Duration(); } SamplePeriod.MergeFrom(other.SamplePeriod); } if (other.ingestDelay_ != null) { if (ingestDelay_ == null) { IngestDelay = new global::Google.Protobuf.WellKnownTypes.Duration(); } IngestDelay.MergeFrom(other.IngestDelay); } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } case 18: { if (samplePeriod_ == null) { SamplePeriod = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(SamplePeriod); break; } case 26: { if (ingestDelay_ == null) { IngestDelay = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(IngestDelay); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { LaunchStage = (global::Google.Api.LaunchStage) input.ReadEnum(); break; } case 18: { if (samplePeriod_ == null) { SamplePeriod = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(SamplePeriod); break; } case 26: { if (ingestDelay_ == null) { IngestDelay = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(IngestDelay); break; } } } } #endif } } #endregion } /// <summary> /// A specific metric, identified by specifying values for all of the /// labels of a [`MetricDescriptor`][google.api.MetricDescriptor]. /// </summary> public sealed partial class Metric : pb::IMessage<Metric> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Metric> _parser = new pb::MessageParser<Metric>(() => new Metric()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Metric> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.MetricReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Metric() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Metric(Metric other) : this() { type_ = other.type_; labels_ = other.labels_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Metric Clone() { return new Metric(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 3; private string type_ = ""; /// <summary> /// An existing metric type, see [google.api.MetricDescriptor][google.api.MetricDescriptor]. /// For example, `custom.googleapis.com/invoice/paid/amount`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "labels" field.</summary> public const int LabelsFieldNumber = 2; private static readonly pbc::MapField<string, string>.Codec _map_labels_codec = new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 18); private readonly pbc::MapField<string, string> labels_ = new pbc::MapField<string, string>(); /// <summary> /// The set of label values that uniquely identify this metric. All /// labels listed in the `MetricDescriptor` must be assigned values. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, string> Labels { get { return labels_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Metric); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Metric other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if (!Labels.Equals(other.Labels)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Type.Length != 0) hash ^= Type.GetHashCode(); hash ^= Labels.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else labels_.WriteTo(output, _map_labels_codec); if (Type.Length != 0) { output.WriteRawTag(26); output.WriteString(Type); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { labels_.WriteTo(ref output, _map_labels_codec); if (Type.Length != 0) { output.WriteRawTag(26); output.WriteString(Type); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } size += labels_.CalculateSize(_map_labels_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Metric other) { if (other == null) { return; } if (other.Type.Length != 0) { Type = other.Type; } labels_.Add(other.labels_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 18: { labels_.AddEntriesFrom(input, _map_labels_codec); break; } case 26: { Type = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 18: { labels_.AddEntriesFrom(ref input, _map_labels_codec); break; } case 26: { Type = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
//--------------------------------------------------------------------- // <copyright file="DuplicatePropertyNamesChecker.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.OData.Core.JsonLight; #endregion Namespaces /// <summary> /// Helper class to verify that no duplicate properties are specified for entries and complex values. /// </summary> internal sealed class DuplicatePropertyNamesChecker { /// <summary>Special value for the property annotations which is used to mark the annotations as processed.</summary> private static readonly Dictionary<string, object> propertyAnnotationsProcessedToken = new Dictionary<string, object>(0, StringComparer.Ordinal); /// <summary>true if duplicate properties are allowed; otherwise false.</summary> /// <remarks> /// See the comment on ODataWriterBehavior.AllowDuplicatePropertyNames or /// ODataReaderBehavior.AllowDuplicatePropertyNames for further details. /// </remarks> private readonly bool allowDuplicateProperties; /// <summary>true if we're processing a response; false if it's a request.</summary> private readonly bool isResponse; /// <summary>Disable the check process if it is true.</summary> private readonly bool disabled; #if DEBUG /// <summary>Name of the navigation link for which we were asked to check duplication on its start.</summary> /// <remarks>If this is set, the next call must be a real check for the same navigation link.</remarks> private string startNavigationLinkName; #endif /// <summary> /// A cache of property names to detect duplicate property names. The <see cref="DuplicationKind"/> value stored /// for a given property name indicates what should happen if another property with the same name is found. /// See the comments on <see cref="DuplicationKind"/> for more details. /// </summary> private Dictionary<string, DuplicationRecord> propertyNameCache; /// <summary> /// Constructor. /// </summary> /// <param name="allowDuplicateProperties">true if duplicate properties are allowed; otherwise false.</param> /// <param name="isResponse">true if we're processing a response; false if it's a request.</param> /// <param name="disabled">Disable the check process if it is true.</param> public DuplicatePropertyNamesChecker(bool allowDuplicateProperties, bool isResponse, bool disabled = false) { this.allowDuplicateProperties = allowDuplicateProperties; this.isResponse = isResponse; this.disabled = disabled; } /// <summary> /// An enumeration to represent the duplication kind of a given property name. /// </summary> /// <remarks> /// This enumeration is used to determine what should happen if two properties with the same name are detected on an entry or complex value. /// When the first property is found, the initial value is set based on the kind of property found and the general setting to allow or disallow duplicate properties. /// When a second property with the same name is found, the duplication kind can be 'upgraded' (e.g., from association link to navigation property), 'ignored' (e.g. /// when finding the association link for an existing navigation property or when duplicate properties are allowed by the settings) or 'fail' /// (e.g., when duplicate properties are not allowed). /// </remarks> private enum DuplicationKind { /// <summary>We don't know enough about the property to determine its duplication kind yet, we've just seen a property annotation for it.</summary> PropertyAnnotationSeen, /// <summary>Duplicates for this property name are not allowed.</summary> Prohibited, /// <summary>This kind indicates that duplicates are allowed (if the settings allow duplicates).</summary> PotentiallyAllowed, /// <summary>A navigation link or association link was reported.</summary> NavigationProperty, } /// <summary> /// Check the <paramref name="property"/> for duplicate property names in an entry or complex value. /// If not explicitly allowed throw when duplicate properties are detected. /// If duplicate properties are allowed see the comment on ODataWriterBehavior.AllowDuplicatePropertyNames /// or ODataReaderBehavior.AllowDuplicatePropertyNames for further details. /// </summary> /// <param name="property">The property to be checked.</param> internal void CheckForDuplicatePropertyNames(ODataProperty property) { if (this.disabled) { return; } Debug.Assert(property != null, "property != null"); #if DEBUG Debug.Assert(this.startNavigationLinkName == null, "CheckForDuplicatePropertyNamesOnNavigationLinkStart was followed by a CheckForDuplicatePropertyNames(ODataProperty)."); #endif string propertyName = property.Name; DuplicationKind duplicationKind = GetDuplicationKind(property); DuplicationRecord existingDuplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out existingDuplicationRecord)) { this.propertyNameCache.Add(propertyName, new DuplicationRecord(duplicationKind)); } else if (existingDuplicationRecord.DuplicationKind == DuplicationKind.PropertyAnnotationSeen) { existingDuplicationRecord.DuplicationKind = duplicationKind; } else { // If either of them prohibits duplication, fail // If the existing one is an association link, fail (association links don't allow duplicates with simple properties) // If we don't allow duplication in the first place, fail, since there is no valid case where a simple property coexists with anything else with the same name. if (existingDuplicationRecord.DuplicationKind == DuplicationKind.Prohibited || duplicationKind == DuplicationKind.Prohibited || (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.AssociationLinkName != null) || !this.allowDuplicateProperties) { throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(propertyName)); } else { // Otherwise allow the duplicate. // Note that we don't modify the existing duplication record in any way if the new property is a simple property. // This is because if the existing one is a simple property which allows duplication as well, there's nothing to change. // and if the existing one is a navigation property the navigation property information is more important than the simple property one. } } } /// <summary> /// Checks the <paramref name="navigationLink"/> for duplicate property names in an entry when the navigation link /// has started but we don't know yet if it's expanded or not. /// </summary> /// <param name="navigationLink">The navigation link to be checked.</param> internal void CheckForDuplicatePropertyNamesOnNavigationLinkStart(ODataNavigationLink navigationLink) { if (this.disabled) { return; } Debug.Assert(navigationLink != null, "navigationLink != null"); #if DEBUG this.startNavigationLinkName = navigationLink.Name; #endif // Just check for duplication without modifying anything in the caches - this is to allow callers to choose whether they want to call this method first // or just call the CheckForDuplicatePropertyNames(ODataNavigationLink) directly. string propertyName = navigationLink.Name; DuplicationRecord existingDuplicationRecord; if (this.propertyNameCache != null && this.propertyNameCache.TryGetValue(propertyName, out existingDuplicationRecord)) { this.CheckNavigationLinkDuplicateNameForExistingDuplicationRecord(propertyName, existingDuplicationRecord); } } /// <summary> /// Check the <paramref name="navigationLink"/> for duplicate property names in an entry or complex value. /// If not explicitly allowed throw when duplicate properties are detected. /// If duplicate properties are allowed see the comment on ODataWriterBehavior.AllowDuplicatePropertyNames /// or ODataReaderBehavior.AllowDuplicatePropertyNames for further details. /// </summary> /// <param name="navigationLink">The navigation link to be checked.</param> /// <param name="isExpanded">true if the link is expanded, false otherwise.</param> /// <param name="isCollection">true if the navigation link is a collection, false if it's a singleton or null if we don't know.</param> /// <returns>The association link uri with the same name if there already was one.</returns> internal Uri CheckForDuplicatePropertyNames(ODataNavigationLink navigationLink, bool isExpanded, bool? isCollection) { if (this.disabled) { return null; } #if DEBUG this.startNavigationLinkName = null; #endif string propertyName = navigationLink.Name; DuplicationRecord existingDuplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out existingDuplicationRecord)) { DuplicationRecord duplicationRecord = new DuplicationRecord(DuplicationKind.NavigationProperty); ApplyNavigationLinkToDuplicationRecord(duplicationRecord, navigationLink, isExpanded, isCollection); this.propertyNameCache.Add(propertyName, duplicationRecord); return null; } else { // First check for duplication without expansion knowledge. this.CheckNavigationLinkDuplicateNameForExistingDuplicationRecord(propertyName, existingDuplicationRecord); if (existingDuplicationRecord.DuplicationKind == DuplicationKind.PropertyAnnotationSeen || (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.AssociationLinkName != null && existingDuplicationRecord.NavigationLink == null)) { // If the existing one is just an association link, update it to include the navigation link portion as well ApplyNavigationLinkToDuplicationRecord(existingDuplicationRecord, navigationLink, isExpanded, isCollection); } else if (this.allowDuplicateProperties) { Debug.Assert( (existingDuplicationRecord.DuplicationKind == DuplicationKind.PotentiallyAllowed || existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty), "We should have already taken care of prohibit duplication."); // If the configuration explicitly allows duplication, then just turn the existing property into a nav link with all the information we have existingDuplicationRecord.DuplicationKind = DuplicationKind.NavigationProperty; ApplyNavigationLinkToDuplicationRecord(existingDuplicationRecord, navigationLink, isExpanded, isCollection); } else { // We've found two navigation links in a request Debug.Assert( existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.NavigationLink != null && !this.isResponse, "We can only get here if we've found two navigation links in a request."); bool? isCollectionEffectiveValue = GetIsCollectionEffectiveValue(isExpanded, isCollection); // If one of them is a definitive singleton, then we fail. if (isCollectionEffectiveValue == false || existingDuplicationRecord.NavigationPropertyIsCollection == false) { // This is the case where an expanded singleton is followed by a deferred link for example. // Once we know for sure that the nav. prop. is a singleton we can't allow more than one link for it. throw new ODataException(Strings.DuplicatePropertyNamesChecker_MultipleLinksForSingleton(propertyName)); } // Otherwise allow it, but update the link with the new information if (isCollectionEffectiveValue.HasValue) { existingDuplicationRecord.NavigationPropertyIsCollection = isCollectionEffectiveValue; } } return existingDuplicationRecord.AssociationLinkUrl; } } /// <summary> /// Check the <paramref name="associationLinkName"/> for duplicate property names in an entry or complex value. /// If not explicitly allowed throw when duplicate properties are detected. /// If duplicate properties are allowed see the comment on ODataWriterBehavior.AllowDuplicatePropertyNames /// or ODataReaderBehavior.AllowDuplicatePropertyNames for further details. /// </summary> /// <param name="associationLinkName">The name of association link to be checked.</param> /// <param name="associationLinkUrl">The url of association link to be checked.</param> /// <returns>The navigation link with the same name as the association link if there's one.</returns> internal ODataNavigationLink CheckForDuplicateAssociationLinkNames(string associationLinkName, Uri associationLinkUrl) { if (this.disabled) { return null; } Debug.Assert(associationLinkName != null, "associationLinkName != null"); #if DEBUG Debug.Assert(this.startNavigationLinkName == null, "CheckForDuplicatePropertyNamesOnNavigationLinkStart was followed by a CheckForDuplicatePropertyNames(ODataProperty)."); #endif DuplicationRecord existingDuplicationRecord; if (!this.TryGetDuplicationRecord(associationLinkName, out existingDuplicationRecord)) { this.propertyNameCache.Add( associationLinkName, new DuplicationRecord(DuplicationKind.NavigationProperty) { AssociationLinkName = associationLinkName, AssociationLinkUrl = associationLinkUrl }); return null; } else { if (existingDuplicationRecord.DuplicationKind == DuplicationKind.PropertyAnnotationSeen || (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.AssociationLinkName == null)) { // The only valid case for a duplication with association link is if the existing record is for a navigation property // which doesn't have its association link yet. // In this case just mark the navigation property as having found its association link. existingDuplicationRecord.DuplicationKind = DuplicationKind.NavigationProperty; existingDuplicationRecord.AssociationLinkName = associationLinkName; existingDuplicationRecord.AssociationLinkUrl = associationLinkUrl; } else { // In all other cases fail. throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(associationLinkName)); } return existingDuplicationRecord.NavigationLink; } } /// <summary> /// Clear the internal data structures of the checker so it can be reused. /// </summary> internal void Clear() { if (this.propertyNameCache != null) { this.propertyNameCache.Clear(); } } /// <summary> /// Adds an OData annotation to a property. /// </summary> /// <param name="propertyName">The name of the property to add annotation to. string.empty means the annotation is for the current scope.</param> /// <param name="annotationName">The name of the annotation to add.</param> /// <param name="annotationValue">The valud of the annotation to add.</param> internal void AddODataPropertyAnnotation(string propertyName, string annotationName, object annotationValue) { Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)"); Debug.Assert(JsonLight.ODataJsonLightReaderUtils.IsODataAnnotationName(annotationName), "annotationName must be an OData annotation."); DuplicationRecord duplicationRecord = this.GetDuplicationRecordToAddPropertyAnnotation(propertyName, annotationName); Dictionary<string, object> odataAnnotations = duplicationRecord.PropertyODataAnnotations; if (odataAnnotations == null) { odataAnnotations = new Dictionary<string, object>(StringComparer.Ordinal); duplicationRecord.PropertyODataAnnotations = odataAnnotations; } else if (odataAnnotations.ContainsKey(annotationName)) { if (ODataJsonLightReaderUtils.IsAnnotationProperty(propertyName)) { throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicateAnnotationForInstanceAnnotationNotAllowed(annotationName, propertyName)); } throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed(annotationName, propertyName)); } odataAnnotations.Add(annotationName, annotationValue); } /// <summary> /// Adds a custom annotation to a property. /// </summary> /// <param name="propertyName">The name of the property to add annotation to. string.empty means the annotation is for the current scope.</param> /// <param name="annotationName">The name of the annotation to add.</param> /// <param name="annotationValue">The valud of the annotation to add.</param> internal void AddCustomPropertyAnnotation(string propertyName, string annotationName, object annotationValue = null) { Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)"); Debug.Assert(!JsonLight.ODataJsonLightReaderUtils.IsODataAnnotationName(annotationName), "annotationName must not be an OData annotation."); DuplicationRecord duplicationRecord = this.GetDuplicationRecordToAddPropertyAnnotation(propertyName, annotationName); Dictionary<string, object> customAnnotations = duplicationRecord.PropertyCustomAnnotations; if (customAnnotations == null) { customAnnotations = new Dictionary<string, object>(StringComparer.Ordinal); duplicationRecord.PropertyCustomAnnotations = customAnnotations; } else if (customAnnotations.ContainsKey(annotationName)) { throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicateAnnotationForPropertyNotAllowed(annotationName, propertyName)); } customAnnotations.Add(annotationName, annotationValue); } /// <summary> /// Returns OData annotations for the specified property with name <paramref name="propertyName"/>. /// </summary> /// <param name="propertyName">The name of the property to return the annotations for.</param> /// <returns>Enumeration of pairs of OData annotation name and and the annotation value, or null if there are no OData annotations for the property.</returns> internal Dictionary<string, object> GetODataPropertyAnnotations(string propertyName) { Debug.Assert(propertyName != null, "propertyName != null"); DuplicationRecord duplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out duplicationRecord)) { return null; } // TODO: Refactor the duplicate property names checker and use different implementations for JSON Light // and the other formats (most of the logic is not needed for JSON Light). // Once we create a JSON Light specific duplicate property names checker, we will check for duplicates in // the ParseProperty method and thus detect duplicates before we get here. ThrowIfPropertyIsProcessed(propertyName, duplicationRecord); return duplicationRecord.PropertyODataAnnotations; } /// <summary> /// Returns custom instance annotations for the specified property with name <paramref name="propertyName"/>. /// </summary> /// <param name="propertyName">The name of the property to return the annotations for.</param> /// <returns>Enumeration of pairs of custom instance annotation name and and the annotation value, or null if there are no OData annotations for the property.</returns> internal Dictionary<string, object> GetCustomPropertyAnnotations(string propertyName) { Debug.Assert(propertyName != null, "propertyName != null"); DuplicationRecord duplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out duplicationRecord)) { return null; } // TODO: Refactor the duplicate property names checker and use different implementations for JSON Light // and the other formats (most of the logic is not needed for JSON Light). // Once we create a JSON Light specific duplicate property names checker, we will check for duplicates in // the ParseProperty method and thus detect duplicates before we get here. ThrowIfPropertyIsProcessed(propertyName, duplicationRecord); return duplicationRecord.PropertyCustomAnnotations; } /// <summary> /// Marks the <paramref name="propertyName"/> property to note that all its annotations were already processed. /// </summary> /// <param name="propertyName">The property name to mark.</param> /// <remarks> /// Properties marked like this will fail if there are more annotations found for them in the payload. /// </remarks> internal void MarkPropertyAsProcessed(string propertyName) { if (this.disabled) { return; } Debug.Assert(propertyName != null, "propertyName != null"); DuplicationRecord duplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out duplicationRecord)) { duplicationRecord = new DuplicationRecord(DuplicationKind.PropertyAnnotationSeen); this.propertyNameCache.Add(propertyName, duplicationRecord); } ThrowIfPropertyIsProcessed(propertyName, duplicationRecord); duplicationRecord.PropertyODataAnnotations = propertyAnnotationsProcessedToken; } /// <summary> /// Throw if property is processed already. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="duplicationRecord">DuplicationRecord of the property.</param> private static void ThrowIfPropertyIsProcessed(string propertyName, DuplicationRecord duplicationRecord) { if (object.ReferenceEquals(duplicationRecord.PropertyODataAnnotations, propertyAnnotationsProcessedToken)) { if (ODataJsonLightReaderUtils.IsAnnotationProperty(propertyName) && !ODataJsonLightUtils.IsMetadataReferenceProperty(propertyName)) { throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicateAnnotationNotAllowed(propertyName)); } throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(propertyName)); } } /// <summary> /// Decides whether a the given <paramref name="property"/> supports duplicates (if allowed by the settings). /// </summary> /// <param name="property">The property to check.</param> /// <returns>true if the <paramref name="property"/> supports duplicates (if allowed by the settings); otherwise false.</returns> private static DuplicationKind GetDuplicationKind(ODataProperty property) { object value = property.Value; return value != null && (value is ODataStreamReferenceValue || value is ODataCollectionValue) ? DuplicationKind.Prohibited : DuplicationKind.PotentiallyAllowed; } /// <summary> /// Determines the effective value for the isCollection flag. /// </summary> /// <param name="isExpanded">true if the navigation link is expanded, false otherwise.</param> /// <param name="isCollection">true if the navigation link is marked as collection, false if it's marked as singletong or null if we don't know.</param> /// <returns>The effective value of the isCollection flag. Note that we can't rely on singleton links which are not expanded since /// those can appear even in cases where the actual navigation property is a collection. /// We allow singleton deferred links for collection properties in requests, as that is one way of expressing a bind operation.</returns> private static bool? GetIsCollectionEffectiveValue(bool isExpanded, bool? isCollection) { return isExpanded ? isCollection : (isCollection == true ? (bool?)true : null); } /// <summary> /// Sets the properties on a duplication record for a navigation link. /// </summary> /// <param name="duplicationRecord">The duplication record to modify.</param> /// <param name="navigationLink">The navigation link found for this property.</param> /// <param name="isExpanded">true if the navigation link is expanded, false otherwise.</param> /// <param name="isCollection">true if the navigation link is marked as collection, false if it's marked as singletong or null if we don't know.</param> private static void ApplyNavigationLinkToDuplicationRecord(DuplicationRecord duplicationRecord, ODataNavigationLink navigationLink, bool isExpanded, bool? isCollection) { duplicationRecord.DuplicationKind = DuplicationKind.NavigationProperty; duplicationRecord.NavigationLink = navigationLink; // We only take the cardinality of the link for granted if it was expanded or if it is a collection. // We can't rely on singleton deferred links to know the cardinality since they can be used for binding even if the actual link is a collection. duplicationRecord.NavigationPropertyIsCollection = GetIsCollectionEffectiveValue(isExpanded, isCollection); } /// <summary> /// Tries to get an existing duplication record for the specified <paramref name="propertyName"/>. /// </summary> /// <param name="propertyName">The property name to look for.</param> /// <param name="duplicationRecord">The existing duplication if one was already found.</param> /// <returns>true if a duplication record already exists, false otherwise.</returns> /// <remarks>This method also initializes the cache if it was not initialized yet.</remarks> private bool TryGetDuplicationRecord(string propertyName, out DuplicationRecord duplicationRecord) { if (this.propertyNameCache == null) { this.propertyNameCache = new Dictionary<string, DuplicationRecord>(StringComparer.Ordinal); duplicationRecord = null; return false; } return this.propertyNameCache.TryGetValue(propertyName, out duplicationRecord); } /// <summary> /// Checks for duplication of a navigation link against an existing duplication record. /// </summary> /// <param name="propertyName">The name of the navigation link.</param> /// <param name="existingDuplicationRecord">The existing duplication record.</param> /// <remarks>This only performs checks possible without the knowledge of whether the link was expanded or not.</remarks> private void CheckNavigationLinkDuplicateNameForExistingDuplicationRecord(string propertyName, DuplicationRecord existingDuplicationRecord) { if (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && existingDuplicationRecord.AssociationLinkUrl != null && existingDuplicationRecord.NavigationLink == null) { // Existing one is just an association link, so the new one is a navigation link portion which is OK always. } else if (existingDuplicationRecord.DuplicationKind == DuplicationKind.Prohibited || (existingDuplicationRecord.DuplicationKind == DuplicationKind.PotentiallyAllowed && !this.allowDuplicateProperties) || (existingDuplicationRecord.DuplicationKind == DuplicationKind.NavigationProperty && this.isResponse && !this.allowDuplicateProperties)) { // If the existing one doesn't allow duplication at all, // or it's simple property which does allow duplication, but the configuration does not allow it, // or it's a duplicate navigation property in a response, // fail. throw new ODataException(Strings.DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed(propertyName)); } } /// <summary> /// Gets a duplication record to use for adding property annotation. /// </summary> /// <param name="propertyName">The name of the property to get the duplication record for.</param> /// <param name="annotationName">The name of the annotation being added (only for error reporting).</param> /// <returns>The duplication record to use. This will never be null.</returns> private DuplicationRecord GetDuplicationRecordToAddPropertyAnnotation(string propertyName, string annotationName) { Debug.Assert(propertyName != null, "propertyName != null"); Debug.Assert(!string.IsNullOrEmpty(annotationName), "!string.IsNullOrEmpty(annotationName)"); DuplicationRecord duplicationRecord; if (!this.TryGetDuplicationRecord(propertyName, out duplicationRecord)) { duplicationRecord = new DuplicationRecord(DuplicationKind.PropertyAnnotationSeen); this.propertyNameCache.Add(propertyName, duplicationRecord); } if (object.ReferenceEquals(duplicationRecord.PropertyODataAnnotations, propertyAnnotationsProcessedToken)) { throw new ODataException(Strings.DuplicatePropertyNamesChecker_PropertyAnnotationAfterTheProperty(annotationName, propertyName)); } Debug.Assert(duplicationRecord != null, "duplicationRecord != null"); return duplicationRecord; } /// <summary> /// A record of a single property for duplicate property names checking. /// </summary> private sealed class DuplicationRecord { /// <summary> /// Constructor. /// </summary> /// <param name="duplicationKind">The duplication kind of the record to create.</param> public DuplicationRecord(DuplicationKind duplicationKind) { this.DuplicationKind = duplicationKind; } /// <summary> /// The duplication kind of the record to create. /// </summary> public DuplicationKind DuplicationKind { get; set; } /// <summary> /// The navigation link if it was already found for this property. /// </summary> public ODataNavigationLink NavigationLink { get; set; } /// <summary> /// The association link name if it was already found for this property. /// </summary> public string AssociationLinkName { get; set; } /// <summary> /// The association link url if it was already found for this property. /// </summary> public Uri AssociationLinkUrl { get; set; } /// <summary> /// true if we know for sure that the navigation property with the property name is a collection, /// false if we know for sure that the navigation property with the property name is a singleton, /// null if we don't know the cardinality of the navigation property for sure (yet). /// </summary> public bool? NavigationPropertyIsCollection { get; set; } /// <summary> /// Dictionary of OData annotations for the property for which the duplication record is stored. /// </summary> /// <remarks> /// The key of the dictionary is the fully qualified annotation name (i.e. odata.type), /// the value is the parsed value of the annotation (this is annotation specific). /// </remarks> public Dictionary<string, object> PropertyODataAnnotations { get; set; } /// <summary> /// Dictionary of custom annotations for the property for which the duplication record is stored. /// </summary> /// <remarks> /// The key of the dictionary is the fully qualified annotation name , /// the value is the parsed value of the annotation (this is annotation specific). /// </remarks> public Dictionary<string, object> PropertyCustomAnnotations { get; set; } } } }
using System; using System.Collections; using System.IO; using System.Text; using Raksha.Crypto.Agreement; using Raksha.Crypto.Agreement.Srp; using Raksha.Crypto.Digests; using Raksha.Crypto.Encodings; using Raksha.Crypto.Engines; using Raksha.Crypto.Generators; using Raksha.Crypto.IO; using Raksha.Crypto.Parameters; using Raksha.Math; using Raksha.Utilities.Date; using Raksha.Asn1; using Raksha.Asn1.X509; using Raksha.Crypto.Prng; using Raksha.Security; using Raksha.Utilities; namespace Raksha.Crypto.Tls { /// <remarks>An implementation of all high level protocols in TLS 1.0.</remarks> public class TlsProtocolHandler { /* * Our Connection states */ private const short CS_CLIENT_HELLO_SEND = 1; private const short CS_SERVER_HELLO_RECEIVED = 2; private const short CS_SERVER_CERTIFICATE_RECEIVED = 3; private const short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4; private const short CS_CERTIFICATE_REQUEST_RECEIVED = 5; private const short CS_SERVER_HELLO_DONE_RECEIVED = 6; private const short CS_CLIENT_KEY_EXCHANGE_SEND = 7; private const short CS_CERTIFICATE_VERIFY_SEND = 8; private const short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 9; private const short CS_CLIENT_FINISHED_SEND = 10; private const short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 11; private const short CS_DONE = 12; private static readonly byte[] emptybuf = new byte[0]; private static readonly string TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Queues for data from some protocols. */ private ByteQueue applicationDataQueue = new ByteQueue(); private ByteQueue changeCipherSpecQueue = new ByteQueue(); private ByteQueue alertQueue = new ByteQueue(); private ByteQueue handshakeQueue = new ByteQueue(); /* * The Record Stream we use */ private RecordStream rs; private SecureRandom random; private TlsStream tlsStream = null; private bool closed = false; private bool failedWithError = false; private bool appDataReady = false; private IDictionary clientExtensions; private SecurityParameters securityParameters = null; private TlsClientContextImpl tlsClientContext = null; private TlsClient tlsClient = null; private CipherSuite[] offeredCipherSuites = null; private CompressionMethod[] offeredCompressionMethods = null; private TlsKeyExchange keyExchange = null; private TlsAuthentication authentication = null; private CertificateRequest certificateRequest = null; private short connection_state = 0; private static SecureRandom CreateSecureRandom() { /* * We use our threaded seed generator to generate a good random seed. If the user * has a better random seed, he should use the constructor with a SecureRandom. * * Hopefully, 20 bytes in fast mode are good enough. */ byte[] seed = new ThreadedSeedGenerator().GenerateSeed(20, true); return new SecureRandom(seed); } public TlsProtocolHandler( Stream s) : this(s, s) { } public TlsProtocolHandler( Stream s, SecureRandom sr) : this(s, s, sr) { } /// <remarks>Both streams can be the same object</remarks> public TlsProtocolHandler( Stream inStr, Stream outStr) : this(inStr, outStr, CreateSecureRandom()) { } /// <remarks>Both streams can be the same object</remarks> public TlsProtocolHandler( Stream inStr, Stream outStr, SecureRandom sr) { this.rs = new RecordStream(this, inStr, outStr); this.random = sr; } internal void ProcessData( ContentType protocol, byte[] buf, int offset, int len) { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case ContentType.change_cipher_spec: changeCipherSpecQueue.AddData(buf, offset, len); ProcessChangeCipherSpec(); break; case ContentType.alert: alertQueue.AddData(buf, offset, len); ProcessAlert(); break; case ContentType.handshake: handshakeQueue.AddData(buf, offset, len); ProcessHandshake(); break; case ContentType.application_data: if (!appDataReady) { this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } applicationDataQueue.AddData(buf, offset, len); ProcessApplicationData(); break; default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ break; } } private void ProcessHandshake() { bool read; do { read = false; /* * We need the first 4 bytes, they contain type and length of * the message. */ if (handshakeQueue.Available >= 4) { byte[] beginning = new byte[4]; handshakeQueue.Read(beginning, 0, 4, 0); MemoryStream bis = new MemoryStream(beginning, false); HandshakeType type = (HandshakeType)TlsUtilities.ReadUint8(bis); int len = TlsUtilities.ReadUint24(bis); /* * Check if we have enough bytes in the buffer to read * the full message. */ if (handshakeQueue.Available >= (len + 4)) { /* * Read the message. */ byte[] buf = new byte[len]; handshakeQueue.Read(buf, 0, len, 4); handshakeQueue.RemoveData(len + 4); /* * RFC 2246 7.4.9. The value handshake_messages includes all * handshake messages starting at client hello up to, but not * including, this finished message. [..] Note: [Also,] Hello Request * messages are omitted from handshake hashes. */ switch (type) { case HandshakeType.hello_request: case HandshakeType.finished: break; default: rs.UpdateHandshakeData(beginning, 0, 4); rs.UpdateHandshakeData(buf, 0, len); break; } /* * Now, parse the message. */ ProcessHandshakeMessage(type, buf); read = true; } } } while (read); } private void ProcessHandshakeMessage(HandshakeType type, byte[] buf) { MemoryStream inStr = new MemoryStream(buf, false); /* * Check the type. */ switch (type) { case HandshakeType.certificate: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: { // Parse the Certificate message and send to cipher suite Certificate serverCertificate = Certificate.Parse(inStr); AssertEmpty(inStr); this.keyExchange.ProcessServerCertificate(serverCertificate); this.authentication = tlsClient.GetAuthentication(); this.authentication.NotifyServerCertificate(serverCertificate); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } connection_state = CS_SERVER_CERTIFICATE_RECEIVED; break; } case HandshakeType.finished: switch (connection_state) { case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED: /* * Read the checksum from the finished message, it has always 12 bytes. */ byte[] serverVerifyData = new byte[12]; TlsUtilities.ReadFully(serverVerifyData, inStr); AssertEmpty(inStr); /* * Calculate our own checksum. */ byte[] expectedServerVerifyData = TlsUtilities.PRF( securityParameters.masterSecret, "server finished", rs.GetCurrentHash(), 12); /* * Compare both checksums. */ if (!Arrays.ConstantTimeAreEqual(expectedServerVerifyData, serverVerifyData)) { /* * Wrong checksum in the finished message. */ this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } connection_state = CS_DONE; /* * We are now ready to receive application data. */ this.appDataReady = true; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } break; case HandshakeType.server_hello: switch (connection_state) { case CS_CLIENT_HELLO_SEND: /* * Read the server hello message */ TlsUtilities.CheckVersion(inStr, this); /* * Read the server random */ securityParameters.serverRandom = new byte[32]; TlsUtilities.ReadFully(securityParameters.serverRandom, inStr); byte[] sessionID = TlsUtilities.ReadOpaque8(inStr); if (sessionID.Length > 32) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySessionID(sessionID); /* * Find out which CipherSuite the server has chosen and check that * it was one of the offered ones. */ CipherSuite selectedCipherSuite = (CipherSuite)TlsUtilities.ReadUint16(inStr); if (!ArrayContains(offeredCipherSuites, selectedCipherSuite) || selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySelectedCipherSuite(selectedCipherSuite); /* * Find out which CompressionMethod the server has chosen and check that * it was one of the offered ones. */ CompressionMethod selectedCompressionMethod = (CompressionMethod)TlsUtilities.ReadUint8(inStr); if (!ArrayContains(offeredCompressionMethods, selectedCompressionMethod)) { this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } this.tlsClient.NotifySelectedCompressionMethod(selectedCompressionMethod); /* * RFC3546 2.2 The extended server hello message format MAY be * sent in place of the server hello message when the client has * requested extended functionality via the extended client hello * message specified in Section 2.1. * ... * Note that the extended server hello message is only sent in response * to an extended client hello message. This prevents the possibility * that the extended server hello message could "break" existing TLS 1.0 * clients. */ /* * TODO RFC 3546 2.3 * If [...] the older session is resumed, then the server MUST ignore * extensions appearing in the client hello, and send a server hello * containing no extensions. */ // ExtensionType -> byte[] IDictionary serverExtensions = Platform.CreateHashtable(); if (inStr.Position < inStr.Length) { // Process extensions from extended server hello byte[] extBytes = TlsUtilities.ReadOpaque16(inStr); MemoryStream ext = new MemoryStream(extBytes, false); while (ext.Position < ext.Length) { ExtensionType extType = (ExtensionType)TlsUtilities.ReadUint16(ext); byte[] extValue = TlsUtilities.ReadOpaque16(ext); // Note: RFC 5746 makes a special case for EXT_RenegotiationInfo if (extType != ExtensionType.renegotiation_info && !clientExtensions.Contains(extType)) { /* * RFC 3546 2.3 * Note that for all extension types (including those defined in * future), the extension type MUST NOT appear in the extended server * hello unless the same extension type appeared in the corresponding * client hello. Thus clients MUST abort the handshake if they receive * an extension type in the extended server hello that they did not * request in the associated (extended) client hello. */ this.FailWithError(AlertLevel.fatal, AlertDescription.unsupported_extension); } if (serverExtensions.Contains(extType)) { /* * RFC 3546 2.3 * Also note that when multiple extensions of different types are * present in the extended client hello or the extended server hello, * the extensions may appear in any order. There MUST NOT be more than * one extension of the same type. */ this.FailWithError(AlertLevel.fatal, AlertDescription.illegal_parameter); } serverExtensions.Add(extType, extValue); } } AssertEmpty(inStr); /* * RFC 5746 3.4. When a ServerHello is received, the client MUST check if it * includes the "renegotiation_info" extension: */ { bool secure_negotiation = serverExtensions.Contains(ExtensionType.renegotiation_info); /* * If the extension is present, set the secure_renegotiation flag * to TRUE. The client MUST then verify that the length of the * "renegotiated_connection" field is zero, and if it is not, MUST * abort the handshake (by sending a fatal handshake_failure * alert). */ if (secure_negotiation) { byte[] renegExtValue = (byte[])serverExtensions[ExtensionType.renegotiation_info]; if (!Arrays.ConstantTimeAreEqual(renegExtValue, CreateRenegotiationInfo(emptybuf))) { this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } } tlsClient.NotifySecureRenegotiation(secure_negotiation); } if (clientExtensions != null) { tlsClient.ProcessServerExtensions(serverExtensions); } this.keyExchange = tlsClient.GetKeyExchange(); connection_state = CS_SERVER_HELLO_RECEIVED; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } break; case HandshakeType.server_hello_done: switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: case CS_SERVER_KEY_EXCHANGE_RECEIVED: case CS_CERTIFICATE_REQUEST_RECEIVED: // NB: Original code used case label fall-through if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED) { // There was no server key exchange message; check it's OK this.keyExchange.SkipServerKeyExchange(); } AssertEmpty(inStr); connection_state = CS_SERVER_HELLO_DONE_RECEIVED; TlsCredentials clientCreds = null; if (certificateRequest == null) { this.keyExchange.SkipClientCredentials(); } else { clientCreds = this.authentication.GetClientCredentials(certificateRequest); Certificate clientCert; if (clientCreds == null) { this.keyExchange.SkipClientCredentials(); clientCert = Certificate.EmptyChain; } else { this.keyExchange.ProcessClientCredentials(clientCreds); clientCert = clientCreds.Certificate; } SendClientCertificate(clientCert); } /* * Send the client key exchange message, depending on the key * exchange we are using in our CipherSuite. */ SendClientKeyExchange(); connection_state = CS_CLIENT_KEY_EXCHANGE_SEND; if (clientCreds != null && clientCreds is TlsSignerCredentials) { TlsSignerCredentials signerCreds = (TlsSignerCredentials)clientCreds; byte[] md5andsha1 = rs.GetCurrentHash(); byte[] clientCertificateSignature = signerCreds.GenerateCertificateSignature( md5andsha1); SendCertificateVerify(clientCertificateSignature); connection_state = CS_CERTIFICATE_VERIFY_SEND; } /* * Now, we send change cipher state */ byte[] cmessage = new byte[1]; cmessage[0] = 1; rs.WriteMessage(ContentType.change_cipher_spec, cmessage, 0, cmessage.Length); connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND; /* * Calculate the master_secret */ byte[] pms = this.keyExchange.GeneratePremasterSecret(); securityParameters.masterSecret = TlsUtilities.PRF(pms, "master secret", TlsUtilities.Concat(securityParameters.clientRandom, securityParameters.serverRandom), 48); // TODO Is there a way to ensure the data is really overwritten? /* * RFC 2246 8.1. The pre_master_secret should be deleted from * memory once the master_secret has been computed. */ Array.Clear(pms, 0, pms.Length); /* * Initialize our cipher suite */ rs.ClientCipherSpecDecided(tlsClient.GetCompression(), tlsClient.GetCipher()); /* * Send our finished message. */ byte[] clientVerifyData = TlsUtilities.PRF(securityParameters.masterSecret, "client finished", rs.GetCurrentHash(), 12); MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.finished, bos); TlsUtilities.WriteOpaque24(clientVerifyData, bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); this.connection_state = CS_CLIENT_FINISHED_SEND; break; default: this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); break; } break; case HandshakeType.server_key_exchange: { switch (connection_state) { case CS_SERVER_HELLO_RECEIVED: case CS_SERVER_CERTIFICATE_RECEIVED: { // NB: Original code used case label fall-through if (connection_state == CS_SERVER_HELLO_RECEIVED) { // There was no server certificate message; check it's OK this.keyExchange.SkipServerCertificate(); this.authentication = null; } this.keyExchange.ProcessServerKeyExchange(inStr); AssertEmpty(inStr); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED; break; } case HandshakeType.certificate_request: switch (connection_state) { case CS_SERVER_CERTIFICATE_RECEIVED: case CS_SERVER_KEY_EXCHANGE_RECEIVED: { // NB: Original code used case label fall-through if (connection_state == CS_SERVER_CERTIFICATE_RECEIVED) { // There was no server key exchange message; check it's OK this.keyExchange.SkipServerKeyExchange(); } if (this.authentication == null) { /* * RFC 2246 7.4.4. It is a fatal handshake_failure alert * for an anonymous server to request client identification. */ this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } int numTypes = TlsUtilities.ReadUint8(inStr); ClientCertificateType[] certificateTypes = new ClientCertificateType[numTypes]; for (int i = 0; i < numTypes; ++i) { certificateTypes[i] = (ClientCertificateType)TlsUtilities.ReadUint8(inStr); } byte[] authorities = TlsUtilities.ReadOpaque16(inStr); AssertEmpty(inStr); IList authorityDNs = Platform.CreateArrayList(); MemoryStream bis = new MemoryStream(authorities, false); while (bis.Position < bis.Length) { byte[] dnBytes = TlsUtilities.ReadOpaque16(bis); // TODO Switch to X500Name when available authorityDNs.Add(X509Name.GetInstance(Asn1Object.FromByteArray(dnBytes))); } this.certificateRequest = new CertificateRequest(certificateTypes, authorityDNs); this.keyExchange.ValidateCertificateRequest(this.certificateRequest); break; } default: this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED; break; case HandshakeType.hello_request: /* * RFC 2246 7.4.1.1 Hello request * This message will be ignored by the client if the client is currently * negotiating a session. This message may be ignored by the client if it * does not wish to renegotiate a session, or the client may, if it wishes, * respond with a no_renegotiation alert. */ if (connection_state == CS_DONE) { // Renegotiation not supported yet SendAlert(AlertLevel.warning, AlertDescription.no_renegotiation); } break; case HandshakeType.client_key_exchange: case HandshakeType.certificate_verify: case HandshakeType.client_hello: default: // We do not support this! this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); break; } } private void ProcessApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application * data arrives in the future. */ } private void ProcessAlert() { while (alertQueue.Available >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = new byte[2]; alertQueue.Read(tmp, 0, 2, 0); alertQueue.RemoveData(2); byte level = tmp[0]; byte description = tmp[1]; if (level == (byte)AlertLevel.fatal) { /* * This is a fatal error. */ this.failedWithError = true; this.closed = true; /* * Now try to Close the stream, ignore errors. */ try { rs.Close(); } catch (Exception) { } throw new IOException(TLS_ERROR_MESSAGE); } else { /* * This is just a warning. */ if (description == (byte)AlertDescription.close_notify) { /* * Close notify */ this.FailWithError(AlertLevel.warning, AlertDescription.close_notify); } /* * If it is just a warning, we continue. */ } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the * handshake is not in the correct state. */ private void ProcessChangeCipherSpec() { while (changeCipherSpecQueue.Available > 0) { /* * A change cipher spec message is only one byte with the value 1. */ byte[] b = new byte[1]; changeCipherSpecQueue.Read(b, 0, 1, 0); changeCipherSpecQueue.RemoveData(1); if (b[0] != 1) { /* * This should never happen. */ this.FailWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } /* * Check if we are in the correct connection state. */ if (this.connection_state != CS_CLIENT_FINISHED_SEND) { this.FailWithError(AlertLevel.fatal, AlertDescription.handshake_failure); } rs.ServerClientSpecReceived(); this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED; } } private void SendClientCertificate(Certificate clientCert) { MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.certificate, bos); clientCert.Encode(bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } private void SendClientKeyExchange() { MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.client_key_exchange, bos); this.keyExchange.GenerateClientKeyExchange(bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } private void SendCertificateVerify(byte[] data) { /* * Send signature of handshake messages so far to prove we are the owner of * the cert See RFC 2246 sections 4.7, 7.4.3 and 7.4.8 */ MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.certificate_verify, bos); TlsUtilities.WriteUint24(data.Length + 2, bos); TlsUtilities.WriteOpaque16(data, bos); byte[] message = bos.ToArray(); rs.WriteMessage(ContentType.handshake, message, 0, message.Length); } /// <summary>Connects to the remote system.</summary> /// <param name="verifyer">Will be used when a certificate is received to verify /// that this certificate is accepted by the client.</param> /// <exception cref="IOException">If handshake was not successful</exception> [Obsolete("Use version taking TlsClient")] public virtual void Connect( ICertificateVerifyer verifyer) { this.Connect(new LegacyTlsClient(verifyer)); } public virtual void Connect(TlsClient tlsClient) { if (tlsClient == null) throw new ArgumentNullException("tlsClient"); if (this.tlsClient != null) throw new InvalidOperationException("Connect can only be called once"); /* * Send Client hello * * First, generate some random data. */ this.securityParameters = new SecurityParameters(); this.securityParameters.clientRandom = new byte[32]; random.NextBytes(securityParameters.clientRandom, 4, 28); TlsUtilities.WriteGmtUnixTime(securityParameters.clientRandom, 0); this.tlsClientContext = new TlsClientContextImpl(random, securityParameters); this.tlsClient = tlsClient; this.tlsClient.Init(tlsClientContext); MemoryStream outStr = new MemoryStream(); TlsUtilities.WriteVersion(outStr); outStr.Write(securityParameters.clientRandom, 0, 32); /* * Length of Session id */ TlsUtilities.WriteUint8(0, outStr); this.offeredCipherSuites = this.tlsClient.GetCipherSuites(); // ExtensionType -> byte[] this.clientExtensions = this.tlsClient.GetClientExtensions(); // Cipher Suites (and SCSV) { /* * RFC 5746 3.4. * The client MUST include either an empty "renegotiation_info" * extension, or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling * cipher suite value in the ClientHello. Including both is NOT * RECOMMENDED. */ bool noRenegExt = clientExtensions == null || !clientExtensions.Contains(ExtensionType.renegotiation_info); int count = offeredCipherSuites.Length; if (noRenegExt) { // Note: 1 extra slot for TLS_EMPTY_RENEGOTIATION_INFO_SCSV ++count; } TlsUtilities.WriteUint16(2 * count, outStr); for (int i = 0; i < offeredCipherSuites.Length; ++i) { TlsUtilities.WriteUint16((int)offeredCipherSuites[i], outStr); } if (noRenegExt) { TlsUtilities.WriteUint16((int)CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV, outStr); } } /* * Compression methods, just the null method. */ this.offeredCompressionMethods = tlsClient.GetCompressionMethods(); { TlsUtilities.WriteUint8((byte)offeredCompressionMethods.Length, outStr); for (int i = 0; i < offeredCompressionMethods.Length; ++i) { TlsUtilities.WriteUint8((byte)offeredCompressionMethods[i], outStr); } } // Extensions if (clientExtensions != null) { MemoryStream ext = new MemoryStream(); foreach (ExtensionType extType in clientExtensions.Keys) { WriteExtension(ext, extType, (byte[])clientExtensions[extType]); } TlsUtilities.WriteOpaque16(ext.ToArray(), outStr); } MemoryStream bos = new MemoryStream(); TlsUtilities.WriteUint8((byte)HandshakeType.client_hello, bos); TlsUtilities.WriteUint24((int)outStr.Length, bos); byte[] outBytes = outStr.ToArray(); bos.Write(outBytes, 0, outBytes.Length); byte[] message = bos.ToArray(); SafeWriteMessage(ContentType.handshake, message, 0, message.Length); connection_state = CS_CLIENT_HELLO_SEND; /* * We will now read data, until we have completed the handshake. */ while (connection_state != CS_DONE) { SafeReadData(); } this.tlsStream = new TlsStream(this); } /** * Read data from the network. The method will return immediately, if there is * still some data left in the buffer, or block until some application * data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ internal int ReadApplicationData(byte[] buf, int offset, int len) { while (applicationDataQueue.Available == 0) { if (this.closed) { /* * We need to read some data. */ if (this.failedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } /* * Connection has been closed, there is no more data to read. */ return 0; } SafeReadData(); } len = System.Math.Min(len, applicationDataQueue.Available); applicationDataQueue.Read(buf, offset, len, 0); applicationDataQueue.RemoveData(len); return len; } private void SafeReadData() { try { rs.ReadData(); } catch (TlsFatalAlert e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription); } throw e; } catch (IOException e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } catch (Exception e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } } private void SafeWriteMessage(ContentType type, byte[] buf, int offset, int len) { try { rs.WriteMessage(type, buf, offset, len); } catch (TlsFatalAlert e) { if (!this.closed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription); } throw e; } catch (IOException e) { if (!closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } catch (Exception e) { if (!closed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error); } throw e; } } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ internal void WriteData(byte[] buf, int offset, int len) { if (this.closed) { if (this.failedWithError) throw new IOException(TLS_ERROR_MESSAGE); throw new IOException("Sorry, connection has been closed, you cannot write more data"); } /* * Protect against known IV attack! * * DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT * YOU ARE DOING HERE. */ SafeWriteMessage(ContentType.application_data, emptybuf, 0, 0); do { /* * We are only allowed to write fragments up to 2^14 bytes. */ int toWrite = System.Math.Min(len, 1 << 14); SafeWriteMessage(ContentType.application_data, buf, offset, toWrite); offset += toWrite; len -= toWrite; } while (len > 0); } /// <summary>A Stream which can be used to send data.</summary> [Obsolete("Use 'Stream' property instead")] public virtual Stream OutputStream { get { return this.tlsStream; } } /// <summary>A Stream which can be used to read data.</summary> [Obsolete("Use 'Stream' property instead")] public virtual Stream InputStream { get { return this.tlsStream; } } /// <summary>The secure bidirectional stream for this connection</summary> public virtual Stream Stream { get { return this.tlsStream; } } /** * Terminate this connection with an alert. * <p/> * Can be used for normal closure too. * * @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning. * @param alertDescription The exact alert message. * @throws IOException If alert was fatal. */ private void FailWithError(AlertLevel alertLevel, AlertDescription alertDescription) { /* * Check if the connection is still open. */ if (!closed) { /* * Prepare the message */ this.closed = true; if (alertLevel == AlertLevel.fatal) { /* * This is a fatal message. */ this.failedWithError = true; } SendAlert(alertLevel, alertDescription); rs.Close(); if (alertLevel == AlertLevel.fatal) { throw new IOException(TLS_ERROR_MESSAGE); } } else { throw new IOException(TLS_ERROR_MESSAGE); } } internal void SendAlert(AlertLevel alertLevel, AlertDescription alertDescription) { byte[] error = new byte[2]; error[0] = (byte)alertLevel; error[1] = (byte)alertDescription; rs.WriteMessage(ContentType.alert, error, 0, 2); } /// <summary>Closes this connection</summary> /// <exception cref="IOException">If something goes wrong during closing.</exception> public virtual void Close() { if (!closed) { this.FailWithError(AlertLevel.warning, AlertDescription.close_notify); } } /** * Make sure the Stream is now empty. Fail otherwise. * * @param is The Stream to check. * @throws IOException If is is not empty. */ internal void AssertEmpty( MemoryStream inStr) { if (inStr.Position < inStr.Length) { throw new TlsFatalAlert(AlertDescription.decode_error); } } internal void Flush() { rs.Flush(); } internal bool IsClosed { get { return closed; } } private static bool ArrayContains(CipherSuite[] a, CipherSuite n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } private static bool ArrayContains(CompressionMethod[] a, CompressionMethod n) { for (int i = 0; i < a.Length; ++i) { if (a[i] == n) return true; } return false; } private static byte[] CreateRenegotiationInfo(byte[] renegotiated_connection) { MemoryStream buf = new MemoryStream(); TlsUtilities.WriteOpaque8(renegotiated_connection, buf); return buf.ToArray(); } private static void WriteExtension(Stream output, ExtensionType extType, byte[] extValue) { TlsUtilities.WriteUint16((int)extType, output); TlsUtilities.WriteOpaque16(extValue, output); } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using ZXing.Aztec; using ZXing.Datamatrix; using ZXing.IMB; using ZXing.Maxicode; using ZXing.MicroQrCode; using ZXing.OneD; using ZXing.PDF417; using ZXing.QrCode; namespace ZXing { /// <summary> /// MultiFormatReader is a convenience class and the main entry point into the library for most uses. /// By default it attempts to decode all barcode formats that the library supports. Optionally, you /// can provide a hints object to request different behavior, for example only decoding QR codes. /// </summary> /// <author>Sean Owen</author> /// <author>[email protected] (Daniel Switkin)</author> /// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source</author> public sealed class MultiFormatReader : Reader { private IDictionary<DecodeHintType, object> hints; private IList<Reader> readers; /// <summary> This version of decode honors the intent of Reader.decode(BinaryBitmap) in that it /// passes null as a hint to the decoders. However, that makes it inefficient to call repeatedly. /// Use setHints() followed by decodeWithState() for continuous scan applications. /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decode(BinaryBitmap image) { Hints = null; return decodeInternal(image); } /// <summary> Decode an image using the hints provided. Does not honor existing state. /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <param name="hints">The hints to use, clearing the previous state. /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { Hints = hints; return decodeInternal(image); } /// <summary> Decode an image using the state set up by calling setHints() previously. Continuous scan /// clients will get a <b>large</b> speed increase by using this instead of decode(). /// /// </summary> /// <param name="image">The pixel data to decode /// </param> /// <returns> The contents of the image /// </returns> /// <throws> ReaderException Any errors which occurred </throws> public Result decodeWithState(BinaryBitmap image) { // Make sure to set up the default state so we don't crash if (readers == null) { Hints = null; } return decodeInternal(image); } /// <summary> This method adds state to the MultiFormatReader. By setting the hints once, subsequent calls /// to decodeWithState(image) can reuse the same set of readers without reallocating memory. This /// is important for performance in continuous scan clients. /// /// </summary> /// <param name="hints">The set of hints to use for subsequent calls to decode(image) /// </param> public IDictionary<DecodeHintType, object> Hints { set { hints = value; var tryHarder = value != null && value.ContainsKey(DecodeHintType.TRY_HARDER); var formats = value == null || !value.ContainsKey(DecodeHintType.POSSIBLE_FORMATS) ? null : (IList<BarcodeFormat>)value[DecodeHintType.POSSIBLE_FORMATS]; if (formats != null) { bool addOneDReader = formats.Contains(BarcodeFormat.All_1D) || formats.Contains(BarcodeFormat.UPC_A) || formats.Contains(BarcodeFormat.UPC_E) || formats.Contains(BarcodeFormat.EAN_13) || formats.Contains(BarcodeFormat.EAN_8) || formats.Contains(BarcodeFormat.CODABAR) || formats.Contains(BarcodeFormat.CODE_39) || formats.Contains(BarcodeFormat.CODE_93) || formats.Contains(BarcodeFormat.CODE_128) || formats.Contains(BarcodeFormat.ITF) || formats.Contains(BarcodeFormat.RSS_14) || formats.Contains(BarcodeFormat.RSS_EXPANDED); readers = new List<Reader>(); // Put 1D readers upfront in "normal" mode if (addOneDReader && !tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } if (formats.Contains(BarcodeFormat.QR_CODE)) { readers.Add(new QRCodeReader()); } if (formats.Contains(BarcodeFormat.MICRO_QR_CODE)) { readers.Add(new MicroQRCodeReader()); } if (formats.Contains(BarcodeFormat.DATA_MATRIX)) { readers.Add(new DataMatrixReader()); } if (formats.Contains(BarcodeFormat.AZTEC)) { readers.Add(new AztecReader()); } if (formats.Contains(BarcodeFormat.PDF_417)) { readers.Add(new PDF417Reader()); } if (formats.Contains(BarcodeFormat.MAXICODE)) { readers.Add(new MaxiCodeReader()); } if (formats.Contains(BarcodeFormat.IMB)) { readers.Add(new IMBReader()); } // At end in "try harder" mode if (addOneDReader && tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } } if (readers == null || readers.Count == 0) { readers = readers ?? new List<Reader>(); if (!tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } readers.Add(new QRCodeReader()); readers.Add(new MicroQRCodeReader()); readers.Add(new DataMatrixReader()); readers.Add(new AztecReader()); readers.Add(new PDF417Reader()); readers.Add(new MaxiCodeReader()); if (tryHarder) { readers.Add(new MultiFormatOneDReader(value)); } } } } public void reset() { if (readers != null) { foreach (var reader in readers) { reader.reset(); } } } private Result decodeInternal(BinaryBitmap image) { if (readers != null) { var rpCallback = hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK] : null; for (var index = 0; index < readers.Count; index++) { var reader = readers[index]; reader.reset(); var result = reader.decode(image, hints); if (result != null) { // found a barcode, pushing the successful reader up front // I assume that the same type of barcode is read multiple times // so the reordering of the readers list should speed up the next reading // a little bit readers.RemoveAt(index); readers.Insert(0, reader); return result; } if (rpCallback != null) rpCallback(null); } } return null; } } }
using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.Arm.Arm64 { /// <summary> /// This class provides access to the Arm64 AdvSIMD intrinsics /// /// Arm64 CPU indicate support for this feature by setting /// ID_AA64PFR0_EL1.AdvSIMD == 0 or better. /// </summary> [CLSCompliant(false)] public static class Simd { /// <summary> /// IsSupported property indicates whether any method provided /// by this class is supported by the current runtime. /// </summary> public static bool IsSupported { get { return false; }} /// <summary> /// Vector abs /// Corresponds to vector forms of ARM64 ABS & FABS /// </summary> public static Vector64<byte> Abs(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector64<ushort> Abs(Vector64<short> value) { throw new PlatformNotSupportedException(); } public static Vector64<uint> Abs(Vector64<int> value) { throw new PlatformNotSupportedException(); } public static Vector64<float> Abs(Vector64<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<byte> Abs(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector128<ushort> Abs(Vector128<short> value) { throw new PlatformNotSupportedException(); } public static Vector128<uint> Abs(Vector128<int> value) { throw new PlatformNotSupportedException(); } public static Vector128<ulong> Abs(Vector128<long> value) { throw new PlatformNotSupportedException(); } public static Vector128<float> Abs(Vector128<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<double> Abs(Vector128<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector add /// Corresponds to vector forms of ARM64 ADD & FADD /// </summary> public static Vector64<T> Add<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Add<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector and /// Corresponds to vector forms of ARM64 AND /// </summary> public static Vector64<T> And<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> And<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector and not /// Corresponds to vector forms of ARM64 BIC /// </summary> public static Vector64<T> AndNot<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> AndNot<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector BitwiseSelect /// For each bit in the vector result[bit] = sel[bit] ? left[bit] : right[bit] /// Corresponds to vector forms of ARM64 BSL (Also BIF & BIT) /// </summary> public static Vector64<T> BitwiseSelect<T>(Vector64<T> sel, Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> BitwiseSelect<T>(Vector128<T> sel, Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareEqual /// For each element result[elem] = (left[elem] == right[elem]) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ /// </summary> public static Vector64<T> CompareEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareEqualZero /// For each element result[elem] = (left[elem] == 0) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMEQ & FCMEQ /// </summary> public static Vector64<T> CompareEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareGreaterThan /// For each element result[elem] = (left[elem] > right[elem]) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGT/CMHI & FCMGT /// </summary> public static Vector64<T> CompareGreaterThan<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareGreaterThan<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareGreaterThanZero /// For each element result[elem] = (left[elem] > 0) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGT & FCMGT /// </summary> public static Vector64<T> CompareGreaterThanZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareGreaterThanZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareGreaterThanOrEqual /// For each element result[elem] = (left[elem] >= right[elem]) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGE/CMHS & FCMGE /// </summary> public static Vector64<T> CompareGreaterThanOrEqual<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareGreaterThanOrEqual<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareGreaterThanOrEqualZero /// For each element result[elem] = (left[elem] >= 0) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGE & FCMGE /// </summary> public static Vector64<T> CompareGreaterThanOrEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareGreaterThanOrEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareLessThanZero /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGT & FCMGT /// </summary> public static Vector64<T> CompareLessThanZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareLessThanZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareLessThanOrEqualZero /// For each element result[elem] = (left[elem] < 0) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMGT & FCMGT /// </summary> public static Vector64<T> CompareLessThanOrEqualZero<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareLessThanOrEqualZero<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector CompareTest /// For each element result[elem] = (left[elem] & right[elem]) ? ~0 : 0 /// Corresponds to vector forms of ARM64 CMTST /// </summary> public static Vector64<T> CompareTest<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> CompareTest<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// TBD Convert... /// <summary> /// Vector Divide /// Corresponds to vector forms of ARM64 FDIV /// </summary> public static Vector64<float> Divide(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector extract item /// /// result = vector[index] /// /// Note: In order to be inlined, index must be a JIT time const expression which can be used to /// populate the literal immediate field. Use of a non constant will result in generation of a switch table /// /// Corresponds to vector forms of ARM64 MOV /// </summary> public static T Extract<T>(Vector64<T> vector, byte index) where T : struct { throw new PlatformNotSupportedException(); } public static T Extract<T>(Vector128<T> vector, byte index) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector insert item /// /// result = vector; /// result[index] = data; /// /// Note: In order to be inlined, index must be a JIT time const expression which can be used to /// populate the literal immediate field. Use of a non constant will result in generation of a switch table /// /// Corresponds to vector forms of ARM64 INS /// </summary> public static Vector64<T> Insert<T>(Vector64<T> vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Insert<T>(Vector128<T> vector, byte index, T data) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector LeadingSignCount /// Corresponds to vector forms of ARM64 CLS /// </summary> public static Vector64<sbyte> LeadingSignCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector64<short> LeadingSignCount(Vector64<short> value) { throw new PlatformNotSupportedException(); } public static Vector64<int> LeadingSignCount(Vector64<int> value) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> LeadingSignCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector128<short> LeadingSignCount(Vector128<short> value) { throw new PlatformNotSupportedException(); } public static Vector128<int> LeadingSignCount(Vector128<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector LeadingZeroCount /// Corresponds to vector forms of ARM64 CLZ /// </summary> public static Vector64<byte> LeadingZeroCount(Vector64<byte> value) { throw new PlatformNotSupportedException(); } public static Vector64<sbyte> LeadingZeroCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector64<ushort> LeadingZeroCount(Vector64<ushort> value) { throw new PlatformNotSupportedException(); } public static Vector64<short> LeadingZeroCount(Vector64<short> value) { throw new PlatformNotSupportedException(); } public static Vector64<uint> LeadingZeroCount(Vector64<uint> value) { throw new PlatformNotSupportedException(); } public static Vector64<int> LeadingZeroCount(Vector64<int> value) { throw new PlatformNotSupportedException(); } public static Vector128<byte> LeadingZeroCount(Vector128<byte> value) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> LeadingZeroCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector128<ushort> LeadingZeroCount(Vector128<ushort> value) { throw new PlatformNotSupportedException(); } public static Vector128<short> LeadingZeroCount(Vector128<short> value) { throw new PlatformNotSupportedException(); } public static Vector128<uint> LeadingZeroCount(Vector128<uint> value) { throw new PlatformNotSupportedException(); } public static Vector128<int> LeadingZeroCount(Vector128<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector max /// Corresponds to vector forms of ARM64 SMAX, UMAX & FMAX /// </summary> public static Vector64<byte> Max(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); } public static Vector64<sbyte> Max(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector64<ushort> Max(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector64<short> Max(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); } public static Vector64<uint> Max(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); } public static Vector64<int> Max(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); } public static Vector64<float> Max(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); } public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); } public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); } public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector min /// Corresponds to vector forms of ARM64 SMIN, UMIN & FMIN /// </summary> public static Vector64<byte> Min(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); } public static Vector64<sbyte> Min(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector64<ushort> Min(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector64<short> Min(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); } public static Vector64<uint> Min(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); } public static Vector64<int> Min(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); } public static Vector64<float> Min(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); } public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); } public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); } public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// TBD MOV, FMOV /// <summary> /// Vector multiply /// /// For each element result[elem] = left[elem] * right[elem] /// /// Corresponds to vector forms of ARM64 MUL & FMUL /// </summary> public static Vector64<byte> Multiply(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); } public static Vector64<sbyte> Multiply(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector64<ushort> Multiply(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector64<short> Multiply(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); } public static Vector64<uint> Multiply(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); } public static Vector64<int> Multiply(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); } public static Vector64<float> Multiply(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<byte> Multiply(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> Multiply(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); } public static Vector128<ushort> Multiply(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); } public static Vector128<short> Multiply(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); } public static Vector128<uint> Multiply(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); } public static Vector128<int> Multiply(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); } public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector negate /// Corresponds to vector forms of ARM64 NEG & FNEG /// </summary> public static Vector64<sbyte> Negate(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector64<short> Negate(Vector64<short> value) { throw new PlatformNotSupportedException(); } public static Vector64<int> Negate(Vector64<int> value) { throw new PlatformNotSupportedException(); } public static Vector64<float> Negate(Vector64<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> Negate(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector128<short> Negate(Vector128<short> value) { throw new PlatformNotSupportedException(); } public static Vector128<int> Negate(Vector128<int> value) { throw new PlatformNotSupportedException(); } public static Vector128<long> Negate(Vector128<long> value) { throw new PlatformNotSupportedException(); } public static Vector128<float> Negate(Vector128<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<double> Negate(Vector128<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector not /// Corresponds to vector forms of ARM64 NOT /// </summary> public static Vector64<T> Not<T>(Vector64<T> value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Not<T>(Vector128<T> value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector or /// Corresponds to vector forms of ARM64 ORR /// </summary> public static Vector64<T> Or<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Or<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector or not /// Corresponds to vector forms of ARM64 ORN /// </summary> public static Vector64<T> OrNot<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> OrNot<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector PopCount /// Corresponds to vector forms of ARM64 CNT /// </summary> public static Vector64<byte> PopCount(Vector64<byte> value) { throw new PlatformNotSupportedException(); } public static Vector64<sbyte> PopCount(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } public static Vector128<byte> PopCount(Vector128<byte> value) { throw new PlatformNotSupportedException(); } public static Vector128<sbyte> PopCount(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } /// <summary> /// SetVector* Fill vector elements by replicating element value /// /// Corresponds to vector forms of ARM64 DUP (general), DUP (element 0), FMOV (vector, immediate) /// </summary> public static Vector64<T> SetAllVector64<T>(T value) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> SetAllVector128<T>(T value) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector square root /// Corresponds to vector forms of ARM64 FRSQRT /// </summary> public static Vector64<float> Sqrt(Vector64<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<float> Sqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); } public static Vector128<double> Sqrt(Vector128<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// Vector subtract /// Corresponds to vector forms of ARM64 SUB & FSUB /// </summary> public static Vector64<T> Subtract<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Subtract<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } /// <summary> /// Vector exclusive or /// Corresponds to vector forms of ARM64 EOR /// </summary> public static Vector64<T> Xor<T>(Vector64<T> left, Vector64<T> right) where T : struct { throw new PlatformNotSupportedException(); } public static Vector128<T> Xor<T>(Vector128<T> left, Vector128<T> right) where T : struct { throw new PlatformNotSupportedException(); } } }
// // Copyright (c) @jevertt // Copyright (c) Rafael Rivera // Licensed under the MIT License. See LICENSE in the project root for license information. // using System.IO; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEngine; using System.Net; using System; using System.Xml; namespace HoloToolkit.Unity { /// <summary> /// Build window - supports SLN creation, APPX from SLN, Deploy on device, and misc helper utilities associated with the build/deploy/test iteration loop /// Requires the device to be set in developer mode & to have secure connections disabled (in the security tab in the device portal) /// </summary> public class BuildDeployWindow : EditorWindow { private const float GUISectionOffset = 10.0f; private const string GUIHorizSpacer = " "; private const float UpdateBuildsPeriod = 1.0f; // Properties private bool ShouldOpenSLNBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldBuildSLNBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldBuildAppxBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory) && !string.IsNullOrEmpty(BuildDeployPrefs.MsBuildVersion) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildConfig); } } private bool ShouldLaunchAppBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldWebPortalBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool ShouldLogViewBeEnabled { get { return !string.IsNullOrEmpty(BuildDeployPrefs.TargetIPs) && !string.IsNullOrEmpty(BuildDeployPrefs.BuildDirectory); } } private bool LocalIPsOnly { get { return true; } } // Privates private List<string> builds = new List<string>(); private float timeLastUpdatedBuilds = 0.0f; // Functions [MenuItem("HoloToolkit/Build Window", false, 101)] public static void OpenWindow() { BuildDeployWindow window = GetWindow<BuildDeployWindow>("Build Window") as BuildDeployWindow; if (window != null) { window.Show(); } } void OnEnable() { Setup(); } private void Setup() { this.titleContent = new GUIContent("Build Window"); this.minSize = new Vector2(600, 200); UpdateXdeStatus(); UpdateBuilds(); } private void UpdateXdeStatus() { XdeGuestLocator.FindGuestAddressAsync(); } private void OnGUI() { GUILayout.Space(GUISectionOffset); // Setup int buttonWidth_Quarter = Screen.width / 4; int buttonWidth_Half = Screen.width / 2; int buttonWidth_Full = Screen.width - 25; string appName = PlayerSettings.productName; // Build section GUILayout.BeginVertical(); GUILayout.Label("SLN"); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); // Build directory (and save setting, if it's changed) string curBuildDirectory = BuildDeployPrefs.BuildDirectory; string newBuildDirectory = EditorGUILayout.TextField(GUIHorizSpacer + "Build directory", curBuildDirectory); if (newBuildDirectory != curBuildDirectory) { BuildDeployPrefs.BuildDirectory = newBuildDirectory; curBuildDirectory = newBuildDirectory; } // Build SLN button using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); GUI.enabled = ShouldOpenSLNBeEnabled; if (GUILayout.Button("Open SLN", GUILayout.Width(buttonWidth_Quarter))) { // Open SLN string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln"); if (File.Exists(slnFilename)) { FileInfo slnFile = new FileInfo(slnFilename); System.Diagnostics.Process.Start(slnFile.FullName); } else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No")) { // Build SLN EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); }; } } GUI.enabled = ShouldBuildSLNBeEnabled; if (GUILayout.Button("Build Visual Studio SLN", GUILayout.Width(buttonWidth_Half))) { // Build SLN EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); }; } GUI.enabled = true; } // Build & Run button... using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); GUI.enabled = ShouldBuildSLNBeEnabled; if (GUILayout.Button("Build SLN, Build APPX, then Install", GUILayout.Width(buttonWidth_Half))) { // Build SLN EditorApplication.delayCall += () => { BuildAndRun(appName); }; } GUI.enabled = true; } // Appx sub-section GUILayout.BeginVertical(); GUILayout.Label("APPX"); // MSBuild Ver (and save setting, if it's changed) string curMSBuildVer = BuildDeployPrefs.MsBuildVersion; string newMSBuildVer = EditorGUILayout.TextField(GUIHorizSpacer + "MSBuild Version", curMSBuildVer); if (newMSBuildVer != curMSBuildVer) { BuildDeployPrefs.MsBuildVersion = newMSBuildVer; curMSBuildVer = newMSBuildVer; } // Build config (and save setting, if it's changed) string curBuildConfig = BuildDeployPrefs.BuildConfig; string newBuildConfig = EditorGUILayout.TextField(GUIHorizSpacer + "Build Configuration", curBuildConfig); if (newBuildConfig != curBuildConfig) { BuildDeployPrefs.BuildConfig = newBuildConfig; curBuildConfig = newBuildConfig; } // Build APPX button using (new EditorGUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); // Force rebuild float labelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 50; bool curForceRebuildAppx = BuildDeployPrefs.ForceRebuild; bool newForceRebuildAppx = EditorGUILayout.Toggle("Rebuild", curForceRebuildAppx); if (newForceRebuildAppx != curForceRebuildAppx) { BuildDeployPrefs.ForceRebuild = newForceRebuildAppx; curForceRebuildAppx = newForceRebuildAppx; } EditorGUIUtility.labelWidth = labelWidth; // Build APPX GUI.enabled = ShouldBuildAppxBeEnabled; if (GUILayout.Button("Build APPX from SLN", GUILayout.Width(buttonWidth_Half))) { BuildDeployTools.BuildAppxFromSolution(appName, curMSBuildVer, curForceRebuildAppx, curBuildConfig, curBuildDirectory); } GUI.enabled = true; } GUILayout.EndVertical(); GUILayout.EndVertical(); GUILayout.Space(GUISectionOffset); // Deploy section GUILayout.BeginVertical(); GUILayout.Label("Deploy"); // Target IPs (and save setting, if it's changed) string curTargetIps = BuildDeployPrefs.TargetIPs; if (!LocalIPsOnly) { string newTargetIPs = EditorGUILayout.TextField( new GUIContent(GUIHorizSpacer + "IP Address(es)", "IP(s) of target devices (e.g. 127.0.0.1;10.11.12.13)"), curTargetIps); if (newTargetIPs != curTargetIps) { BuildDeployPrefs.TargetIPs = newTargetIPs; curTargetIps = newTargetIPs; } } else { var isLocatorSearching = XdeGuestLocator.IsSearching; var doesLocatorHaveData = XdeGuestLocator.HasData; var xdeGuestIpAddress = XdeGuestLocator.GuestIpAddress; // Queue up a repaint if we're still busy, or we'll get stuck // in a disabled state. if (isLocatorSearching) Repaint(); var addressesToPresent = new List<string>(); addressesToPresent.Add("127.0.0.1"); if (!isLocatorSearching && doesLocatorHaveData) addressesToPresent.Add(xdeGuestIpAddress.ToString()); var previouslySavedAddress = addressesToPresent.IndexOf(curTargetIps); if (previouslySavedAddress == -1) previouslySavedAddress = 0; EditorGUILayout.BeginHorizontal(); GUI.enabled = !isLocatorSearching; var selectedAddressIndex = EditorGUILayout.Popup(GUIHorizSpacer + "IP Address", previouslySavedAddress, addressesToPresent.ToArray()); if (GUILayout.Button(isLocatorSearching ? "Searching" : "Refresh", GUILayout.Width(buttonWidth_Quarter))) { UpdateXdeStatus(); } GUI.enabled = true; EditorGUILayout.EndHorizontal(); var selectedAddress = addressesToPresent[selectedAddressIndex]; if (curTargetIps != selectedAddress && !isLocatorSearching) BuildDeployPrefs.TargetIPs = selectedAddress; } // Username/Password (and save seeings, if changed) string curUsername = BuildDeployPrefs.DeviceUser; string newUsername = EditorGUILayout.TextField(GUIHorizSpacer + "Username", curUsername); string curPassword = BuildDeployPrefs.DevicePassword; string newPassword = EditorGUILayout.PasswordField(GUIHorizSpacer + "Password", curPassword); bool curFullReinstall = BuildDeployPrefs.FullReinstall; bool newFullReinstall = EditorGUILayout.Toggle( new GUIContent(GUIHorizSpacer + "Uninstall first", "Uninstall application before installing"), curFullReinstall); if ((newUsername != curUsername) || (newPassword != curPassword) || (newFullReinstall != curFullReinstall)) { BuildDeployPrefs.DeviceUser = newUsername; BuildDeployPrefs.DevicePassword = newPassword; BuildDeployPrefs.FullReinstall = newFullReinstall; curUsername = newUsername; curPassword = newPassword; curFullReinstall = newFullReinstall; } // Build list (with install buttons) if (this.builds.Count == 0) { GUILayout.Label(GUIHorizSpacer + "*** No builds found in build directory", EditorStyles.boldLabel); } else { foreach (var fullBuildLocation in this.builds) { int lastBackslashIndex = fullBuildLocation.LastIndexOf("\\"); var directoryDate = Directory.GetLastWriteTime(fullBuildLocation).ToString("yyyy/MM/dd HH:mm:ss"); string packageName = fullBuildLocation.Substring(lastBackslashIndex + 1); EditorGUILayout.BeginHorizontal(); GUILayout.Space(GUISectionOffset + 15); if (GUILayout.Button("Install", GUILayout.Width(120.0f))) { string thisBuildLocation = fullBuildLocation; string[] IPlist = ParseIPList(curTargetIps); EditorApplication.delayCall += () => { InstallAppOnDevicesList(thisBuildLocation, curFullReinstall, IPlist); }; } GUILayout.Space(5); GUILayout.Label(packageName + " (" + directoryDate + ")"); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Separator(); } GUILayout.EndVertical(); GUILayout.Space(GUISectionOffset); // Utilities section GUILayout.BeginVertical(); GUILayout.Label("Utilities"); // Open web portal using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldWebPortalBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Open Device Portal", GUILayout.Width(buttonWidth_Full))) { OpenWebPortalForIPs(curTargetIps); } GUI.enabled = true; } // Launch app.. using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLaunchAppBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Launch Application", GUILayout.Width(buttonWidth_Full))) { // If already running, kill it (button is a toggle) if (IsAppRunning_FirstIPCheck(appName, curTargetIps)) { KillAppOnIPs(curTargetIps); } else { LaunchAppOnIPs(curTargetIps); } } GUI.enabled = true; } // Log file using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLogViewBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("View Log File", GUILayout.Width(buttonWidth_Full))) { OpenLogFileForIPs(curTargetIps); } GUI.enabled = true; } // Uninstall... using (new EditorGUILayout.HorizontalScope()) { GUI.enabled = ShouldLogViewBeEnabled; GUILayout.FlexibleSpace(); if (GUILayout.Button("Uninstall Application", GUILayout.Width(buttonWidth_Full))) { string[] IPlist = ParseIPList(curTargetIps); EditorApplication.delayCall += () => { UninstallAppOnDevicesList(IPlist); }; } GUI.enabled = true; } GUILayout.EndVertical(); } void BuildAndRun(string appName) { // First build SLN if (!BuildDeployTools.BuildSLN(BuildDeployPrefs.BuildDirectory, false)) { return; } // Next, APPX if (!BuildDeployTools.BuildAppxFromSolution( appName, BuildDeployPrefs.MsBuildVersion, BuildDeployPrefs.ForceRebuild, BuildDeployPrefs.BuildConfig, BuildDeployPrefs.BuildDirectory)) { return; } // Next, Install string fullBuildLocation = CalcMostRecentBuild(); string[] IPlist = ParseIPList(BuildDeployPrefs.TargetIPs); InstallAppOnDevicesList(fullBuildLocation, BuildDeployPrefs.FullReinstall, IPlist); } private string CalcMostRecentBuild() { DateTime mostRecent = DateTime.MinValue; string mostRecentBuild = ""; foreach (var fullBuildLocation in this.builds) { DateTime directoryDate = Directory.GetLastWriteTime(fullBuildLocation); if (directoryDate > mostRecent) { mostRecentBuild = fullBuildLocation; mostRecent = directoryDate; } } return mostRecentBuild; } private string CalcPackageFamilyName() { // Find the manifest string[] manifests = Directory.GetFiles(BuildDeployPrefs.AbsoluteBuildDirectory, "Package.appxmanifest", SearchOption.AllDirectories); if (manifests.Length == 0) { Debug.LogError("Unable to find manifest file for build (in path - " + BuildDeployPrefs.AbsoluteBuildDirectory + ")"); return ""; } string manifest = manifests[0]; // Parse it using (XmlTextReader reader = new XmlTextReader(manifest)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name.Equals("identity", StringComparison.OrdinalIgnoreCase)) { while (reader.MoveToNextAttribute()) { if (reader.Name.Equals("name", StringComparison.OrdinalIgnoreCase)) { return reader.Value; } } } break; } } } Debug.LogError("Unable to find PackageFamilyName in manifest file (" + manifest + ")"); return ""; } private void InstallAppOnDevicesList(string buildPath, bool uninstallBeforeInstall, string[] targetList) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } for (int i = 0; i < targetList.Length; i++) { try { bool completedUninstall = false; string IP = FinalizeIP(targetList[i]); if (BuildDeployPrefs.FullReinstall && BuildDeployPortal.IsAppInstalled(packageFamilyName, new BuildDeployPortal.ConnectInfo(IP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword))) { EditorUtility.DisplayProgressBar("Installing on devices", "Uninstall (" + IP + ")", (float)i / (float)targetList.Length); if (!UninstallApp(packageFamilyName, IP)) { Debug.LogError("Uninstall failed - skipping install (" + IP + ")"); continue; } completedUninstall = true; } EditorUtility.DisplayProgressBar("Installing on devices", "Install (" + IP + ")", (float)(i + (completedUninstall ? 0.5f : 0.0f)) / (float)targetList.Length); InstallApp(buildPath, packageFamilyName, IP); } catch (Exception ex) { Debug.LogError(ex.ToString()); } } EditorUtility.ClearProgressBar(); } private bool InstallApp(string buildPath, string appName, string targetDevice) { // Get the appx path FileInfo[] files = (new DirectoryInfo(buildPath)).GetFiles("*.appx"); files = (files.Length == 0) ? (new DirectoryInfo(buildPath)).GetFiles("*.appxbundle") : files; if (files.Length == 0) { Debug.LogError("No APPX found in folder build folder (" + buildPath + ")"); return false; } // Connection info var connectInfo = new BuildDeployPortal.ConnectInfo(targetDevice, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword); // Kick off the install Debug.Log("Installing build on: " + targetDevice); return BuildDeployPortal.InstallApp(files[0].FullName, connectInfo); } private void UninstallAppOnDevicesList(string[] targetList) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } try { for (int i = 0; i < targetList.Length; i++) { string IP = FinalizeIP(targetList[i]); EditorUtility.DisplayProgressBar("Uninstalling application", "Uninstall (" + IP + ")", (float)i / (float)targetList.Length); UninstallApp(packageFamilyName, IP); } } catch (Exception ex) { Debug.LogError(ex.ToString()); } EditorUtility.ClearProgressBar(); } private bool UninstallApp(string packageFamilyName, string targetDevice) { // Connection info var connectInfo = new BuildDeployPortal.ConnectInfo(targetDevice, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword); // Kick off the install Debug.Log("Uninstall build: " + targetDevice); return BuildDeployPortal.UninstallApp(packageFamilyName, connectInfo); } private void UpdateBuilds() { this.builds.Clear(); try { List<string> appPackageDirectories = new List<string>(); string[] buildList = Directory.GetDirectories(BuildDeployPrefs.AbsoluteBuildDirectory); foreach (string appBuild in buildList) { string appPackageDirectory = appBuild + @"\AppPackages"; if (Directory.Exists(appPackageDirectory)) { appPackageDirectories.AddRange(Directory.GetDirectories(appPackageDirectory)); } } IEnumerable<string> selectedDirectories = from string directory in appPackageDirectories orderby Directory.GetLastWriteTime(directory) descending select Path.GetFullPath(directory); this.builds.AddRange(selectedDirectories); } catch (DirectoryNotFoundException) { } timeLastUpdatedBuilds = Time.realtimeSinceStartup; } void Update() { if ((Time.realtimeSinceStartup - timeLastUpdatedBuilds) > UpdateBuildsPeriod) { UpdateBuilds(); } } public static string[] ParseIPList(string IPs) { string[] IPlist = { }; if (IPs == null || IPs == "") return IPlist; string[] separators = { ";", " " }; IPlist = IPs.Split(separators, System.StringSplitOptions.RemoveEmptyEntries); return IPlist; } static string FinalizeIP(string ip) { // If it's local, add the port if (ip == "127.0.0.1") { ip += ":10080"; } return ip; } public static void OpenWebPortalForIPs(string IPs) { string[] ipList = ParseIPList(IPs); for (int i = 0; i < ipList.Length; i++) { string url = string.Format("http://{0}", FinalizeIP(ipList[i])); // Run the process System.Diagnostics.Process.Start(url); } } bool IsAppRunning_FirstIPCheck(string appName, string targetIPs) { // Just pick the first one and use it... string[] IPlist = ParseIPList(targetIPs); if (IPlist.Length > 0) { string targetIP = FinalizeIP(IPlist[0]); return BuildDeployPortal.IsAppRunning( appName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } return false; } void LaunchAppOnIPs(string targetIPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] IPlist = ParseIPList(targetIPs); for (int i = 0; i < IPlist.Length; i++) { string targetIP = FinalizeIP(IPlist[i]); Debug.Log("Launch app on: " + targetIP); BuildDeployPortal.LaunchApp( packageFamilyName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } void KillAppOnIPs(string targetIPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] IPlist = ParseIPList(targetIPs); for (int i = 0; i < IPlist.Length; i++) { string targetIP = FinalizeIP(IPlist[i]); Debug.Log("Kill app on: " + targetIP); BuildDeployPortal.KillApp( packageFamilyName, new BuildDeployPortal.ConnectInfo(targetIP, BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } public void OpenLogFileForIPs(string IPs) { string packageFamilyName = CalcPackageFamilyName(); if (string.IsNullOrEmpty(packageFamilyName)) { return; } string[] ipList = ParseIPList(IPs); for (int i = 0; i < ipList.Length; i++) { // Use the Device Portal REST API BuildDeployPortal.DeviceLogFile_View( packageFamilyName, new BuildDeployPortal.ConnectInfo(FinalizeIP(ipList[i]), BuildDeployPrefs.DeviceUser, BuildDeployPrefs.DevicePassword)); } } } }
//----------------------------------------------------------------------- // <copyright file="RoleApi.cs" company="LoginRadius"> // Created by LoginRadius Development Team // Copyright 2019 LoginRadius Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using LoginRadiusSDK.V2.Common; using System.Threading.Tasks; using LoginRadiusSDK.V2.Util; using LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects; using LoginRadiusSDK.V2.Models.RequestModels; using LoginRadiusSDK.V2.Models.ResponseModels; using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile.Objects; namespace LoginRadiusSDK.V2.Api.Account { public class RoleApi : LoginRadiusResource { /// <summary> /// API is used to retrieve all the assigned roles of a particular User. /// </summary> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Complete Roles data</returns> /// 18.6 public async Task<ApiResponse<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.AccountRolesModel>> GetRolesByUid(string uid) { if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/role"; return await ConfigureAndExecute<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.AccountRolesModel>(HttpMethod.GET, resourcePath, queryParameters, null); } /// <summary> /// This API is used to assign your desired roles to a given user. /// </summary> /// <param name="accountRolesModel">Model Class containing Definition of payload for Create Role API</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Complete Roles data</returns> /// 18.7 public async Task<ApiResponse<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.AccountRolesModel>> AssignRolesByUid(LoginRadiusSDK.V2.Models.RequestModels.AccountRolesModel accountRolesModel, string uid) { if (accountRolesModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accountRolesModel)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/role"; return await ConfigureAndExecute<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.AccountRolesModel>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(accountRolesModel)); } /// <summary> /// This API is used to unassign roles from a user. /// </summary> /// <param name="accountRolesModel">Model Class containing Definition of payload for Create Role API</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Delete Request</returns> /// 18.8 public async Task<ApiResponse<DeleteResponse>> UnassignRolesByUid(LoginRadiusSDK.V2.Models.RequestModels.AccountRolesModel accountRolesModel, string uid) { if (accountRolesModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accountRolesModel)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/role"; return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(accountRolesModel)); } /// <summary> /// This API Gets the contexts that have been configured and the associated roles and permissions. /// </summary> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Complete user RoleContext data</returns> /// 18.9 public async Task<ApiResponse<ListReturn<RoleContext>>> GetRoleContextByUid(string uid) { if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/rolecontext"; return await ConfigureAndExecute<ListReturn<RoleContext>>(HttpMethod.GET, resourcePath, queryParameters, null); } /// <summary> /// The API is used to retrieve role context by the context name. /// </summary> /// <param name="contextName">Name of context</param> /// <returns>Complete user RoleContext data</returns> /// 18.10 public async Task<ApiResponse<ListReturn<RoleContextResponseModel>>> GetRoleContextByContextName(string contextName) { if (string.IsNullOrWhiteSpace(contextName)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(contextName)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/rolecontext/{contextName}"; return await ConfigureAndExecute<ListReturn<RoleContextResponseModel>>(HttpMethod.GET, resourcePath, queryParameters, null); } /// <summary> /// This API creates a Context with a set of Roles /// </summary> /// <param name="accountRoleContextModel">Model Class containing Definition of RoleContext payload</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Complete user RoleContext data</returns> /// 18.11 public async Task<ApiResponse<ListReturn<RoleContext>>> UpdateRoleContextByUid(AccountRoleContextModel accountRoleContextModel, string uid) { if (accountRoleContextModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accountRoleContextModel)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/rolecontext"; return await ConfigureAndExecute<ListReturn<RoleContext>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(accountRoleContextModel)); } /// <summary> /// This API Deletes the specified Role Context /// </summary> /// <param name="contextName">Name of context</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Delete Request</returns> /// 18.12 public async Task<ApiResponse<DeleteResponse>> DeleteRoleContextByUid(string contextName, string uid) { if (string.IsNullOrWhiteSpace(contextName)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(contextName)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/rolecontext/{contextName}"; return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null); } /// <summary> /// This API Deletes the specified Role from a Context. /// </summary> /// <param name="contextName">Name of context</param> /// <param name="roleContextRemoveRoleModel">Model Class containing Definition of payload for RoleContextRemoveRole API</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Delete Request</returns> /// 18.13 public async Task<ApiResponse<DeleteResponse>> DeleteRolesFromRoleContextByUid(string contextName, RoleContextRemoveRoleModel roleContextRemoveRoleModel, string uid) { if (string.IsNullOrWhiteSpace(contextName)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(contextName)); } if (roleContextRemoveRoleModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(roleContextRemoveRoleModel)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/rolecontext/{contextName}/role"; return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(roleContextRemoveRoleModel)); } /// <summary> /// This API Deletes Additional Permissions from Context. /// </summary> /// <param name="contextName">Name of context</param> /// <param name="roleContextAdditionalPermissionRemoveRoleModel">Model Class containing Definition of payload for RoleContextAdditionalPermissionRemoveRole API</param> /// <param name="uid">UID, the unified identifier for each user account</param> /// <returns>Response containing Definition of Delete Request</returns> /// 18.14 public async Task<ApiResponse<DeleteResponse>> DeleteAdditionalPermissionFromRoleContextByUid(string contextName, RoleContextAdditionalPermissionRemoveRoleModel roleContextAdditionalPermissionRemoveRoleModel, string uid) { if (string.IsNullOrWhiteSpace(contextName)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(contextName)); } if (roleContextAdditionalPermissionRemoveRoleModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(roleContextAdditionalPermissionRemoveRoleModel)); } if (string.IsNullOrWhiteSpace(uid)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(uid)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/account/{uid}/rolecontext/{contextName}/additionalpermission"; return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(roleContextAdditionalPermissionRemoveRoleModel)); } /// <summary> /// This API retrieves the complete list of created roles with permissions of your app. /// </summary> /// <returns>Complete user Roles List data</returns> /// 41.1 public async Task<ApiResponse<ListData<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>>> GetRolesList() { var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = "identity/v2/manage/role"; return await ConfigureAndExecute<ListData<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>>(HttpMethod.GET, resourcePath, queryParameters, null); } /// <summary> /// This API creates a role with permissions. /// </summary> /// <param name="rolesModel">Model Class containing Definition of payload for Roles API</param> /// <returns>Complete user Roles data</returns> /// 41.2 public async Task<ApiResponse<ListData<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>>> CreateRoles(RolesModel rolesModel) { if (rolesModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(rolesModel)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = "identity/v2/manage/role"; return await ConfigureAndExecute<ListData<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(rolesModel)); } /// <summary> /// This API is used to delete the role. /// </summary> /// <param name="role">Created RoleName</param> /// <returns>Response containing Definition of Delete Request</returns> /// 41.3 public async Task<ApiResponse<DeleteResponse>> DeleteRole(string role) { if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(role)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/role/{role}"; return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null); } /// <summary> /// This API is used to add permissions to a given role. /// </summary> /// <param name="permissionsModel">Model Class containing Definition for PermissionsModel Property</param> /// <param name="role">Created RoleName</param> /// <returns>Response containing Definition of Complete role data</returns> /// 41.4 public async Task<ApiResponse<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>> AddRolePermissions(PermissionsModel permissionsModel, string role) { if (permissionsModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(permissionsModel)); } if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(role)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/role/{role}/permission"; return await ConfigureAndExecute<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(permissionsModel)); } /// <summary> /// API is used to remove permissions from a role. /// </summary> /// <param name="permissionsModel">Model Class containing Definition for PermissionsModel Property</param> /// <param name="role">Created RoleName</param> /// <returns>Response containing Definition of Complete role data</returns> /// 41.5 public async Task<ApiResponse<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>> RemoveRolePermissions(PermissionsModel permissionsModel, string role) { if (permissionsModel == null) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(permissionsModel)); } if (string.IsNullOrWhiteSpace(role)) { throw new ArgumentException(BaseConstants.ValidationMessage, nameof(role)); } var queryParameters = new QueryParameters { { "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }, { "apiSecret", ConfigDictionary[LRConfigConstants.LoginRadiusApiSecret] } }; var resourcePath = $"identity/v2/manage/role/{role}/permission"; return await ConfigureAndExecute<LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects.RoleModel>(HttpMethod.DELETE, resourcePath, queryParameters, ConvertToJson(permissionsModel)); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the route53-2013-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Route53.Model { /// <summary> /// A complex type that contains information about the current resource record set. /// </summary> public partial class ResourceRecordSet { private string _name; private RRType _type; private string _setIdentifier; private long? _weight; private ResourceRecordSetRegion _region; private GeoLocation _geoLocation; private ResourceRecordSetFailover _failover; private long? _ttl; private List<ResourceRecord> _resourceRecords = new List<ResourceRecord>(); private AliasTarget _aliasTarget; private string _healthCheckId; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public ResourceRecordSet() { } /// <summary> /// Instantiates ResourceRecordSet with the parameterized properties /// </summary> /// <param name="name">The domain name of the current resource record set.</param> /// <param name="type">The type of the current resource record set.</param> public ResourceRecordSet(string name, RRType type) { _name = name; _type = type; } /// <summary> /// Gets and sets the property Name. /// <para> /// The domain name of the current resource record set. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Type. /// <para> /// The type of the current resource record set. /// </para> /// </summary> public RRType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } /// <summary> /// Gets and sets the property SetIdentifier. /// <para> /// <i>Weighted, Latency, Geo, and Failover resource record sets only:</i> An identifier /// that differentiates among multiple resource record sets that have the same combination /// of DNS name and type. /// </para> /// </summary> public string SetIdentifier { get { return this._setIdentifier; } set { this._setIdentifier = value; } } // Check to see if SetIdentifier property is set internal bool IsSetSetIdentifier() { return this._setIdentifier != null; } /// <summary> /// Gets and sets the property Weight. /// <para> /// <i>Weighted resource record sets only:</i> Among resource record sets that have the /// same combination of DNS name and type, a value that determines what portion of traffic /// for the current resource record set is routed to the associated location. /// </para> /// </summary> public long Weight { get { return this._weight.GetValueOrDefault(); } set { this._weight = value; } } // Check to see if Weight property is set internal bool IsSetWeight() { return this._weight.HasValue; } /// <summary> /// Gets and sets the property Region. /// <para> /// <i>Latency-based resource record sets only:</i> Among resource record sets that have /// the same combination of DNS name and type, a value that specifies the AWS region for /// the current resource record set. /// </para> /// </summary> public ResourceRecordSetRegion Region { get { return this._region; } set { this._region = value; } } // Check to see if Region property is set internal bool IsSetRegion() { return this._region != null; } /// <summary> /// Gets and sets the property GeoLocation. /// <para> /// <i>Geo location resource record sets only:</i> Among resource record sets that have /// the same combination of DNS name and type, a value that specifies the geo location /// for the current resource record set. /// </para> /// </summary> public GeoLocation GeoLocation { get { return this._geoLocation; } set { this._geoLocation = value; } } // Check to see if GeoLocation property is set internal bool IsSetGeoLocation() { return this._geoLocation != null; } /// <summary> /// Gets and sets the property Failover. /// <para> /// <i>Failover resource record sets only:</i> Among resource record sets that have the /// same combination of DNS name and type, a value that indicates whether the current /// resource record set is a primary or secondary resource record set. A failover set /// may contain at most one resource record set marked as primary and one resource record /// set marked as secondary. A resource record set marked as primary will be returned /// if any of the following are true: (1) an associated health check is passing, (2) if /// the resource record set is an alias with the evaluate target health and at least one /// target resource record set is healthy, (3) both the primary and secondary resource /// record set are failing health checks or (4) there is no secondary resource record /// set. A secondary resource record set will be returned if: (1) the primary is failing /// a health check and either the secondary is passing a health check or has no associated /// health check, or (2) there is no primary resource record set. /// </para> /// /// <para> /// Valid values: <code>PRIMARY</code> | <code>SECONDARY</code> /// </para> /// </summary> public ResourceRecordSetFailover Failover { get { return this._failover; } set { this._failover = value; } } // Check to see if Failover property is set internal bool IsSetFailover() { return this._failover != null; } /// <summary> /// Gets and sets the property TTL. /// <para> /// The cache time to live for the current resource record set. /// </para> /// </summary> public long TTL { get { return this._ttl.GetValueOrDefault(); } set { this._ttl = value; } } // Check to see if TTL property is set internal bool IsSetTTL() { return this._ttl.HasValue; } /// <summary> /// Gets and sets the property ResourceRecords. /// <para> /// A complex type that contains the resource records for the current resource record /// set. /// </para> /// </summary> public List<ResourceRecord> ResourceRecords { get { return this._resourceRecords; } set { this._resourceRecords = value; } } // Check to see if ResourceRecords property is set internal bool IsSetResourceRecords() { return this._resourceRecords != null && this._resourceRecords.Count > 0; } /// <summary> /// Gets and sets the property AliasTarget. /// <para> /// <i>Alias resource record sets only:</i> Information about the AWS resource to which /// you are redirecting traffic. /// </para> /// </summary> public AliasTarget AliasTarget { get { return this._aliasTarget; } set { this._aliasTarget = value; } } // Check to see if AliasTarget property is set internal bool IsSetAliasTarget() { return this._aliasTarget != null; } /// <summary> /// Gets and sets the property HealthCheckId. /// <para> /// <i>Health Check resource record sets only, not required for alias resource record /// sets:</i> An identifier that is used to identify health check associated with the /// resource record set. /// </para> /// </summary> public string HealthCheckId { get { return this._healthCheckId; } set { this._healthCheckId = value; } } // Check to see if HealthCheckId property is set internal bool IsSetHealthCheckId() { return this._healthCheckId != null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.BuildEngine { public partial class BuildItem { public BuildItem(string itemName, Microsoft.Build.Framework.ITaskItem taskItem) { } public BuildItem(string itemName, string itemInclude) { } public string Condition { get { throw null; } set { } } public int CustomMetadataCount { get { throw null; } } public System.Collections.ICollection CustomMetadataNames { get { throw null; } } public string Exclude { get { throw null; } set { } } public string FinalItemSpec { get { throw null; } } public string Include { get { throw null; } set { } } public bool IsImported { get { throw null; } } public int MetadataCount { get { throw null; } } public System.Collections.ICollection MetadataNames { get { throw null; } } public string Name { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildItem Clone() { throw null; } public void CopyCustomMetadataTo(Microsoft.Build.BuildEngine.BuildItem destinationItem) { } public string GetEvaluatedMetadata(string metadataName) { throw null; } public string GetMetadata(string metadataName) { throw null; } public bool HasMetadata(string metadataName) { throw null; } public void RemoveMetadata(string metadataName) { } public void SetMetadata(string metadataName, string metadataValue) { } public void SetMetadata(string metadataName, string metadataValue, bool treatMetadataValueAsLiteral) { } } public partial class BuildItemGroup : System.Collections.IEnumerable { public BuildItemGroup() { } public string Condition { get { throw null; } set { } } public int Count { get { throw null; } } public bool IsImported { get { throw null; } } public Microsoft.Build.BuildEngine.BuildItem this[int index] { get { throw null; } } public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude) { throw null; } public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude, bool treatItemIncludeAsLiteral) { throw null; } public void Clear() { } public Microsoft.Build.BuildEngine.BuildItemGroup Clone(bool deepClone) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void RemoveItem(Microsoft.Build.BuildEngine.BuildItem itemToRemove) { } public void RemoveItemAt(int index) { } public Microsoft.Build.BuildEngine.BuildItem[] ToArray() { throw null; } } public partial class BuildItemGroupCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal BuildItemGroupCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } } public partial class BuildProperty { public BuildProperty(string propertyName, string propertyValue) { } public string Condition { get { throw null; } set { } } public string FinalValue { get { throw null; } } public bool IsImported { get { throw null; } } public string Name { get { throw null; } } public string Value { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildProperty Clone(bool deepClone) { throw null; } public static explicit operator string (Microsoft.Build.BuildEngine.BuildProperty propertyToCast) { throw null; } public override string ToString() { throw null; } } public partial class BuildPropertyGroup : System.Collections.IEnumerable { public BuildPropertyGroup() { } public BuildPropertyGroup(Microsoft.Build.BuildEngine.Project parentProject) { } public string Condition { get { throw null; } set { } } public int Count { get { throw null; } } public bool IsImported { get { throw null; } } public Microsoft.Build.BuildEngine.BuildProperty this[string propertyName] { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildProperty AddNewProperty(string propertyName, string propertyValue) { throw null; } public Microsoft.Build.BuildEngine.BuildProperty AddNewProperty(string propertyName, string propertyValue, bool treatPropertyValueAsLiteral) { throw null; } public void Clear() { } public Microsoft.Build.BuildEngine.BuildPropertyGroup Clone(bool deepClone) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void RemoveProperty(Microsoft.Build.BuildEngine.BuildProperty property) { } public void RemoveProperty(string propertyName) { } public void SetImportedPropertyGroupCondition(string condition) { } public void SetProperty(string propertyName, string propertyValue) { } public void SetProperty(string propertyName, string propertyValue, bool treatPropertyValueAsLiteral) { } } public partial class BuildPropertyGroupCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal BuildPropertyGroupCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } } [System.FlagsAttribute] public enum BuildSettings { DoNotResetPreviouslyBuiltTargets = 1, None = 0, } public partial class BuildTask { internal BuildTask() { } public string Condition { get { throw null; } set { } } public bool ContinueOnError { get { throw null; } set { } } public Microsoft.Build.Framework.ITaskHost HostObject { get { throw null; } set { } } public string Name { get { throw null; } } public System.Type Type { get { throw null; } } public void AddOutputItem(string taskParameter, string itemName) { } public void AddOutputProperty(string taskParameter, string propertyName) { } public bool Execute() { throw null; } public string[] GetParameterNames() { throw null; } public string GetParameterValue(string attributeName) { throw null; } public void SetParameterValue(string parameterName, string parameterValue) { } public void SetParameterValue(string parameterName, string parameterValue, bool treatParameterValueAsLiteral) { } } public delegate void ColorResetter(); public delegate void ColorSetter(System.ConsoleColor color); public partial class ConfigurableForwardingLogger : Microsoft.Build.Framework.IForwardingLogger, Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger { public ConfigurableForwardingLogger() { } public Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get { throw null; } set { } } public int NodeId { get { throw null; } set { } } public string Parameters { get { throw null; } set { } } public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } } protected virtual void ForwardToCentralLogger(Microsoft.Build.Framework.BuildEventArgs e) { } public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { } public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { } public virtual void Shutdown() { } } public partial class ConsoleLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger { public ConsoleLogger() { } public ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity verbosity) { } public ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity verbosity, Microsoft.Build.BuildEngine.WriteHandler write, Microsoft.Build.BuildEngine.ColorSetter colorSet, Microsoft.Build.BuildEngine.ColorResetter colorReset) { } public string Parameters { get { throw null; } set { } } public bool ShowSummary { get { throw null; } set { } } public bool SkipProjectStartedText { get { throw null; } set { } } public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } } protected Microsoft.Build.BuildEngine.WriteHandler WriteHandler { get { throw null; } set { } } public void ApplyParameter(string parameterName, string parameterValue) { } public void BuildFinishedHandler(object sender, Microsoft.Build.Framework.BuildFinishedEventArgs e) { } public void BuildStartedHandler(object sender, Microsoft.Build.Framework.BuildStartedEventArgs e) { } public void CustomEventHandler(object sender, Microsoft.Build.Framework.CustomBuildEventArgs e) { } public void ErrorHandler(object sender, Microsoft.Build.Framework.BuildErrorEventArgs e) { } public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { } public virtual void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { } public void MessageHandler(object sender, Microsoft.Build.Framework.BuildMessageEventArgs e) { } public void ProjectFinishedHandler(object sender, Microsoft.Build.Framework.ProjectFinishedEventArgs e) { } public void ProjectStartedHandler(object sender, Microsoft.Build.Framework.ProjectStartedEventArgs e) { } public virtual void Shutdown() { } public void TargetFinishedHandler(object sender, Microsoft.Build.Framework.TargetFinishedEventArgs e) { } public void TargetStartedHandler(object sender, Microsoft.Build.Framework.TargetStartedEventArgs e) { } public void TaskFinishedHandler(object sender, Microsoft.Build.Framework.TaskFinishedEventArgs e) { } public void TaskStartedHandler(object sender, Microsoft.Build.Framework.TaskStartedEventArgs e) { } public void WarningHandler(object sender, Microsoft.Build.Framework.BuildWarningEventArgs e) { } } public partial class DistributedFileLogger : Microsoft.Build.Framework.IForwardingLogger, Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger { public DistributedFileLogger() { } public Microsoft.Build.Framework.IEventRedirector BuildEventRedirector { get { throw null; } set { } } public int NodeId { get { throw null; } set { } } public string Parameters { get { throw null; } set { } } public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } } public void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { } public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { } public void Shutdown() { } } [System.ObsoleteAttribute("This class has been deprecated. Please use Microsoft.Build.Evaluation.ProjectCollection from the Microsoft.Build assembly instead.")] public partial class Engine { public Engine() { } public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties) { } public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations) { } public Engine(Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations, int numberOfCpus, string localNodeProviderParameters) { } public Engine(Microsoft.Build.BuildEngine.ToolsetDefinitionLocations locations) { } [System.ObsoleteAttribute("If you were simply passing in the .NET Framework location as the BinPath, just change to the parameterless Engine() constructor. Otherwise, you can define custom toolsets in the registry or config file, or by adding elements to the Engine's ToolsetCollection. Then use either the Engine() or Engine(ToolsetLocations) constructor instead.")] public Engine(string binPath) { } [System.ObsoleteAttribute("Avoid setting BinPath. If you were simply passing in the .NET Framework location as the BinPath, no other action is necessary. Otherwise, define Toolsets instead in the registry or config file, or by adding elements to the Engine's ToolsetCollection, in order to use a custom BinPath.")] public string BinPath { get { throw null; } set { } } public bool BuildEnabled { get { throw null; } set { } } public string DefaultToolsVersion { get { throw null; } set { } } public static Microsoft.Build.BuildEngine.Engine GlobalEngine { get { throw null; } } public Microsoft.Build.BuildEngine.BuildPropertyGroup GlobalProperties { get { throw null; } set { } } public bool IsBuilding { get { throw null; } } public bool OnlyLogCriticalEvents { get { throw null; } set { } } public Microsoft.Build.BuildEngine.ToolsetCollection Toolsets { get { throw null; } } public static System.Version Version { get { throw null; } } public bool BuildProject(Microsoft.Build.BuildEngine.Project project) { throw null; } public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string targetName) { throw null; } public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames) { throw null; } public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames, System.Collections.IDictionary targetOutputs) { throw null; } public bool BuildProject(Microsoft.Build.BuildEngine.Project project, string[] targetNames, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; } public bool BuildProjectFile(string projectFile) { throw null; } public bool BuildProjectFile(string projectFile, string targetName) { throw null; } public bool BuildProjectFile(string projectFile, string[] targetNames) { throw null; } public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties) { throw null; } public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs) { throw null; } public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; } public bool BuildProjectFile(string projectFile, string[] targetNames, Microsoft.Build.BuildEngine.BuildPropertyGroup globalProperties, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags, string toolsVersion) { throw null; } public bool BuildProjectFiles(string[] projectFiles, string[][] targetNamesPerProject, Microsoft.Build.BuildEngine.BuildPropertyGroup[] globalPropertiesPerProject, System.Collections.IDictionary[] targetOutputsPerProject, Microsoft.Build.BuildEngine.BuildSettings buildFlags, string[] toolsVersions) { throw null; } public Microsoft.Build.BuildEngine.Project CreateNewProject() { throw null; } public Microsoft.Build.BuildEngine.Project GetLoadedProject(string projectFullFileName) { throw null; } public void RegisterDistributedLogger(Microsoft.Build.Framework.ILogger centralLogger, Microsoft.Build.BuildEngine.LoggerDescription forwardingLogger) { } public void RegisterLogger(Microsoft.Build.Framework.ILogger logger) { } public void Shutdown() { } public void UnloadAllProjects() { } public void UnloadProject(Microsoft.Build.BuildEngine.Project project) { } public void UnregisterAllLoggers() { } } public partial class FileLogger : Microsoft.Build.BuildEngine.ConsoleLogger { public FileLogger() { } public override void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { } public override void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int nodeCount) { } public override void Shutdown() { } } public partial class Import { internal Import() { } public string Condition { get { throw null; } set { } } public string EvaluatedProjectPath { get { throw null; } } public bool IsImported { get { throw null; } } public string ProjectPath { get { throw null; } set { } } } public partial class ImportCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal ImportCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void AddNewImport(string projectFile, string condition) { } public void CopyTo(Microsoft.Build.BuildEngine.Import[] array, int index) { } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void RemoveImport(Microsoft.Build.BuildEngine.Import importToRemove) { } } public sealed partial class InternalLoggerException : System.Exception { public InternalLoggerException() { } public InternalLoggerException(string message) { } public InternalLoggerException(string message, System.Exception innerException) { } public Microsoft.Build.Framework.BuildEventArgs BuildEventArgs { get { throw null; } } public string ErrorCode { get { throw null; } } public string HelpKeyword { get { throw null; } } public bool InitializationException { get { throw null; } } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public sealed partial class InvalidProjectFileException : System.Exception { public InvalidProjectFileException() { } public InvalidProjectFileException(string message) { } public InvalidProjectFileException(string message, System.Exception innerException) { } public InvalidProjectFileException(string projectFile, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, string errorSubcategory, string errorCode, string helpKeyword) { } public InvalidProjectFileException(System.Xml.XmlNode xmlNode, string message, string errorSubcategory, string errorCode, string helpKeyword) { } public string BaseMessage { get { throw null; } } public int ColumnNumber { get { throw null; } } public int EndColumnNumber { get { throw null; } } public int EndLineNumber { get { throw null; } } public string ErrorCode { get { throw null; } } public string ErrorSubcategory { get { throw null; } } public string HelpKeyword { get { throw null; } } public int LineNumber { get { throw null; } } public override string Message { get { throw null; } } public string ProjectFile { get { throw null; } } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class InvalidToolsetDefinitionException : System.Exception { public InvalidToolsetDefinitionException() { } protected InvalidToolsetDefinitionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public InvalidToolsetDefinitionException(string message) { } public InvalidToolsetDefinitionException(string message, System.Exception innerException) { } public InvalidToolsetDefinitionException(string message, string errorCode) { } public InvalidToolsetDefinitionException(string message, string errorCode, System.Exception innerException) { } public string ErrorCode { get { throw null; } } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class LocalNode { internal LocalNode() { } public static void StartLocalNodeServer(int nodeNumber) { } } public partial class LoggerDescription { public LoggerDescription(string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, Microsoft.Build.Framework.LoggerVerbosity verbosity) { } public string LoggerSwitchParameters { get { throw null; } } public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } } } [System.ObsoleteAttribute("This class has been deprecated. Please use Microsoft.Build.Evaluation.Project from the Microsoft.Build assembly instead.")] public partial class Project { public Project() { } public Project(Microsoft.Build.BuildEngine.Engine engine) { } public Project(Microsoft.Build.BuildEngine.Engine engine, string toolsVersion) { } public bool BuildEnabled { get { throw null; } set { } } public string DefaultTargets { get { throw null; } set { } } public string DefaultToolsVersion { get { throw null; } set { } } public System.Text.Encoding Encoding { get { throw null; } } public Microsoft.Build.BuildEngine.BuildItemGroup EvaluatedItems { get { throw null; } } public Microsoft.Build.BuildEngine.BuildItemGroup EvaluatedItemsIgnoringCondition { get { throw null; } } public Microsoft.Build.BuildEngine.BuildPropertyGroup EvaluatedProperties { get { throw null; } } public string FullFileName { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildPropertyGroup GlobalProperties { get { throw null; } set { } } public bool HasToolsVersionAttribute { get { throw null; } } public Microsoft.Build.BuildEngine.ImportCollection Imports { get { throw null; } } public string InitialTargets { get { throw null; } set { } } public bool IsDirty { get { throw null; } } public bool IsValidated { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildItemGroupCollection ItemGroups { get { throw null; } } public Microsoft.Build.BuildEngine.Engine ParentEngine { get { throw null; } } public Microsoft.Build.BuildEngine.BuildPropertyGroupCollection PropertyGroups { get { throw null; } } public string SchemaFile { get { throw null; } set { } } public Microsoft.Build.BuildEngine.TargetCollection Targets { get { throw null; } } public System.DateTime TimeOfLastDirty { get { throw null; } } public string ToolsVersion { get { throw null; } } public Microsoft.Build.BuildEngine.UsingTaskCollection UsingTasks { get { throw null; } } public string Xml { get { throw null; } } public void AddNewImport(string projectFile, string condition) { } public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude) { throw null; } public Microsoft.Build.BuildEngine.BuildItem AddNewItem(string itemName, string itemInclude, bool treatItemIncludeAsLiteral) { throw null; } public Microsoft.Build.BuildEngine.BuildItemGroup AddNewItemGroup() { throw null; } public Microsoft.Build.BuildEngine.BuildPropertyGroup AddNewPropertyGroup(bool insertAtEndOfProject) { throw null; } public void AddNewUsingTaskFromAssemblyFile(string taskName, string assemblyFile) { } public void AddNewUsingTaskFromAssemblyName(string taskName, string assemblyName) { } public bool Build() { throw null; } public bool Build(string targetName) { throw null; } public bool Build(string[] targetNames) { throw null; } public bool Build(string[] targetNames, System.Collections.IDictionary targetOutputs) { throw null; } public bool Build(string[] targetNames, System.Collections.IDictionary targetOutputs, Microsoft.Build.BuildEngine.BuildSettings buildFlags) { throw null; } public string[] GetConditionedPropertyValues(string propertyName) { throw null; } public Microsoft.Build.BuildEngine.BuildItemGroup GetEvaluatedItemsByName(string itemName) { throw null; } public Microsoft.Build.BuildEngine.BuildItemGroup GetEvaluatedItemsByNameIgnoringCondition(string itemName) { throw null; } public string GetEvaluatedProperty(string propertyName) { throw null; } public string GetProjectExtensions(string id) { throw null; } public void Load(System.IO.TextReader textReader) { } public void Load(System.IO.TextReader textReader, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { } public void Load(string projectFileName) { } public void Load(string projectFileName, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { } public void LoadXml(string projectXml) { } public void LoadXml(string projectXml, Microsoft.Build.BuildEngine.ProjectLoadSettings projectLoadSettings) { } public void MarkProjectAsDirty() { } public void RemoveAllItemGroups() { } public void RemoveAllPropertyGroups() { } public void RemoveImportedPropertyGroup(Microsoft.Build.BuildEngine.BuildPropertyGroup propertyGroupToRemove) { } public void RemoveItem(Microsoft.Build.BuildEngine.BuildItem itemToRemove) { } public void RemoveItemGroup(Microsoft.Build.BuildEngine.BuildItemGroup itemGroupToRemove) { } public void RemoveItemGroupsWithMatchingCondition(string matchCondition) { } public void RemoveItemsByName(string itemName) { } public void RemovePropertyGroup(Microsoft.Build.BuildEngine.BuildPropertyGroup propertyGroupToRemove) { } public void RemovePropertyGroupsWithMatchingCondition(string matchCondition) { } public void RemovePropertyGroupsWithMatchingCondition(string matchCondition, bool includeImportedPropertyGroups) { } public void ResetBuildStatus() { } public void Save(System.IO.TextWriter textWriter) { } public void Save(string projectFileName) { } public void Save(string projectFileName, System.Text.Encoding encoding) { } public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importProject) { } public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importedProject, Microsoft.Build.BuildEngine.PropertyPosition position) { } public void SetImportedProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.Project importedProject, Microsoft.Build.BuildEngine.PropertyPosition position, bool treatPropertyValueAsLiteral) { } public void SetProjectExtensions(string id, string content) { } public void SetProperty(string propertyName, string propertyValue) { } public void SetProperty(string propertyName, string propertyValue, string condition) { } public void SetProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.PropertyPosition position) { } public void SetProperty(string propertyName, string propertyValue, string condition, Microsoft.Build.BuildEngine.PropertyPosition position, bool treatPropertyValueAsLiteral) { } } [System.FlagsAttribute] public enum ProjectLoadSettings { IgnoreMissingImports = 1, None = 0, } public enum PropertyPosition { UseExistingOrCreateAfterLastImport = 1, UseExistingOrCreateAfterLastPropertyGroup = 0, } public sealed partial class RemoteErrorException : System.Exception { internal RemoteErrorException() { } [System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter=true)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public static partial class SolutionWrapperProject { public static string Generate(string solutionPath, string toolsVersionOverride, Microsoft.Build.Framework.BuildEventContext projectBuildEventContext) { throw null; } } public partial class Target : System.Collections.IEnumerable { internal Target() { } public string Condition { get { throw null; } set { } } public string DependsOnTargets { get { throw null; } set { } } public string Inputs { get { throw null; } set { } } public bool IsImported { get { throw null; } } public string Name { get { throw null; } } public string Outputs { get { throw null; } set { } } public Microsoft.Build.BuildEngine.BuildTask AddNewTask(string taskName) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void RemoveTask(Microsoft.Build.BuildEngine.BuildTask taskElement) { } } public partial class TargetCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal TargetCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public Microsoft.Build.BuildEngine.Target this[string index] { get { throw null; } } public object SyncRoot { get { throw null; } } public Microsoft.Build.BuildEngine.Target AddNewTarget(string targetName) { throw null; } public void CopyTo(System.Array array, int index) { } public bool Exists(string targetName) { throw null; } public System.Collections.IEnumerator GetEnumerator() { throw null; } public void RemoveTarget(Microsoft.Build.BuildEngine.Target targetToRemove) { } } public partial class Toolset { public Toolset(string toolsVersion, string toolsPath) { } public Toolset(string toolsVersion, string toolsPath, Microsoft.Build.BuildEngine.BuildPropertyGroup buildProperties) { } public Microsoft.Build.BuildEngine.BuildPropertyGroup BuildProperties { get { throw null; } } public string ToolsPath { get { throw null; } } public string ToolsVersion { get { throw null; } } public Microsoft.Build.BuildEngine.Toolset Clone() { throw null; } } public partial class ToolsetCollection : System.Collections.Generic.ICollection<Microsoft.Build.BuildEngine.Toolset>, System.Collections.Generic.IEnumerable<Microsoft.Build.BuildEngine.Toolset>, System.Collections.IEnumerable { internal ToolsetCollection() { } public int Count { get { throw null; } } public bool IsReadOnly { get { throw null; } } public Microsoft.Build.BuildEngine.Toolset this[string toolsVersion] { get { throw null; } } public System.Collections.Generic.IEnumerable<string> ToolsVersions { get { throw null; } } public void Add(Microsoft.Build.BuildEngine.Toolset item) { } public void Clear() { } public bool Contains(Microsoft.Build.BuildEngine.Toolset item) { throw null; } public bool Contains(string toolsVersion) { throw null; } public void CopyTo(Microsoft.Build.BuildEngine.Toolset[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<Microsoft.Build.BuildEngine.Toolset> GetEnumerator() { throw null; } public bool Remove(Microsoft.Build.BuildEngine.Toolset item) { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } [System.FlagsAttribute] public enum ToolsetDefinitionLocations { ConfigurationFile = 1, None = 0, Registry = 2, } public partial class UsingTask { internal UsingTask() { } public string AssemblyFile { get { throw null; } } public string AssemblyName { get { throw null; } } public string Condition { get { throw null; } } public bool IsImported { get { throw null; } } public string TaskName { get { throw null; } } } public partial class UsingTaskCollection : System.Collections.ICollection, System.Collections.IEnumerable { internal UsingTaskCollection() { } public int Count { get { throw null; } } public bool IsSynchronized { get { throw null; } } public object SyncRoot { get { throw null; } } public void CopyTo(Microsoft.Build.BuildEngine.UsingTask[] array, int index) { } public void CopyTo(System.Array array, int index) { } public System.Collections.IEnumerator GetEnumerator() { throw null; } } public static partial class Utilities { public static string Escape(string unescapedExpression) { throw null; } } public delegate void WriteHandler(string message); }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Contoso.Core.TaxonomyMenuWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// 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 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.Cloud.BinaryAuthorization.V1Beta1 { /// <summary>Settings for <see cref="SystemPolicyV1Beta1Client"/> instances.</summary> public sealed partial class SystemPolicyV1Beta1Settings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="SystemPolicyV1Beta1Settings"/>.</summary> /// <returns>A new instance of the default <see cref="SystemPolicyV1Beta1Settings"/>.</returns> public static SystemPolicyV1Beta1Settings GetDefault() => new SystemPolicyV1Beta1Settings(); /// <summary>Constructs a new <see cref="SystemPolicyV1Beta1Settings"/> object with default settings.</summary> public SystemPolicyV1Beta1Settings() { } private SystemPolicyV1Beta1Settings(SystemPolicyV1Beta1Settings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetSystemPolicySettings = existing.GetSystemPolicySettings; OnCopy(existing); } partial void OnCopy(SystemPolicyV1Beta1Settings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SystemPolicyV1Beta1Client.GetSystemPolicy</c> and <c>SystemPolicyV1Beta1Client.GetSystemPolicyAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetSystemPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="SystemPolicyV1Beta1Settings"/> object.</returns> public SystemPolicyV1Beta1Settings Clone() => new SystemPolicyV1Beta1Settings(this); } /// <summary> /// Builder class for <see cref="SystemPolicyV1Beta1Client"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class SystemPolicyV1Beta1ClientBuilder : gaxgrpc::ClientBuilderBase<SystemPolicyV1Beta1Client> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public SystemPolicyV1Beta1Settings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public SystemPolicyV1Beta1ClientBuilder() { UseJwtAccessWithScopes = SystemPolicyV1Beta1Client.UseJwtAccessWithScopes; } partial void InterceptBuild(ref SystemPolicyV1Beta1Client client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SystemPolicyV1Beta1Client> task); /// <summary>Builds the resulting client.</summary> public override SystemPolicyV1Beta1Client Build() { SystemPolicyV1Beta1Client client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<SystemPolicyV1Beta1Client> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<SystemPolicyV1Beta1Client> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private SystemPolicyV1Beta1Client BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return SystemPolicyV1Beta1Client.Create(callInvoker, Settings); } private async stt::Task<SystemPolicyV1Beta1Client> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return SystemPolicyV1Beta1Client.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => SystemPolicyV1Beta1Client.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => SystemPolicyV1Beta1Client.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => SystemPolicyV1Beta1Client.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>SystemPolicyV1Beta1 client wrapper, for convenient use.</summary> /// <remarks> /// API for working with the system policy. /// </remarks> public abstract partial class SystemPolicyV1Beta1Client { /// <summary> /// The default endpoint for the SystemPolicyV1Beta1 service, which is a host of /// "binaryauthorization.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "binaryauthorization.googleapis.com:443"; /// <summary>The default SystemPolicyV1Beta1 scopes.</summary> /// <remarks> /// The default SystemPolicyV1Beta1 scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); 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="SystemPolicyV1Beta1Client"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="SystemPolicyV1Beta1ClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="SystemPolicyV1Beta1Client"/>.</returns> public static stt::Task<SystemPolicyV1Beta1Client> CreateAsync(st::CancellationToken cancellationToken = default) => new SystemPolicyV1Beta1ClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="SystemPolicyV1Beta1Client"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="SystemPolicyV1Beta1ClientBuilder"/>. /// </summary> /// <returns>The created <see cref="SystemPolicyV1Beta1Client"/>.</returns> public static SystemPolicyV1Beta1Client Create() => new SystemPolicyV1Beta1ClientBuilder().Build(); /// <summary> /// Creates a <see cref="SystemPolicyV1Beta1Client"/> 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="SystemPolicyV1Beta1Settings"/>.</param> /// <returns>The created <see cref="SystemPolicyV1Beta1Client"/>.</returns> internal static SystemPolicyV1Beta1Client Create(grpccore::CallInvoker callInvoker, SystemPolicyV1Beta1Settings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } SystemPolicyV1Beta1.SystemPolicyV1Beta1Client grpcClient = new SystemPolicyV1Beta1.SystemPolicyV1Beta1Client(callInvoker); return new SystemPolicyV1Beta1ClientImpl(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 SystemPolicyV1Beta1 client</summary> public virtual SystemPolicyV1Beta1.SystemPolicyV1Beta1Client GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Gets the current system policy in the specified location. /// </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 Policy GetSystemPolicy(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the current system policy in the specified location. /// </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<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the current system policy in the specified location. /// </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<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, st::CancellationToken cancellationToken) => GetSystemPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Policy GetSystemPolicy(string name, gaxgrpc::CallSettings callSettings = null) => GetSystemPolicy(new GetSystemPolicyRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </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<Policy> GetSystemPolicyAsync(string name, gaxgrpc::CallSettings callSettings = null) => GetSystemPolicyAsync(new GetSystemPolicyRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </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<Policy> GetSystemPolicyAsync(string name, st::CancellationToken cancellationToken) => GetSystemPolicyAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Policy GetSystemPolicy(PolicyName name, gaxgrpc::CallSettings callSettings = null) => GetSystemPolicy(new GetSystemPolicyRequest { PolicyName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </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<Policy> GetSystemPolicyAsync(PolicyName name, gaxgrpc::CallSettings callSettings = null) => GetSystemPolicyAsync(new GetSystemPolicyRequest { PolicyName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the current system policy in the specified location. /// </summary> /// <param name="name"> /// Required. The resource name, in the format `locations/*/policy`. /// Note that the system policy is not associated with a project. /// </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<Policy> GetSystemPolicyAsync(PolicyName name, st::CancellationToken cancellationToken) => GetSystemPolicyAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>SystemPolicyV1Beta1 client wrapper implementation, for convenient use.</summary> /// <remarks> /// API for working with the system policy. /// </remarks> public sealed partial class SystemPolicyV1Beta1ClientImpl : SystemPolicyV1Beta1Client { private readonly gaxgrpc::ApiCall<GetSystemPolicyRequest, Policy> _callGetSystemPolicy; /// <summary> /// Constructs a client wrapper for the SystemPolicyV1Beta1 service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="SystemPolicyV1Beta1Settings"/> used within this client.</param> public SystemPolicyV1Beta1ClientImpl(SystemPolicyV1Beta1.SystemPolicyV1Beta1Client grpcClient, SystemPolicyV1Beta1Settings settings) { GrpcClient = grpcClient; SystemPolicyV1Beta1Settings effectiveSettings = settings ?? SystemPolicyV1Beta1Settings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetSystemPolicy = clientHelper.BuildApiCall<GetSystemPolicyRequest, Policy>(grpcClient.GetSystemPolicyAsync, grpcClient.GetSystemPolicy, effectiveSettings.GetSystemPolicySettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetSystemPolicy); Modify_GetSystemPolicyApiCall(ref _callGetSystemPolicy); 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_GetSystemPolicyApiCall(ref gaxgrpc::ApiCall<GetSystemPolicyRequest, Policy> call); partial void OnConstruction(SystemPolicyV1Beta1.SystemPolicyV1Beta1Client grpcClient, SystemPolicyV1Beta1Settings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC SystemPolicyV1Beta1 client</summary> public override SystemPolicyV1Beta1.SystemPolicyV1Beta1Client GrpcClient { get; } partial void Modify_GetSystemPolicyRequest(ref GetSystemPolicyRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Gets the current system policy in the specified location. /// </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 Policy GetSystemPolicy(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetSystemPolicyRequest(ref request, ref callSettings); return _callGetSystemPolicy.Sync(request, callSettings); } /// <summary> /// Gets the current system policy in the specified location. /// </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<Policy> GetSystemPolicyAsync(GetSystemPolicyRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetSystemPolicyRequest(ref request, ref callSettings); return _callGetSystemPolicy.Async(request, callSettings); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsModelFlattening { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Extension methods for AutoRestResourceFlatteningTestService. /// </summary> public static partial class AutoRestResourceFlatteningTestServiceExtensions { /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> public static void PutArray(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutArrayAsync(resourceArray), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutArrayAsync(this IAutoRestResourceFlatteningTestService operations, IList<Resource> resourceArray = default(IList<Resource>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutArrayWithHttpMessagesAsync(resourceArray, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IList<FlattenedProduct> GetArray(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetArrayAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<FlattenedProduct>> GetArrayAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetArrayWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a Dictionary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> public static void PutDictionary(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutDictionaryAsync(resourceDictionary), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a Dictionary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDictionaryWithHttpMessagesAsync(resourceDictionary, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IDictionary<string, FlattenedProduct> GetDictionary(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetDictionaryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IDictionary<string, FlattenedProduct>> GetDictionaryAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDictionaryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> public static void PutResourceCollection(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection)) { Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutResourceCollectionAsync(resourceComplexObject), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, ResourceCollection resourceComplexObject = default(ResourceCollection), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutResourceCollectionWithHttpMessagesAsync(resourceComplexObject, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ResourceCollection GetResourceCollection(this IAutoRestResourceFlatteningTestService operations) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).GetResourceCollectionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceCollection> GetResourceCollectionAsync(this IAutoRestResourceFlatteningTestService operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetResourceCollectionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> public static SimpleProduct PutSimpleProduct(this IAutoRestResourceFlatteningTestService operations, SimpleProduct simpleBodyProduct = default(SimpleProduct)) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutSimpleProductAsync(simpleBodyProduct), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SimpleProduct> PutSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, SimpleProduct simpleBodyProduct = default(SimpleProduct), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PutSimpleProductWithHttpMessagesAsync(simpleBodyProduct, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Flattened Simple Product with client flattening true on the parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, genericValue, odatavalue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Flattened Simple Product with client flattening true on the parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SimpleProduct> PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, genericValue, odatavalue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> public static SimpleProduct PutSimpleProductWithGrouping(this IAutoRestResourceFlatteningTestService operations, FlattenParameterGroup flattenParameterGroup) { return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PutSimpleProductWithGroupingAsync(flattenParameterGroup), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SimpleProduct> PutSimpleProductWithGroupingAsync(this IAutoRestResourceFlatteningTestService operations, FlattenParameterGroup flattenParameterGroup, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PutSimpleProductWithGroupingWithHttpMessagesAsync(flattenParameterGroup, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* hotkey.c - Hot key functions * Copyright (c) 1995-1997 Stefan Jokisch * * This file is part of Frotz. * * Frotz 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. * * Frotz 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 zword = System.UInt16; using zbyte = System.Byte; using Frotz; using Frotz.Constants; namespace Frotz.Generic { internal static class Hotkey { /* * hot_key_debugging * * ...allows user to toggle cheating options on/off. * */ internal static bool hot_key_debugging () { Text.print_string ("Debugging options\n"); main.option_attribute_assignment = Input.read_yes_or_no("Watch attribute assignment"); main.option_attribute_testing = Input.read_yes_or_no("Watch attribute testing"); main.option_object_movement = Input.read_yes_or_no("Watch object movement"); main.option_object_locating = Input.read_yes_or_no("Watch object locating"); return false; }/* hot_key_debugging */ /* * hot_key_help * * ...displays a list of all hot keys. * */ static bool hot_key_help () { Text.print_string ("Help\n"); Text.print_string ( "\n" + "Alt-D debugging options\n" + "Alt-H help\n" + "Alt-N new game\n" + "Alt-P playback on\n" + "Alt-R recording on/off\n" + "Alt-S seed random numbers\n" + "Alt-U undo one turn\n" + "Alt-X exit game\n"); return false; }/* hot_key_help */ /* * hot_key_playback * * ...allows user to turn playback on. * */ internal static bool hot_key_playback () { Text.print_string ("Playback on\n"); if (!main.istream_replay) Files.replay_open (); return false; }/* hot_key_playback */ /* * hot_key_recording * * ...allows user to turn recording on/off. * */ internal static bool hot_key_recording () { if (main.istream_replay) { Text.print_string ("Playback off\n"); Files.replay_close (); } else if (main.ostream_record) { Text.print_string ("Recording off\n"); Files.record_close (); } else { Text.print_string ("Recording on\n"); Files.record_open (); } return false; }/* hot_key_recording */ /* * hot_key_seed * * ...allows user to seed the random number seed. * */ internal static bool hot_key_seed () { Text.print_string ("Seed random numbers\n"); Text.print_string ("Enter seed value (or return to randomize): "); Random.seed_random (Input.read_number ()); return false; }/* hot_key_seed */ /* * hot_key_undo * * ...allows user to undo the previous turn. * */ internal static bool hot_key_undo () { Text.print_string ("Undo one turn\n"); if (FastMem.restore_undo () > 0) { if (main.h_version >= ZMachine.V5) { /* for V5+ games we must */ Process.store (2); /* store 2 (for success) */ return true; /* and abort the input */ } if (main.h_version <= ZMachine.V3) { /* for V3- games we must */ Screen.z_show_status (); /* draw the status line */ return false; /* and continue input */ } } else Text.print_string ("No more undo information available.\n"); return false; }/* hot_key_undo */ /* * hot_key_restart * * ...allows user to start a new game. * */ internal static bool hot_key_restart () { Text.print_string ("New game\n"); if (Input.read_yes_or_no ("Do you wish to restart")) { FastMem.z_restart (); return true; } else return false; }/* hot_key_restart */ /* * hot_key_quit * * ...allows user to exit the game. * */ static bool hot_key_quit () { Text.print_string ("Exit game\n"); if (Input.read_yes_or_no ("Do you wish to quit")) { Process.z_quit (); return true; } else return false; }/* hot_key_quit */ /* * handle_hot_key * * Perform the action associated with a so-called hot key. Return * true to abort the current input action. * */ public static bool handle_hot_key(zword key) { if (main.cwin == 0) { bool aborting; aborting = false; Text.print_string("\nHot key -- "); switch (key) { case CharCodes.ZC_HKEY_RECORD: aborting = hot_key_recording(); break; case CharCodes.ZC_HKEY_PLAYBACK: aborting = hot_key_playback(); break; case CharCodes.ZC_HKEY_SEED: aborting = hot_key_seed(); break; case CharCodes.ZC_HKEY_UNDO: aborting = hot_key_undo(); break; case CharCodes.ZC_HKEY_RESTART: aborting = hot_key_restart(); break; case CharCodes.ZC_HKEY_QUIT: aborting = hot_key_quit(); break; case CharCodes.ZC_HKEY_DEBUG: aborting = hot_key_debugging(); break; case CharCodes.ZC_HKEY_HELP: aborting = hot_key_help(); break; } if (aborting) return false; Text.print_string("\nContinue input...\n"); } return false; }/* handle_hot_key */ } }
/* * 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.Data; using System.Reflection; using log4net; using Mono.Data.Sqlite; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.SQLite { public class SQLiteGenericTableHandler<T> : SQLiteFramework where T: class, new() { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>(); protected List<string> m_ColumnNames = null; protected string m_Realm; protected FieldInfo m_DataField = null; protected static SqliteConnection m_Connection; private static bool m_initialized; public SQLiteGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { m_Realm = realm; if (!m_initialized) { m_Connection = new SqliteConnection(connectionString); //Console.WriteLine(string.Format("OPENING CONNECTION FOR {0} USING {1}", storeName, connectionString)); m_Connection.Open(); if (storeName != String.Empty) { Assembly assem = GetType().Assembly; //SqliteConnection newConnection = // (SqliteConnection)((ICloneable)m_Connection).Clone(); //newConnection.Open(); //Migration m = new Migration(newConnection, assem, storeName); Migration m = new Migration(m_Connection, assem, storeName); m.Update(); //newConnection.Close(); //newConnection.Dispose(); } m_initialized = true; } Type t = typeof(T); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (fields.Length == 0) return; foreach (FieldInfo f in fields) { if (f.Name != "Data") m_Fields[f.Name] = f; else m_DataField = f; } } private void CheckColumnNames(IDataReader reader) { if (m_ColumnNames != null) return; m_ColumnNames = new List<string>(); DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null && (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) m_ColumnNames.Add(row["ColumnName"].ToString()); } } public T[] Get(string field, string key) { return Get(new string[] { field }, new string[] { key }); } public T[] Get(string[] fields, string[] keys) { if (fields.Length != keys.Length) return new T[0]; List<string> terms = new List<string>(); SqliteCommand cmd = new SqliteCommand(); for (int i = 0 ; i < fields.Length ; i++) { cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i])); terms.Add("`" + fields[i] + "` = :" + fields[i]); } string where = String.Join(" and ", terms.ToArray()); string query = String.Format("select * from {0} where {1}", m_Realm, where); cmd.CommandText = query; return DoQuery(cmd); } protected T[] DoQuery(SqliteCommand cmd) { IDataReader reader = ExecuteReader(cmd, m_Connection); if (reader == null) return new T[0]; CheckColumnNames(reader); List<T> result = new List<T>(); while (reader.Read()) { T row = new T(); foreach (string name in m_Fields.Keys) { if (m_Fields[name].GetValue(row) is bool) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v != 0 ? true : false); } else if (m_Fields[name].GetValue(row) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(reader[name].ToString(), out uuid); m_Fields[name].SetValue(row, uuid); } else if (m_Fields[name].GetValue(row) is int) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v); } else { m_Fields[name].SetValue(row, reader[name]); } } if (m_DataField != null) { Dictionary<string, string> data = new Dictionary<string, string>(); foreach (string col in m_ColumnNames) { data[col] = reader[col].ToString(); if (data[col] == null) data[col] = String.Empty; } m_DataField.SetValue(row, data); } result.Add(row); } //CloseCommand(cmd); return result.ToArray(); } public T[] Get(string where) { SqliteCommand cmd = new SqliteCommand(); string query = String.Format("select * from {0} where {1}", m_Realm, where); cmd.CommandText = query; return DoQuery(cmd); } public bool Store(T row) { SqliteCommand cmd = new SqliteCommand(); string query = ""; List<String> names = new List<String>(); List<String> values = new List<String>(); foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); values.Add(":" + fi.Name); cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString())); } if (m_DataField != null) { Dictionary<string, string> data = (Dictionary<string, string>)m_DataField.GetValue(row); foreach (KeyValuePair<string, string> kvp in data) { names.Add(kvp.Key); values.Add(":" + kvp.Key); cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value)); } } query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; cmd.CommandText = query; if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; } public bool Delete(string field, string val) { SqliteCommand cmd = new SqliteCommand(); cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field); cmd.Parameters.Add(new SqliteParameter(field, val)); if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Collections.ObjectModel; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class CorrectEventFiringTest : DriverTestFixture { [Test] public void ShouldFireFocusEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("focus"); } [Test] [Category("Javascript")] public void ShouldFireClickEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("click"); } [Test] [Category("Javascript")] public void ShouldFireMouseDownEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousedown"); } [Test] [Category("Javascript")] public void ShouldFireMouseUpEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseup"); } [Test] [Category("Javascript")] public void ShouldFireMouseOverEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mouseover"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Firefox, "Firefox does not report mouse move event when clicking")] public void ShouldFireMouseMoveEventWhenClicking() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); AssertEventFired("mousemove"); } [Test] [Category("Javascript")] public void ShouldNotThrowIfEventHandlerThrows() { driver.Url = javascriptPage; driver.FindElement(By.Id("throwing-mouseover")).Click(); } [Test] [Category("Javascript")] public void ShouldFireEventsInTheRightOrder() { driver.Url = javascriptPage; ClickOnElementWhichRecordsEvents(); string text = driver.FindElement(By.Id("result")).Text; int lastIndex = -1; List<string> eventList = new List<string>() { "mousedown", "focus", "mouseup", "click" }; foreach (string eventName in eventList) { int index = text.IndexOf(eventName); Assert.IsTrue(index != -1, eventName + " did not fire at all. Text is " + text); Assert.IsTrue(index > lastIndex, eventName + " did not fire in the correct order. Text is " + text); lastIndex = index; } } [Test] [Category("Javascript")] public void ShouldIssueMouseDownEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mousedown")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] public void ShouldIssueClickEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseclick")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse click"); } [Test] [Category("Javascript")] public void ShouldIssueMouseUpEvents() { driver.Url = javascriptPage; driver.FindElement(By.Id("mouseup")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse up"); } [Test] [Category("Javascript")] public void MouseEventsShouldBubbleUpToContainingElements() { driver.Url = javascriptPage; driver.FindElement(By.Id("child")).Click(); String result = driver.FindElement(By.Id("result")).Text; Assert.AreEqual(result, "mouse down"); } [Test] [Category("Javascript")] public void ShouldEmitOnChangeEventsWhenSelectingElements() { driver.Url = javascriptPage; //Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector']//option")); String initialTextValue = driver.FindElement(By.Id("result")).Text; IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, initialTextValue); bar.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] [Category("Javascript")] public void ShouldEmitOnClickEventsWhenSelectingElements() { driver.Url = javascriptPage; // Intentionally not looking up the select tag. See selenium r7937 for details. ReadOnlyCollection<IWebElement> allOptions = driver.FindElements(By.XPath("//select[@id='selector2']//option")); IWebElement foo = allOptions[0]; IWebElement bar = allOptions[1]; foo.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "foo"); bar.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "bar"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "IE does not fire change event when clicking on checkbox")] public void ShouldEmitOnChangeEventsWhenChangingTheStateOfACheckbox() { driver.Url = javascriptPage; IWebElement checkbox = driver.FindElement(By.Id("checkbox")); checkbox.Click(); Assert.AreEqual(driver.FindElement(By.Id("result")).Text, "checkbox thing"); } [Test] [Category("Javascript")] public void ShouldEmitClickEventWhenClickingOnATextInputElement() { driver.Url = javascriptPage; IWebElement clicker = driver.FindElement(By.Id("clickField")); clicker.Click(); Assert.AreEqual(clicker.GetAttribute("value"), "Clicked"); } [Test] [Category("Javascript")] public void ShouldFireTwoClickEventsWhenClickingOnALabel() { driver.Url = javascriptPage; driver.FindElement(By.Id("labelForCheckbox")).Click(); IWebElement result = driver.FindElement(By.Id("result")); Assert.IsTrue(WaitFor(() => { return result.Text.Contains("labelclick chboxclick"); }, "Did not find text: " + result.Text)); } [Test] [Category("Javascript")] public void ClearingAnElementShouldCauseTheOnChangeHandlerToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("clearMe")); element.Clear(); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual(result.Text, "Cleared"); } [Test] [Category("Javascript")] public void SendingKeysToAnotherElementShouldCauseTheBlurEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); IWebElement element2 = driver.FindElement(By.Id("changeable")); element2.SendKeys("bar"); AssertEventFired("blur"); } [Test] [Category("Javascript")] public void SendingKeysToAnElementShouldCauseTheFocusEventToFire() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("foo"); AssertEventFired("focus"); } [Test] [Category("Javascript")] public void SendingKeysToAFocusedElementShouldNotBlurThatElement() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("theworks")); element.Click(); //Wait until focused bool focused = false; IWebElement result = driver.FindElement(By.Id("result")); for (int i = 0; i < 5; ++i) { string fired = result.Text; if (fired.Contains("focus")) { focused = true; break; } try { System.Threading.Thread.Sleep(200); } catch (Exception e) { throw e; } } if (!focused) { Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing"); } element.SendKeys("a"); AssertEventNotFired("blur"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement formElement = driver.FindElement(By.Id("submitListeningForm")); formElement.Submit(); AssertEventFired("form-onsubmit"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormInputSubmitElementShouldFireOnSubmitForThatForm() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit"); } [Test] [Category("Javascript")] public void SubmittingFormFromFormInputTextElementShouldFireOnSubmitForThatFormAndNotClickOnThatInput() { driver.Url = javascriptPage; IWebElement submit = driver.FindElement(By.Id("submitListeningForm-submit")); submit.Submit(); AssertEventFired("form-onsubmit"); AssertEventNotFired("text-onclick"); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] [IgnoreBrowser(Browser.WindowsPhone, "Does not yet support file uploads")] public void UploadingFileShouldFireOnChangeEvent() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); IWebElement result = driver.FindElement(By.Id("fileResults")); Assert.AreEqual(string.Empty, result.Text); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); // Shift focus to something else because send key doesn't make the focus leave driver.FindElement(By.Id("id-name1")).Click(); inputFile.Delete(); Assert.AreEqual("changed", result.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldReportTheXAndYCoordinatesWhenClicking() { driver.Url = clickEventPage; IWebElement element = driver.FindElement(By.Id("eventish")); element.Click(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2); string clientX = driver.FindElement(By.Id("clientX")).Text; string clientY = driver.FindElement(By.Id("clientY")).Text; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0); Assert.AreNotEqual("0", clientX); Assert.AreNotEqual("0", clientY); } [Test] public void ClickEventsShouldBubble() { driver.Url = clicksPage; driver.FindElement(By.Id("bubblesFrom")).Click(); bool eventBubbled = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return !!window.bubbledClick;"); Assert.IsTrue(eventBubbled, "Event didn't bubble up"); } [Test] [IgnoreBrowser(Browser.IE, "IE doesn't support detecting overlapped elements")] [IgnoreBrowser(Browser.Safari)] public void ClickOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/overlapping_elements.html"); var ex = Assert.Throws<WebDriverException>(() => driver.FindElement(By.Id("under")).Click()); Assert.That(ex.Message.Contains("Other element would receive the click")); } [Test] [IgnoreBrowser(Browser.IE, "IE doesn't support detecting overlapped elements")] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Safari)] public void ClickPartiallyOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in under (handled by under)"); expectedLogBuilder.AppendLine("mousedown in under (handled by body)"); expectedLogBuilder.AppendLine("mouseup in under (handled by under)"); expectedLogBuilder.AppendLine("mouseup in under (handled by body)"); expectedLogBuilder.AppendLine("click in under (handled by under)"); expectedLogBuilder.Append("click in under (handled by body)"); for (int i = 1; i < 6; i++) { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/partially_overlapping_elements.html"); IWebElement over = driver.FindElement(By.Id("over" + i)); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.display = 'none'", over); driver.FindElement(By.Id("under")).Click(); Assert.AreEqual(expectedLogBuilder.ToString(), driver.FindElement(By.Id("log")).Text); } } [Test] [IgnoreBrowser(Browser.Firefox)] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Safari)] public void NativelyClickOverlappingElements() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in over (handled by over)"); expectedLogBuilder.AppendLine("mousedown in over (handled by body)"); expectedLogBuilder.AppendLine("mouseup in over (handled by over)"); expectedLogBuilder.AppendLine("mouseup in over (handled by body)"); expectedLogBuilder.AppendLine("click in over (handled by over)"); expectedLogBuilder.Append("click in over (handled by body)"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/overlapping_elements.html"); driver.FindElement(By.Id("under")).Click(); Assert.AreEqual(expectedLogBuilder.ToString(), driver.FindElement(By.Id("log")).Text); } [Test] [IgnoreBrowser(Browser.Safari)] public void ClickAnElementThatDisappear() { if (TestUtilities.IsOldIE(driver)) { Assert.Ignore("Not supported on IE < 9"); } StringBuilder expectedLogBuilder = new StringBuilder(); expectedLogBuilder.AppendLine("Log:"); expectedLogBuilder.AppendLine("mousedown in over (handled by over)"); expectedLogBuilder.AppendLine("mousedown in over (handled by body)"); expectedLogBuilder.AppendLine("mouseup in under (handled by under)"); expectedLogBuilder.Append("mouseup in under (handled by body)"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/disappearing_element.html"); driver.FindElement(By.Id("over")).Click(); Assert.That(driver.FindElement(By.Id("log")).Text.StartsWith(expectedLogBuilder.ToString())); } private void AssertEventNotFired(string eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsFalse(text.Contains(eventName), eventName + " fired: " + text); } private void ClickOnElementWhichRecordsEvents() { driver.FindElement(By.Id("plainButton")).Click(); } private void AssertEventFired(String eventName) { IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains(eventName), "No " + eventName + " fired: " + text); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.Hosting; using System.Web.Security; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Configuration; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Adxstudio.Xrm.Services; using Adxstudio.Xrm.Services.Query; using Microsoft.Xrm.Sdk.Query; namespace Adxstudio.Xrm.Web.Security { public class CrmRoleProvider : RoleProvider { private string _applicationName; private string _attributeMapIsAuthenticatedUsersRole; private string _attributeMapRoleName; private string _attributeMapRoleWebsiteId; private string _attributeMapUsername; private string _attributeMapStateCode; private string _attributeMapIsDisabled; private bool _authenticatedUsersRolesEnabled; private bool _initialized; private string _roleEntityName; private string _roleToUserRelationshipName; private string _userEntityName; private string _roleEntityId; private string _userEntityId; protected static List<string> RequiredCustomAttributes = new List<string> { "attributeMapStateCode", "attributeMapRoleName", "attributeMapRoleWebsiteId", "attributeMapUsername", "roleEntityName", "roleToUserRelationshipName", "userEntityName", "userEntityId", "roleEntityId" }; protected OrganizationServiceContext CreateContext() { return PortalCrmConfigurationManager.CreateServiceContext(PortalName); } /// <summary> /// Initializes the provider with the property values specified in the ASP.NET application's configuration file. /// </summary> public override void Initialize(string name, NameValueCollection config) { if (_initialized) { return; } config.ThrowOnNull("config"); if (string.IsNullOrEmpty(name)) { name = GetType().FullName; } if (string.IsNullOrEmpty(config["description"])) { config["description"] = "XRM Role Provider"; } base.Initialize(name, config); AssertRequiredCustomAttributes(config); ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName(); _attributeMapIsAuthenticatedUsersRole = config["attributeMapIsAuthenticatedUsersRole"]; bool authenticatedUsersRolesEnabledConfigurationValue; // Whether "Authenticated Users" role is supported is determine by a config switch, and whether // or not an attribute map for that boolean has been supplied. The feature is enabled by default, // provided that an attribute map has been supplied. _authenticatedUsersRolesEnabled = !string.IsNullOrWhiteSpace(_attributeMapIsAuthenticatedUsersRole) && bool.TryParse(config["authenticatedUsersRolesEnabled"], out authenticatedUsersRolesEnabledConfigurationValue) ? authenticatedUsersRolesEnabledConfigurationValue : true; _attributeMapStateCode = config["attributeMapStateCode"]; _attributeMapIsDisabled = config["attributeMapIsDisabled"]; _attributeMapRoleName = config["attributeMapRoleName"]; _attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"]; _attributeMapUsername = config["attributeMapUsername"]; PortalName = config["portalName"]; _roleEntityName = config["roleEntityName"]; _roleToUserRelationshipName = config["roleToUserRelationshipName"]; _userEntityName = config["userEntityName"]; _roleEntityId = config["roleEntityId"]; _userEntityId = config["userEntityId"]; var recognizedAttributes = new List<string> { "name", "applicationName", "attributeMapStateCode", "attributeMapIsDisabled", "attributeMapIsAuthenticatedUsersRole", "attributeMapRoleName", "attributeMapRoleWebsiteId", "attributeMapUsername", "portalName", "roleEntityName", "roleToUserRelationshipName", "userEntityName", "roleEntityId", "userEntityId" }; // Remove all of the known configuration values. If there are any left over, they are unrecognized. recognizedAttributes.ForEach(config.Remove); if (config.Count > 0) { var unrecognizedAttribute = config.GetKey(0); if (!string.IsNullOrEmpty(unrecognizedAttribute)) { throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute)); } } _initialized = true; } /// <summary> /// Gets or sets the name of the application to store and retrieve role information for. /// </summary> /// <returns> /// The name of the application to store and retrieve role information for. /// </returns> public override string ApplicationName { get { return _applicationName; } set { if (string.IsNullOrEmpty(value)) throw new ArgumentException("{0} - ApplicationName can't be null or empty.".FormatWith(ToString())); if (value.Length > 0x100) throw new ProviderException("{0} - ApplicationName is too long.".FormatWith(ToString())); _applicationName = value; } } /// <summary> /// The portal name to use to connect to Microsoft Dynamics CRM. /// </summary> public string PortalName { get; private set; } /// <summary> /// Gets the configured adx_website ID to which the operations of this provider are scoped. /// </summary> protected virtual EntityReference WebsiteID { get { return HttpContext.Current.GetWebsite().Entity.ToEntityReference(); } } /// <summary> /// Adds the specified user names to the specified roles for the configured applicationName. /// </summary> /// <param name="roleNames">A string array of the role names to add the specified user names to. </param> /// <param name="usernames">A string array of user names to be added to the specified roles. </param> public override void AddUsersToRoles(string[] usernames, string[] roleNames) { using (var context = CreateContext()) { ForEachUserAndRole(context, usernames, roleNames, (user, role) => context.AddLink(user, _roleToUserRelationshipName.ToRelationship(), role)); context.SaveChanges(); } } /// <summary> /// Adds a new role to the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to create.</param> public override void CreateRole(string roleName) { if (RoleExists(roleName)) { throw new ProviderException("A role with the name {0} already exists.".FormatWith(roleName)); } var webrole = new Entity(_roleEntityName); webrole.SetAttributeValue(_attributeMapRoleName, roleName); webrole.SetAttributeValue(_attributeMapRoleWebsiteId, WebsiteID); using (var context = CreateContext()) { context.AddObject(webrole); context.SaveChanges(); } } /// <summary> /// Removes a role from the data source for the configured applicationName. /// </summary> /// <returns> /// True if the role was successfully deleted; otherwise, false. /// </returns> /// <param name="throwOnPopulatedRole">If true, then an exception will be thrown if the role has one or more members and the role will not be deleted.</param> /// <param name="roleName">The name of the role to delete.</param> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { using (var context = CreateContext()) { var roles = GetRolesInWebsiteByName(context, roleName).ToList(); if (throwOnPopulatedRole) { if (roles.Where(role => role.GetRelatedEntities(context, _roleToUserRelationshipName).Any()).Any()) { throw new ProviderException("The role {0} can't be deleted because it has one or more members.".FormatWith(roleName)); } } foreach (var role in roles) { context.DeleteObject(role); } context.SaveChanges(); return true; } } /// <summary> /// Gets an array of user names in a role where the user name contains the specified user name to match. /// </summary> /// <returns> /// A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role. /// </returns> /// <param name="usernameToMatch">The user name to search for.</param> /// <param name="roleName">The role to search in.</param> public override string[] FindUsersInRole(string roleName, string usernameToMatch) { var usersInRole = GetUsersInRole(roleName); return usersInRole.Where(username => username.Contains(usernameToMatch)).ToArray(); } /// <summary> /// Gets an array of all the roles for the configured applicationName. /// </summary> /// <returns> /// A string array containing the names of all the roles stored in the data source for the configured applicationName. /// </returns> public override string[] GetAllRoles() { using (var context = CreateContext()) { var roleNames = ( from role in context.CreateQuery(_roleEntityName) where role.GetAttributeValue<int>(_attributeMapStateCode) == 0 && role.GetAttributeValue<EntityReference>(_attributeMapRoleWebsiteId) == WebsiteID select role) .ToArray().Select(e => e.GetAttributeValue<string>(_attributeMapRoleName)); return roleNames.Distinct().ToArray(); } } /// <summary> /// Gets an array of the roles that a specified user is in for the configured applicationName. /// </summary> /// <returns> /// A string array containing the names of all the roles that the specified user is in for the configured applicationName. /// </returns> /// <param name="username">The user to return a list of roles for.</param> public override string[] GetRolesForUser(string username) { var fetch = new Fetch { Entity = new FetchEntity(_roleEntityName) { Attributes = new[] { new FetchAttribute(_attributeMapRoleName) }, Filters = new[] { new Filter { Conditions = new[] { new Condition(_attributeMapStateCode, ConditionOperator.Equal, 0), new Condition(_attributeMapRoleWebsiteId, ConditionOperator.Equal, WebsiteID.Id) } } }, Links = new[] { new Link { Name = _roleToUserRelationshipName, ToAttribute = _roleEntityId, FromAttribute = _roleEntityId, Links = new[] { new Link { IsUnique = true, Name = _userEntityName, ToAttribute = _userEntityId, FromAttribute = _userEntityId, Attributes = new[] { new FetchAttribute(_userEntityId) }, Filters = new[] { new Filter { Conditions = GetUserNamePredicate(username) } } } } } } } }; var service = HttpContext.Current.GetOrganizationService(); var entities = service.RetrieveMultiple(fetch).Entities; var roleNames = entities.Select(e => e.GetAttributeValue<string>(_attributeMapRoleName)).ToList(); // Merge in the authenticated users roles, if that option is defined. if (_authenticatedUsersRolesEnabled) { fetch = new Fetch { Entity = new FetchEntity(_roleEntityName) { Attributes = new[] { new FetchAttribute(_attributeMapRoleName) }, Filters = new[] { new Filter { Conditions = new[] { new Condition(_attributeMapStateCode, ConditionOperator.Equal, 0), new Condition(_attributeMapRoleWebsiteId, ConditionOperator.Equal, WebsiteID.Id), new Condition(_attributeMapIsAuthenticatedUsersRole, ConditionOperator.Equal, true) } } } } }; entities = service.RetrieveMultiple(fetch).Entities; var authenticatedUsersRoleNames = entities.Select(e => e.GetAttributeValue<string>(_attributeMapRoleName)).ToList(); return roleNames.Union(authenticatedUsersRoleNames).Distinct().ToArray(); } return roleNames.Distinct().ToArray(); } /// <summary> /// Gets the conditions based on _attributeMapIsDisabled value /// </summary> /// <param name="userName">The username</param> /// <returns>The conditions.</returns> private Condition[] GetUserNamePredicate(string userName) { if (!string.IsNullOrWhiteSpace(_attributeMapIsDisabled)) { return new[] { new Condition(_attributeMapIsDisabled, ConditionOperator.Equal, false), new Condition(_attributeMapUsername, ConditionOperator.Equal, userName) }; } else { return new[] { new Condition(_attributeMapStateCode, ConditionOperator.Equal, 0), new Condition(_attributeMapUsername, ConditionOperator.Equal, userName) }; } } /// <summary> /// Gets an array of users in the specified role for the configured applicationName. /// </summary> /// <returns> /// A string array containing the names of all the users who are members of the specified role for the configured applicationName. /// </returns> /// <param name="roleName">The name of the role to get the list of users for. </param> public override string[] GetUsersInRole(string roleName) { if (!RoleExists(roleName)) { return new string[0]; } var roles = GetRolesInWebsiteByName(roleName).ToList(); if (!roles.Any()) { return new string[0]; } // If any of the role entities in question have the Authenticated Users flag switched on, return the names of all users with // a non-null username. if (_authenticatedUsersRolesEnabled && roles.Any(role => role.GetAttributeValue<bool?>(_attributeMapIsAuthenticatedUsersRole) == true)) { var authenticatedUsers = HttpContext.Current.GetOrganizationService() .RetrieveAll(_userEntityName, new[] { _attributeMapUsername }, GetAllUsersPredicate()) .Select(user => user.GetAttributeValue<string>(_attributeMapUsername)) .Distinct() .ToArray(); return authenticatedUsers; } var roleIds = roles.Select(e => e.Id).Cast<object>().ToList(); var fetch = new Fetch { Entity = new FetchEntity(_userEntityName) { Attributes = new[] { new FetchAttribute(_attributeMapUsername) }, Filters = new[] { new Filter { Conditions = GetAllUsersPredicate() } }, Links = new[] { new Link { Name = _roleToUserRelationshipName, ToAttribute = _userEntityId, FromAttribute = _userEntityId, Links = new[] { new Link { Name = _roleEntityName, ToAttribute = _roleEntityId, FromAttribute = _roleEntityId, Filters = new[] { new Filter { Conditions = new[] { new Condition(_roleEntityId, ConditionOperator.In, roleIds) } } } } } } } } }; var users = HttpContext.Current.GetOrganizationService() .RetrieveAll(fetch) .Select(e => e.GetAttributeValue<string>(_attributeMapUsername)) .Distinct() .ToArray(); return users; } private Condition[] GetAllUsersPredicate() { if (!string.IsNullOrWhiteSpace(_attributeMapIsDisabled)) { return new[] { new Condition(_attributeMapIsDisabled, ConditionOperator.Equal, false), new Condition(_attributeMapUsername, ConditionOperator.NotNull) }; } else { return new[] { new Condition(_attributeMapStateCode, ConditionOperator.Equal, 0), new Condition(_attributeMapUsername, ConditionOperator.NotNull) }; } } /// <summary> /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName. /// </summary> /// <returns> /// True if the specified user is in the specified role for the configured applicationName; otherwise, false. /// </returns> /// <param name="username">The user name to search for.</param> /// <param name="roleName">The role to search in.</param> public override bool IsUserInRole(string username, string roleName) { var rolesForUser = GetRolesForUser(username); return rolesForUser.Contains(roleName); } /// <summary> /// Removes the specified user names from the specified roles for the configured applicationName. /// </summary> /// <param name="roleNames">A string array of role names to remove the specified user names from. </param> /// <param name="usernames">A string array of user names to be removed from the specified roles. </param> public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { using (var context = CreateContext()) { ForEachUserAndRole(context, usernames, roleNames, (user, role) => context.DeleteLink(user, _roleToUserRelationshipName.ToRelationship(), role)); context.SaveChanges(); } } /// <summary> /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName. /// </summary> /// <returns> /// True if the role name already exists in the data source for the configured applicationName; otherwise, false. /// </returns> /// <param name="roleName">The name of the role to search for in the data source. </param> public override bool RoleExists(string roleName) { return GetRolesInWebsiteByName(roleName).Any(); } private void AssertRequiredCustomAttributes(NameValueCollection config) { var requiredCustomAttributesNotFound = RequiredCustomAttributes.Where(attribute => string.IsNullOrEmpty(config[attribute])); if (requiredCustomAttributesNotFound.Any()) { throw new ConfigurationErrorsException("The {0} requires the following attribute(s) to be specified:\n{1}".FormatWith(Name, string.Join("\n", requiredCustomAttributesNotFound.ToArray()))); } } /// <summary> /// Finds each user and role entity specified by the usernames and role names provided, respectively, and calls a delegate for each possible pairing. /// </summary> /// <exception cref="ProviderException"> /// Thrown if any of the specified users or roles are not found. /// </exception> private void ForEachUserAndRole(OrganizationServiceContext context, string[] usernames, string[] roleNames, Action<Entity, Entity> action) { // If there are no usernames or no roles, there's nothing to be done, so exit. if (!(usernames.Any() && roleNames.Any())) { return; } var users = context.CreateQuery(_userEntityName) .Where(ContainsPropertyValueEqual<Entity>(_attributeMapUsername, usernames)) .Where(GetDeactivatedPredicate()) .ToList(); var usersNotFound = usernames.Except(users.Select(contact => contact.GetAttributeValue<string>(_attributeMapUsername))); if (usersNotFound.Any()) { throw new ProviderException("The users {0} weren't found.".FormatWith(string.Join(", ", usersNotFound.ToArray()))); } var roles = context.CreateQuery(_roleEntityName) .Where(ContainsPropertyValueEqual<Entity>(_attributeMapRoleName, roleNames)) .Where(role => role.GetAttributeValue<int>(_attributeMapStateCode) == 0 && role.GetAttributeValue<EntityReference>(_attributeMapRoleWebsiteId) == WebsiteID) .ToList(); var rolesNotFound = roleNames.Except(roles.Select(role => role.GetAttributeValue<string>(_attributeMapRoleName))); if (rolesNotFound.Any()) { throw new ProviderException("The role(s) {0} was/were not found.".FormatWith(string.Join(", ", rolesNotFound.ToArray()))); } foreach (var user in users) { foreach (var role in roles) { action(user, role); } } } private Expression<Func<Entity, bool>> GetDeactivatedPredicate() { if (!string.IsNullOrWhiteSpace(_attributeMapIsDisabled)) { return user => user.GetAttributeValue<bool>(_attributeMapIsDisabled) == false; } else { return user => user.GetAttributeValue<int>(_attributeMapStateCode) == 0; } } private IEnumerable<Entity> GetRolesInWebsiteByName(OrganizationServiceContext context, string roleName) { return context.CreateQuery(_roleEntityName) .Where(role => role.GetAttributeValue<int>(_attributeMapStateCode) == 0 && role.GetAttributeValue<string>(_attributeMapRoleName) == roleName && role.GetAttributeValue<EntityReference>(_attributeMapRoleWebsiteId) == WebsiteID); } private IEnumerable<Entity> GetRolesInWebsiteByName(string roleName) { var fetch = new Fetch { Entity = new FetchEntity(_roleEntityName) { Attributes = new[] { new FetchAttribute(_attributeMapRoleName), new FetchAttribute(_attributeMapIsAuthenticatedUsersRole) }, Filters = new[] { new Filter { Conditions = new[] { new Condition(_attributeMapStateCode, ConditionOperator.Equal, 0), new Condition(_attributeMapRoleName, ConditionOperator.Equal, roleName), new Condition(_attributeMapRoleWebsiteId, ConditionOperator.Equal, WebsiteID.Id) } } } } }; var service = HttpContext.Current.GetOrganizationService(); var entities = service.RetrieveMultiple(fetch).Entities; return entities; } private static Expression<Func<TParameter, bool>> ContainsPropertyValueEqual<TParameter>(string crmPropertyName, IEnumerable<object> values) { var parameterType = typeof(TParameter); var parameter = Expression.Parameter(parameterType, parameterType.Name.ToLowerInvariant()); var expression = ContainsPropertyValueEqual(crmPropertyName, values, parameter); return Expression.Lambda<Func<TParameter, bool>>(expression, parameter); } private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<object> values, ParameterExpression parameter) { var left = PropertyValueEqual(parameter, crmPropertyName, values.First()); return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, left); } private static Expression ContainsPropertyValueEqual(string crmPropertyName, IEnumerable<object> values, ParameterExpression parameter, Expression expression) { if (!values.Any()) { return expression; } var orElse = Expression.OrElse(expression, PropertyValueEqual(parameter, crmPropertyName, values.First())); return ContainsPropertyValueEqual(crmPropertyName, values.Skip(1), parameter, orElse); } private static Expression PropertyValueEqual(Expression parameter, string crmPropertyName, object value) { var methodCall = Expression.Call(parameter, "GetAttributeValue", new[] { typeof(string) }, Expression.Constant(crmPropertyName)); return Expression.Equal(methodCall, Expression.Constant(value)); } internal class Utility { public static string GetDefaultApplicationName() { try { string applicationVirtualPath = HostingEnvironment.ApplicationVirtualPath; if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath; applicationVirtualPath = Process.GetCurrentProcess().MainModule.ModuleName; int index = applicationVirtualPath.IndexOf('.'); if (index != -1) { applicationVirtualPath = applicationVirtualPath.Remove(index); } if (!string.IsNullOrEmpty(applicationVirtualPath)) return applicationVirtualPath; return "/"; } catch { return "/"; } } } } /// <summary> /// A <see cref="CrmRoleProvider"/> that validates 'contact' entities (users) against 'adx_webrole' entitles (roles). /// </summary> /// <remarks> /// Configuration format. /// <code> /// <![CDATA[ /// <configuration> /// /// <system.web> /// <roleManager enabled="true" defaultProvider="Xrm"> /// <providers> /// <add /// name="Xrm" /// type="Microsoft.Xrm.Portal.Web.Security.CrmContactRoleProvider" /// portalName="Xrm" [Microsoft.Xrm.Portal.Configuration.PortalContextElement] /// attributeMapIsAuthenticatedUsersRole="adx_authenticatedusersrole" /// attributeMapRoleName="adx_name" /// attributeMapRoleWebsiteId="adx_websiteid" /// attributeMapUsername="adx_identity_username" /// roleEntityName="adx_webrole" /// roleToUserRelationshipName="adx_webrole_contact" /// userEntityName="contact" /// userEntityId="contactid" /// roleEntityId="adx_webroleid" /// /> /// </providers> /// </roleManager> /// </system.web> /// /// </configuration> /// ]]> /// </code> /// </remarks> /// <seealso cref="PortalContextElement"/> /// <seealso cref="PortalCrmConfigurationManager"/> /// <seealso cref="CrmConfigurationManager"/> public class CrmContactRoleProvider : CrmRoleProvider { public override void Initialize(string name, NameValueCollection config) { config["attributeMapStateCode"] = config["attributeMapStateCode"] ?? "statecode"; config["attributeMapIsAuthenticatedUsersRole"] = config["attributeMapIsAuthenticatedUsersRole"] ?? "adx_authenticatedusersrole"; config["attributeMapRoleName"] = config["attributeMapRoleName"] ?? "adx_name"; config["attributeMapRoleWebsiteId"] = config["attributeMapRoleWebsiteId"] ?? "adx_websiteid"; config["attributeMapUsername"] = config["attributeMapUsername"] ?? "adx_identity_username"; config["roleEntityName"] = config["roleEntityName"] ?? "adx_webrole"; config["roleToUserRelationshipName"] = config["roleToUserRelationshipName"] ?? "adx_webrole_contact"; config["userEntityName"] = config["userEntityName"] ?? "contact"; config["userEntityId"] = config["userEntityId"] ?? "contactid"; config["roleEntityId"] = "adx_webroleid"; base.Initialize(name, config); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Activator is an object that contains the Activation (CreateInstance/New) // methods for late bound support. // // // // namespace System { using System; using System.Reflection; using System.Runtime.Remoting; #if FEATURE_REMOTING using System.Runtime.Remoting.Activation; using Message = System.Runtime.Remoting.Messaging.Message; #endif using System.Security; using CultureInfo = System.Globalization.CultureInfo; using Evidence = System.Security.Policy.Evidence; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security.Permissions; using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // Only statics, does not need to be marked with the serializable attribute [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_Activator))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class Activator : _Activator { internal const int LookupMask = 0x000000FF; internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public); internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; // This class only contains statics, so hide the worthless constructor private Activator() { } // CreateInstance // The following methods will create a new instance of an Object // Full Binding Support // For all of these methods we need to get the underlying RuntimeType and // call the Impl version. static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture) { return CreateInstance(type, bindingAttr, binder, args, culture, null); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public Object CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes) { if ((object)type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if (type is System.Reflection.Emit.TypeBuilder) throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder")); // If they didn't specify a lookup, then we will provide the default lookup. if ((bindingAttr & (BindingFlags) LookupMask) == 0) bindingAttr |= Activator.ConstructorDefault; if (activationAttributes != null && activationAttributes.Length > 0){ // If type does not derive from MBR // throw notsupportedexception #if FEATURE_REMOTING if(type.IsMarshalByRef){ // The fix below is preventative. // if(!(type.IsContextful)){ if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute)) throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR")); } } else #endif throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" )); } RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark); } static public Object CreateInstance(Type type, params Object[] args) { return CreateInstance(type, Activator.ConstructorDefault, null, args, null, null); } static public Object CreateInstance(Type type, Object[] args, Object[] activationAttributes) { return CreateInstance(type, Activator.ConstructorDefault, null, args, null, activationAttributes); } static public Object CreateInstance(Type type) { return Activator.CreateInstance(type, false); } /* * Create an instance using the name of type and the assembly where it exists. This allows * types to be created remotely without having to load the type locally. */ [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public ObjectHandle CreateInstance(String assemblyName, String typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, false, Activator.ConstructorDefault, null, null, null, null, null, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public ObjectHandle CreateInstance(String assemblyName, String typeName, Object[] activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, false, Activator.ConstructorDefault, null, null, null, activationAttributes, null, ref stackMark); } [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public Object CreateInstance(Type type, bool nonPublic) { if ((object)type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); RuntimeType rt = type.UnderlyingSystemType as RuntimeType; if (rt == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark); } [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable static public T CreateInstance<T>() { RuntimeType rt = typeof(T) as RuntimeType; // This is a workaround to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[]. // Array, Ref, and Pointer types don't have default constructors. if (rt.HasElementType) throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor")); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions). #if FEATURE_CORECLR // In SL2/3 CreateInstance<T> doesn't do any security checks. This would mean that Assembly B can create instances of an internal // type in Assembly A upon A's request: // TypeInAssemblyA.DoWork() { AssemblyB.Create<InternalTypeInAssemblyA>();} // TypeInAssemblyB.Create<T>() {return new T();} // This violates type safety but we saw multiple user apps that have put a dependency on it. So for compatibility we allow this if // the SL app was built against SL2/3. // Note that in SL2/3 it is possible for app code to instantiate public transparent types with public critical default constructors. // Fortunately we don't have such types in out platform assemblies. if (CompatibilitySwitches.IsAppEarlierThanSilverlight4 || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) return (T)rt.CreateInstanceSlow(true /*publicOnly*/, true /*skipCheckThis*/, false /*fillCache*/, ref stackMark); else #endif // FEATURE_CORECLR return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark); } static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName) { return CreateInstanceFrom(assemblyFile, typeName, null); } static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, Object[] activationAttributes) { return CreateInstanceFrom(assemblyFile, typeName, false, Activator.ConstructorDefault, null, null, null, activationAttributes); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] static public ObjectHandle CreateInstance(String assemblyName, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo, ref stackMark); } [SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null, ref stackMark); } [System.Security.SecurityCritical] // auto-generated static internal ObjectHandle CreateInstance(String assemblyString, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo, ref StackCrawlMark stackMark) { #if FEATURE_CAS_POLICY if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY Type type = null; Assembly assembly = null; if (assemblyString == null) { assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark); } else { RuntimeAssembly assemblyFromResolveEvent; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent); if (assemblyFromResolveEvent != null) { // Assembly was resolved via AssemblyResolve event assembly = assemblyFromResolveEvent; } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { // WinRT type - we have to use Type.GetType type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); } else { // Classic managed type assembly = RuntimeAssembly.InternalLoadAssemblyName( assemblyName, securityInfo, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/); } } if (type == null) { // It's classic managed type (not WinRT type) Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString); if(assembly == null) return null; type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase); } Object o = Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] static public ObjectHandle CreateInstanceFrom(String assemblyFile, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { #if FEATURE_CAS_POLICY if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return CreateInstanceFromInternal(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityInfo); } public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { return CreateInstanceFromInternal(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } private static ObjectHandle CreateInstanceFromInternal(String assemblyFile, String typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo) { #if FEATURE_CAS_POLICY Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null); #endif // FEATURE_CAS_POLICY #pragma warning disable 618 Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo); #pragma warning restore 618 Type t = assembly.GetType(typeName, true, ignoreCase); Object o = Activator.CreateInstance(t, bindingAttr, binder, args, culture, activationAttributes); Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } // // This API is designed to be used when a host needs to execute code in an AppDomain // with restricted security permissions. In that case, we demand in the client domain // and assert in the server domain because the server domain might not be trusted enough // to pass the security checks when activating the type. // [System.Security.SecurityCritical] // auto-generated_required public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); #if FEATURE_CAS_POLICY if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } [SecurityCritical] public static ObjectHandle CreateInstance(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } // // This API is designed to be used when a host needs to execute code in an AppDomain // with restricted security permissions. In that case, we demand in the client domain // and assert in the server domain because the server domain might not be trusted enough // to pass the security checks when activating the type. // [System.Security.SecurityCritical] // auto-generated_required public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName); } [System.Security.SecurityCritical] // auto-generated_required [Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")] public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); #if FEATURE_CAS_POLICY if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit")); } #endif // FEATURE_CAS_POLICY return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes); } [SecurityCritical] public static ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) { if (domain == null) throw new ArgumentNullException("domain"); Contract.EndContractBlock(); return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, null); } #if FEATURE_COMINTEROP #if FEATURE_CLICKONCE [System.Security.SecuritySafeCritical] // auto-generated public static ObjectHandle CreateInstance (ActivationContext activationContext) { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.ApplicationActivator.CreateInstance(activationContext); } [System.Security.SecuritySafeCritical] // auto-generated public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) { AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager; if (domainManager == null) domainManager = new AppDomainManager(); return domainManager.ApplicationActivator.CreateInstance(activationContext, activationCustomData); } #endif // FEATURE_CLICKONCE public static ObjectHandle CreateComInstanceFrom(String assemblyName, String typeName) { return CreateComInstanceFrom(assemblyName, typeName, null, AssemblyHashAlgorithm.None); } public static ObjectHandle CreateComInstanceFrom(String assemblyName, String typeName, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm) { Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm); Type t = assembly.GetType(typeName, true, false); Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false); if (Attr.Length > 0) { if (((ComVisibleAttribute)Attr[0]).Value == false) throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" )); } Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName); if(assembly == null) return null; Object o = Activator.CreateInstance(t, Activator.ConstructorDefault, null, null, null, null); Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName); if(o == null) return null; else { ObjectHandle Handle = new ObjectHandle(o); return Handle; } } #endif // FEATURE_COMINTEROP #if FEATURE_REMOTING // This method is a helper method and delegates to the remoting // services to do the actual work. [System.Security.SecurityCritical] // auto-generated_required static public Object GetObject(Type type, String url) { return GetObject(type, url, null); } // This method is a helper method and delegates to the remoting // services to do the actual work. [System.Security.SecurityCritical] // auto-generated_required static public Object GetObject(Type type, String url, Object state) { if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); return RemotingServices.Connect(type, url, state); } #endif [System.Diagnostics.Conditional("_DEBUG")] private static void Log(bool test, string title, string success, string failure) { #if FEATURE_REMOTING if(test) BCLDebug.Trace("REMOTE", "{0}{1}", title, success); else BCLDebug.Trace("REMOTE", "{0}{1}", title, failure); #endif } #if !FEATURE_CORECLR void _Activator.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _Activator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _Activator.Invoke in VM\DangerousAPIs.h and // include _Activator in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _Activator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Data; using System.Text; using System.Collections; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; using Autodesk.Revit.UI; using Material = Autodesk.Revit.DB.Material; namespace Revit.SDK.Samples.MaterialProperties.CS { /// <summary> /// five basic material types in Revit /// </summary> public enum MaterialType { /// <summary> /// unassigned material /// </summary> Unassigned = 0, /// <summary> /// concrete material /// </summary> Steel = 1, /// <summary> /// steel material /// </summary> Concrete = 2, /// <summary> /// generic material /// </summary> Generic = 3, /// <summary> /// wood material /// </summary> Wood = 4, } /// <summary> /// get the material physical properties of the selected beam, column or brace /// get all material types and their sub types to the user and then change the material type of the selected beam to the one chosen by the user /// with a selected concrete beam, column or brace, change its unit weight to 145 P/ft3 /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] [Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)] public class MaterialProperties : Autodesk.Revit.UI.IExternalCommand { const double ToMetricUnitWeight = 0.010764; //coefficient of converting unit weight from internal unit to metric unit const double ToMetricStress = 0.334554; //coefficient of converting stress from internal unit to metric unit const double ToImperialUnitWeight = 6.365827; //coefficient of converting unit weight from internal unit to imperial unit const double ChangedUnitWeight = 14.5; //the value of unit weight of selected component to be set Autodesk.Revit.UI.UIApplication m_revit = null; Hashtable m_allMaterialMap = new Hashtable(); //hashtable contains all materials with index of their ElementId FamilyInstance m_selectedComponent = null; //selected beam, column or brace Parameter m_currentMaterial = null; //current material of selected beam, column or brace Material m_cacheMaterial; ArrayList m_steels = new ArrayList(); //arraylist of all materials belonging to steel type ArrayList m_concretes = new ArrayList(); //arraylist of all materials belonging to concrete type /// <summary> /// get the material type of selected element /// </summary> public MaterialType CurrentType { get { Material material = CurrentMaterial as Material; int materialId = 0; if (material != null) { materialId = material.Id.IntegerValue; } if (materialId <= 0) { return MaterialType.Generic; } Autodesk.Revit.DB.Material materialElem = (Autodesk.Revit.DB.Material)m_allMaterialMap[materialId]; if (null == materialElem) { return MaterialType.Generic; } Parameter materialPara = materialElem.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_TYPE); if (null == materialPara) { return MaterialType.Generic; } return (MaterialType)materialPara.AsInteger(); } } /// <summary> /// get the material attribute of selected element /// </summary> public object CurrentMaterial { get { m_cacheMaterial = GetCurrentMaterial(); return m_cacheMaterial; } } /// <summary> /// arraylist of all materials belonging to steel type /// </summary> public ArrayList SteelCollection { get { return m_steels; } } /// <summary> /// arraylist of all materials belonging to concrete type /// </summary> public ArrayList ConcreteCollection { get { return m_concretes; } } /// <summary> /// three basic material types in Revit /// </summary> public ArrayList MaterialTypes { get { ArrayList typeAL = new ArrayList(); typeAL.Add("Unassigned"); typeAL.Add("Steel"); typeAL.Add("Concrete"); typeAL.Add("Generic"); typeAL.Add("Wood"); return typeAL; } } /// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { Autodesk.Revit.UI.UIApplication revit = commandData.Application; m_revit = revit; if (!Init()) { // there must be exactly one beam, column or brace selected MessageBox.Show("You should select only one beam, structural column or brace."); return Autodesk.Revit.UI.Result.Failed; } Transaction documentTransaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document"); documentTransaction.Start(); MaterialPropertiesForm displayForm = new MaterialPropertiesForm(this); try { displayForm.ShowDialog(); } catch { MessageBox.Show("Sorry that your command failed."); return Autodesk.Revit.UI.Result.Failed; } documentTransaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; } /// <summary> /// get a datatable contains parameters' information of certain element /// </summary> /// <param name="o">Revit element</param> /// <param name="substanceKind">the material type of this element</param> /// <returns>datatable contains parameters' names and values</returns> public DataTable GetParameterTable(object o, MaterialType substanceKind) { //create an empty datatable DataTable parameterTable = CreateTable(); //if failed to convert object Autodesk.Revit.DB.Material material = o as Autodesk.Revit.DB.Material; if (material == null) { return parameterTable; } Parameter temporaryAttribute = null; // hold each parameter string temporaryValue = ""; // hold each value #region Get all material element parameters //- Behavior temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_BEHAVIOR); switch (temporaryAttribute.AsInteger()) { case 0: AddDataRow(temporaryAttribute.Definition.Name, "Isotropic", parameterTable); break; case 1: AddDataRow(temporaryAttribute.Definition.Name, "Orthotropic", parameterTable); break; default: AddDataRow(temporaryAttribute.Definition.Name, "None", parameterTable); break; } //- Young's Modulus temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD1); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD2); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_YOUNG_MOD3); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); // - Poisson Modulus temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD1); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD2); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_POISSON_MOD3); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); // - Shear Modulus temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD1); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD2); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_MOD3); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Thermal Expansion Coefficient temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF1); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF2); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_EXP_COEFF3); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Unit Weight temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_UNIT_WEIGHT); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Damping Ratio temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_DAMPING_RATIO); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Bending Reinforcement temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_BENDING_REINFORCEMENT); if (null != temporaryAttribute) { temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); } //- Shear Reinforcement temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_REINFORCEMENT); if (null != temporaryAttribute) { temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); } //- Resistance Calc Strength temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_RESISTANCE_CALC_STRENGTH); if (null != temporaryAttribute) { temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); } // For Steel only: if (MaterialType.Steel == substanceKind) { //- Minimum Yield Stress temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_YIELD_STRESS); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Minimum Tensile Strength temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_MINIMUM_TENSILE_STRENGTH); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Reduction Factor temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_REDUCTION_FACTOR); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); } // For Concrete only: if (MaterialType.Concrete == substanceKind) { //- Concrete Compression temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_CONCRETE_COMPRESSION); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Lightweight temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_LIGHT_WEIGHT); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); //- Shear Strength Reduction temporaryAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_SHEAR_STRENGTH_REDUCTION); temporaryValue = temporaryAttribute.AsValueString(); AddDataRow(temporaryAttribute.Definition.Name, temporaryValue, parameterTable); } #endregion return parameterTable; } /// <summary> /// Update cache material /// </summary> /// <param name="obj">new material</param> public void UpdateMaterial(object obj) { if (null == obj) { throw new ArgumentNullException(); } { m_cacheMaterial = obj as Material; } } /// <summary> /// set the material of selected component /// </summary> public void SetMaterial() { if (null == m_cacheMaterial || null == m_currentMaterial) { return; } Autodesk.Revit.DB.ElementId identity = m_cacheMaterial.Id; m_currentMaterial.Set(identity); } /// <summary> /// change unit weight of selected component to 14.50 kN/m3 /// </summary> public bool ChangeUnitWeight() { Autodesk.Revit.DB.Material material = GetCurrentMaterial(); if (material == null) { return false; } Parameter weightPara = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_UNIT_WEIGHT); weightPara.Set(ChangedUnitWeight / ToMetricUnitWeight); return true; } /// <summary> /// firstly, check whether only one beam, column or brace is selected /// then initialize some member variables /// </summary> /// <returns>is the initialize successful</returns> private bool Init() { //selected 0 or more than 1 component if (m_revit.ActiveUIDocument.Selection.Elements.Size != 1) { return false; } try { GetSelectedComponent(); //selected component isn't beam, column or brace if (m_selectedComponent == null) { return false; } //initialize some member variables GetAllMaterial(); return true; } catch { return false; } } /// <summary> /// get current material of selected component /// </summary> private Autodesk.Revit.DB.Material GetCurrentMaterial() { if (null != m_cacheMaterial) return m_cacheMaterial; int identityValue = 0; if (m_currentMaterial != null) identityValue = m_currentMaterial.AsElementId().IntegerValue; //get the value of current material's ElementId //material has no value if (identityValue <= 0) { return null; } Autodesk.Revit.DB.Material material = (Autodesk.Revit.DB.Material)m_allMaterialMap[identityValue]; return material; } /// <summary> /// get selected beam, column or brace /// </summary> /// <returns></returns> private void GetSelectedComponent() { ElementSet componentCollection = m_revit.ActiveUIDocument.Selection.Elements; if (componentCollection.Size != 1) { return; } //if the selection is a beam, column or brace, find out its parameters for display foreach (object o in componentCollection) { FamilyInstance component = o as FamilyInstance; if (component == null) { continue; } if (component.StructuralType == StructuralType.Beam || component.StructuralType == StructuralType.Brace || component.StructuralType == StructuralType.Column) { //get selected beam, column or brace m_selectedComponent = component; } //selection is a beam, column or brace, find out its parameters foreach (object p in component.Parameters) { Parameter attribute = p as Parameter; if (attribute == null) { continue; } string parameterName = attribute.Definition.Name; if (parameterName == "Column Material" || parameterName == "Beam Material") { //get current material of selected component m_currentMaterial = attribute; break; } } } } /// <summary> /// get all materials exist in current document /// </summary> /// <returns></returns> private void GetAllMaterial() { FilteredElementCollector collector = new FilteredElementCollector(m_revit.ActiveUIDocument.Document); FilteredElementIterator i = collector.OfClass(typeof(Material)).GetElementIterator(); i.Reset(); bool moreValue = i.MoveNext(); while (moreValue) { Autodesk.Revit.DB.Material material = i.Current as Autodesk.Revit.DB.Material; if (material == null) { moreValue = i.MoveNext(); continue; } //get the type of the material Parameter materialAttribute = material.get_Parameter(BuiltInParameter.PHY_MATERIAL_PARAM_TYPE); if (materialAttribute == null) { moreValue = i.MoveNext(); continue; } //add materials to different ArrayList according to their types switch ((MaterialType)materialAttribute.AsInteger()) { case MaterialType.Steel: { m_steels.Add(new MaterialMap(material)); break; } case MaterialType.Concrete: { m_concretes.Add(new MaterialMap(material)); break; } default: { break; } } //map between materials and their elementId m_allMaterialMap.Add(material.Id.IntegerValue, material); moreValue = i.MoveNext(); } } /// <summary> /// Create an empty table with parameter's name column and value column /// </summary> /// <returns></returns> private DataTable CreateTable() { // Create a new DataTable. DataTable propDataTable = new DataTable("ParameterTable"); // Create parameter column and add to the DataTable. DataColumn paraDataColumn = new DataColumn(); paraDataColumn.DataType = System.Type.GetType("System.String"); paraDataColumn.ColumnName = "Parameter"; paraDataColumn.Caption = "Parameter"; paraDataColumn.ReadOnly = true; // Add the column to the DataColumnCollection. propDataTable.Columns.Add(paraDataColumn); // Create value column and add to the DataTable. DataColumn valueDataColumn = new DataColumn(); valueDataColumn.DataType = System.Type.GetType("System.String"); valueDataColumn.ColumnName = "Value"; valueDataColumn.Caption = "Value"; valueDataColumn.ReadOnly = false; propDataTable.Columns.Add(valueDataColumn); return propDataTable; } /// <summary> /// add one row to datatable of parameter /// </summary> /// <param name="parameterName">name of parameter</param> /// <param name="parameterValue">value of parameter</param> /// <param name="parameterTable">datatable to be added row</param> private void AddDataRow(string parameterName, string parameterValue, DataTable parameterTable) { DataRow newRow = parameterTable.NewRow(); newRow["Parameter"] = parameterName; newRow["Value"] = parameterValue; parameterTable.Rows.Add(newRow); } } /// <summary> /// assistant class contains material and its name /// </summary> public class MaterialMap { string m_materialName; Autodesk.Revit.DB.Material m_material; /// <summary> /// constructor without parameter is forbidden /// </summary> private MaterialMap() { } /// <summary> /// constructor /// </summary> /// <param name="material"></param> public MaterialMap(Autodesk.Revit.DB.Material material) { m_materialName = material.Name; m_material = material; } /// <summary> /// Get the material name /// </summary> public string MaterialName { get { return m_materialName; } } /// <summary> /// Get the material /// </summary> public Autodesk.Revit.DB.Material Material { get { return m_material; } } } }
//--------------------------------------------------------------------------- // // <copyright file="Transform3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { abstract partial class Transform3D : GeneralTransform3D, DUCE.IResource { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new Transform3D Clone() { return (Transform3D)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new Transform3D CloneCurrentValue() { return (Transform3D)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal abstract DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel); /// <summary> /// AddRefOnChannel /// </summary> DUCE.ResourceHandle DUCE.IResource.AddRefOnChannel(DUCE.Channel channel) { // Reconsider the need for this lock when removing the MultiChannelResource. using (CompositionEngineLock.Acquire()) { return AddRefOnChannelCore(channel); } } internal abstract void ReleaseOnChannelCore(DUCE.Channel channel); /// <summary> /// ReleaseOnChannel /// </summary> void DUCE.IResource.ReleaseOnChannel(DUCE.Channel channel) { // Reconsider the need for this lock when removing the MultiChannelResource. using (CompositionEngineLock.Acquire()) { ReleaseOnChannelCore(channel); } } internal abstract DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel); /// <summary> /// GetHandle /// </summary> DUCE.ResourceHandle DUCE.IResource.GetHandle(DUCE.Channel channel) { DUCE.ResourceHandle handle; using (CompositionEngineLock.Acquire()) { handle = GetHandleCore(channel); } return handle; } internal abstract int GetChannelCountCore(); /// <summary> /// GetChannelCount /// </summary> int DUCE.IResource.GetChannelCount() { // must already be in composition lock here return GetChannelCountCore(); } internal abstract DUCE.Channel GetChannelCore(int index); /// <summary> /// GetChannel /// </summary> DUCE.Channel DUCE.IResource.GetChannel(int index) { // must already be in composition lock here return GetChannelCore(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #endregion Constructors } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace WebsitePanel.Import.Enterprise { partial class ApplicationForm { /// <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(ApplicationForm)); this.lblSpace = new System.Windows.Forms.Label(); this.txtSpace = new System.Windows.Forms.TextBox(); this.btnBrowseSpace = new System.Windows.Forms.Button(); this.btnBrowseOU = new System.Windows.Forms.Button(); this.txtOU = new System.Windows.Forms.TextBox(); this.lblOU = new System.Windows.Forms.Label(); this.grpOrganization = new System.Windows.Forms.GroupBox(); this.cbMailboxPlan = new System.Windows.Forms.ComboBox(); this.lblMailnoxPlan = new System.Windows.Forms.Label(); this.btnSelectAll = new System.Windows.Forms.Button(); this.btnDeselectAll = new System.Windows.Forms.Button(); this.rbCreateAndImport = new System.Windows.Forms.RadioButton(); this.rbImport = new System.Windows.Forms.RadioButton(); this.lvUsers = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.images = new System.Windows.Forms.ImageList(this.components); this.txtOrgName = new System.Windows.Forms.TextBox(); this.lblOrgName = new System.Windows.Forms.Label(); this.txtOrgId = new System.Windows.Forms.TextBox(); this.lblOrgId = new System.Windows.Forms.Label(); this.btnStart = new System.Windows.Forms.Button(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.lblMessage = new System.Windows.Forms.Label(); this.grpOrganization.SuspendLayout(); this.SuspendLayout(); // // lblSpace // this.lblSpace.Location = new System.Drawing.Point(15, 15); this.lblSpace.Name = "lblSpace"; this.lblSpace.Size = new System.Drawing.Size(125, 23); this.lblSpace.TabIndex = 0; this.lblSpace.Text = "Target Hosting Space:"; // // txtSpace // this.txtSpace.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSpace.Location = new System.Drawing.Point(146, 12); this.txtSpace.Name = "txtSpace"; this.txtSpace.ReadOnly = true; this.txtSpace.Size = new System.Drawing.Size(426, 20); this.txtSpace.TabIndex = 1; this.txtSpace.TextChanged += new System.EventHandler(this.OnDataChanged); // // btnBrowseSpace // this.btnBrowseSpace.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnBrowseSpace.Location = new System.Drawing.Point(578, 10); this.btnBrowseSpace.Name = "btnBrowseSpace"; this.btnBrowseSpace.Size = new System.Drawing.Size(24, 22); this.btnBrowseSpace.TabIndex = 2; this.btnBrowseSpace.Text = "..."; this.btnBrowseSpace.UseVisualStyleBackColor = true; this.btnBrowseSpace.Click += new System.EventHandler(this.OnBrowseSpace); // // btnBrowseOU // this.btnBrowseOU.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnBrowseOU.Location = new System.Drawing.Point(578, 36); this.btnBrowseOU.Name = "btnBrowseOU"; this.btnBrowseOU.Size = new System.Drawing.Size(24, 22); this.btnBrowseOU.TabIndex = 5; this.btnBrowseOU.Text = "..."; this.btnBrowseOU.UseVisualStyleBackColor = true; this.btnBrowseOU.Click += new System.EventHandler(this.OnBrowseOU); // // txtOU // this.txtOU.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtOU.Location = new System.Drawing.Point(146, 38); this.txtOU.Name = "txtOU"; this.txtOU.ReadOnly = true; this.txtOU.Size = new System.Drawing.Size(426, 20); this.txtOU.TabIndex = 4; this.txtOU.TextChanged += new System.EventHandler(this.OnDataChanged); // // lblOU // this.lblOU.Location = new System.Drawing.Point(15, 41); this.lblOU.Name = "lblOU"; this.lblOU.Size = new System.Drawing.Size(125, 23); this.lblOU.TabIndex = 3; this.lblOU.Text = "Organizational Unit:"; // // grpOrganization // this.grpOrganization.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpOrganization.Controls.Add(this.cbMailboxPlan); this.grpOrganization.Controls.Add(this.lblMailnoxPlan); this.grpOrganization.Controls.Add(this.btnSelectAll); this.grpOrganization.Controls.Add(this.btnDeselectAll); this.grpOrganization.Controls.Add(this.rbCreateAndImport); this.grpOrganization.Controls.Add(this.rbImport); this.grpOrganization.Controls.Add(this.lvUsers); this.grpOrganization.Controls.Add(this.txtOrgName); this.grpOrganization.Controls.Add(this.lblOrgName); this.grpOrganization.Controls.Add(this.txtOrgId); this.grpOrganization.Controls.Add(this.lblOrgId); this.grpOrganization.Location = new System.Drawing.Point(15, 67); this.grpOrganization.Name = "grpOrganization"; this.grpOrganization.Size = new System.Drawing.Size(587, 328); this.grpOrganization.TabIndex = 6; this.grpOrganization.TabStop = false; // // cbMailboxPlan // this.cbMailboxPlan.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cbMailboxPlan.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbMailboxPlan.FormattingEnabled = true; this.cbMailboxPlan.Location = new System.Drawing.Point(155, 74); this.cbMailboxPlan.Name = "cbMailboxPlan"; this.cbMailboxPlan.Size = new System.Drawing.Size(415, 21); this.cbMailboxPlan.TabIndex = 10; // // lblMailnoxPlan // this.lblMailnoxPlan.Location = new System.Drawing.Point(19, 74); this.lblMailnoxPlan.Name = "lblMailnoxPlan"; this.lblMailnoxPlan.Size = new System.Drawing.Size(130, 23); this.lblMailnoxPlan.TabIndex = 9; this.lblMailnoxPlan.Text = "Default mailbox plan :"; // // btnSelectAll // this.btnSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSelectAll.Location = new System.Drawing.Point(414, 282); this.btnSelectAll.Name = "btnSelectAll"; this.btnSelectAll.Size = new System.Drawing.Size(75, 23); this.btnSelectAll.TabIndex = 7; this.btnSelectAll.Text = "Select All"; this.btnSelectAll.UseVisualStyleBackColor = true; this.btnSelectAll.Click += new System.EventHandler(this.OnSelectAllClick); // // btnDeselectAll // this.btnDeselectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnDeselectAll.Location = new System.Drawing.Point(495, 282); this.btnDeselectAll.Name = "btnDeselectAll"; this.btnDeselectAll.Size = new System.Drawing.Size(75, 23); this.btnDeselectAll.TabIndex = 8; this.btnDeselectAll.Text = "Unselect All"; this.btnDeselectAll.UseVisualStyleBackColor = true; this.btnDeselectAll.Click += new System.EventHandler(this.OnDeselectAllClick); // // rbCreateAndImport // this.rbCreateAndImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.rbCreateAndImport.AutoSize = true; this.rbCreateAndImport.Checked = true; this.rbCreateAndImport.Enabled = false; this.rbCreateAndImport.Location = new System.Drawing.Point(19, 282); this.rbCreateAndImport.Name = "rbCreateAndImport"; this.rbCreateAndImport.Size = new System.Drawing.Size(261, 17); this.rbCreateAndImport.TabIndex = 5; this.rbCreateAndImport.TabStop = true; this.rbCreateAndImport.Text = "Create new organization and import selected items"; this.rbCreateAndImport.UseVisualStyleBackColor = true; this.rbCreateAndImport.CheckedChanged += new System.EventHandler(this.OnCheckedChanged); // // rbImport // this.rbImport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.rbImport.AutoSize = true; this.rbImport.Enabled = false; this.rbImport.Location = new System.Drawing.Point(19, 305); this.rbImport.Name = "rbImport"; this.rbImport.Size = new System.Drawing.Size(237, 17); this.rbImport.TabIndex = 6; this.rbImport.Text = "Import selected items for existing organization"; this.rbImport.UseVisualStyleBackColor = true; // // lvUsers // this.lvUsers.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lvUsers.CheckBoxes = true; this.lvUsers.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3}); this.lvUsers.FullRowSelect = true; this.lvUsers.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvUsers.Location = new System.Drawing.Point(19, 108); this.lvUsers.MultiSelect = false; this.lvUsers.Name = "lvUsers"; this.lvUsers.Size = new System.Drawing.Size(551, 167); this.lvUsers.SmallImageList = this.images; this.lvUsers.TabIndex = 4; this.lvUsers.UseCompatibleStateImageBehavior = false; this.lvUsers.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "Name"; this.columnHeader1.Width = 238; // // columnHeader2 // this.columnHeader2.Text = "Email"; this.columnHeader2.Width = 166; // // columnHeader3 // this.columnHeader3.Text = "Type"; this.columnHeader3.Width = 124; // // images // this.images.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("images.ImageStream"))); this.images.TransparentColor = System.Drawing.Color.Transparent; this.images.Images.SetKeyName(0, "UserSmallIcon.ico"); this.images.Images.SetKeyName(1, "contact.ico"); this.images.Images.SetKeyName(2, "DL.ico"); // // txtOrgName // this.txtOrgName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtOrgName.Location = new System.Drawing.Point(155, 45); this.txtOrgName.Name = "txtOrgName"; this.txtOrgName.Size = new System.Drawing.Size(415, 20); this.txtOrgName.TabIndex = 3; // // lblOrgName // this.lblOrgName.Location = new System.Drawing.Point(19, 48); this.lblOrgName.Name = "lblOrgName"; this.lblOrgName.Size = new System.Drawing.Size(130, 23); this.lblOrgName.TabIndex = 2; this.lblOrgName.Text = "Organization Name:"; // // txtOrgId // this.txtOrgId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtOrgId.Location = new System.Drawing.Point(155, 19); this.txtOrgId.Name = "txtOrgId"; this.txtOrgId.ReadOnly = true; this.txtOrgId.Size = new System.Drawing.Size(415, 20); this.txtOrgId.TabIndex = 1; // // lblOrgId // this.lblOrgId.Location = new System.Drawing.Point(19, 22); this.lblOrgId.Name = "lblOrgId"; this.lblOrgId.Size = new System.Drawing.Size(130, 23); this.lblOrgId.TabIndex = 0; this.lblOrgId.Text = "Organization Id:"; // // btnStart // this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnStart.Location = new System.Drawing.Point(524, 461); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(75, 23); this.btnStart.TabIndex = 9; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.OnImportClick); // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(15, 427); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(584, 23); this.progressBar.TabIndex = 8; // // lblMessage // this.lblMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblMessage.Location = new System.Drawing.Point(12, 401); this.lblMessage.Name = "lblMessage"; this.lblMessage.Size = new System.Drawing.Size(590, 23); this.lblMessage.TabIndex = 7; // // ApplicationForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(614, 496); this.Controls.Add(this.lblMessage); this.Controls.Add(this.progressBar); this.Controls.Add(this.btnStart); this.Controls.Add(this.grpOrganization); this.Controls.Add(this.btnBrowseOU); this.Controls.Add(this.txtOU); this.Controls.Add(this.lblOU); this.Controls.Add(this.btnBrowseSpace); this.Controls.Add(this.txtSpace); this.Controls.Add(this.lblSpace); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(630, 500); this.Name = "ApplicationForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "WebsitePanel Enterprise Import Tool"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OnFormClosing); this.grpOrganization.ResumeLayout(false); this.grpOrganization.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblSpace; private System.Windows.Forms.TextBox txtSpace; private System.Windows.Forms.Button btnBrowseSpace; private System.Windows.Forms.Button btnBrowseOU; private System.Windows.Forms.TextBox txtOU; private System.Windows.Forms.Label lblOU; private System.Windows.Forms.GroupBox grpOrganization; private System.Windows.Forms.TextBox txtOrgId; private System.Windows.Forms.Label lblOrgId; private System.Windows.Forms.TextBox txtOrgName; private System.Windows.Forms.Label lblOrgName; private System.Windows.Forms.ListView lvUsers; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ImageList images; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; internal System.Windows.Forms.Button btnStart; internal System.Windows.Forms.ProgressBar progressBar; internal System.Windows.Forms.Label lblMessage; private System.Windows.Forms.RadioButton rbCreateAndImport; private System.Windows.Forms.RadioButton rbImport; internal System.Windows.Forms.Button btnSelectAll; internal System.Windows.Forms.Button btnDeselectAll; private System.Windows.Forms.ComboBox cbMailboxPlan; private System.Windows.Forms.Label lblMailnoxPlan; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for PolicyAssignmentsOperations. /// </summary> public static partial class PolicyAssignmentsOperationsExtensions { /// <summary> /// Delete policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> public static PolicyAssignment Delete(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).DeleteAsync(scope, policyAssignmentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> DeleteAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(scope, policyAssignmentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> public static PolicyAssignment Create(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, PolicyAssignment parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).CreateAsync(scope, policyAssignmentName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> CreateAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, PolicyAssignment parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(scope, policyAssignmentName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get single policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> public static PolicyAssignment Get(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).GetAsync(scope, policyAssignmentName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get single policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='scope'> /// Scope of the policy assignment. /// </param> /// <param name='policyAssignmentName'> /// Policy assignment name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> GetAsync(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(scope, policyAssignmentName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> public static Microsoft.Rest.Azure.IPage<PolicyAssignment> ListForResourceGroup(this IPolicyAssignmentsOperations operations, string resourceGroupName, string filter = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceGroupAsync(resourceGroupName, filter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Resource group name. /// </param> /// <param name='filter'> /// The filter to apply on the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListForResourceGroupAsync(this IPolicyAssignmentsOperations operations, string resourceGroupName, string filter = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListForResourceGroupWithHttpMessagesAsync(resourceGroupName, filter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments of the resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The resource provider namespace. /// </param> /// <param name='parentResourcePath'> /// The parent resource path. /// </param> /// <param name='resourceType'> /// The resource type. /// </param> /// <param name='resourceName'> /// The resource name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static Microsoft.Rest.Azure.IPage<PolicyAssignment> ListForResource(this IPolicyAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment>)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments of the resource. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// The resource provider namespace. /// </param> /// <param name='parentResourcePath'> /// The parent resource path. /// </param> /// <param name='resourceType'> /// The resource type. /// </param> /// <param name='resourceName'> /// The resource name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListForResourceAsync(this IPolicyAssignmentsOperations operations, string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListForResourceWithHttpMessagesAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static Microsoft.Rest.Azure.IPage<PolicyAssignment> List(this IPolicyAssignmentsOperations operations, Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment>)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListAsync(odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListAsync(this IPolicyAssignmentsOperations operations, Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<PolicyAssignment>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> public static PolicyAssignment DeleteById(this IPolicyAssignmentsOperations operations, string policyAssignmentId) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).DeleteByIdAsync(policyAssignmentId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> DeleteByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.DeleteByIdWithHttpMessagesAsync(policyAssignmentId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create policy assignment by Id. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> public static PolicyAssignment CreateById(this IPolicyAssignmentsOperations operations, string policyAssignmentId, PolicyAssignment parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).CreateByIdAsync(policyAssignmentId, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create policy assignment by Id. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='parameters'> /// Policy assignment. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> CreateByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, PolicyAssignment parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateByIdWithHttpMessagesAsync(policyAssignmentId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get single policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> public static PolicyAssignment GetById(this IPolicyAssignmentsOperations operations, string policyAssignmentId) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).GetByIdAsync(policyAssignmentId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get single policy assignment. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='policyAssignmentId'> /// Policy assignment Id /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PolicyAssignment> GetByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetByIdWithHttpMessagesAsync(policyAssignmentId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<PolicyAssignment> ListForResourceGroupNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceGroupNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments of the resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListForResourceGroupNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListForResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets policy assignments of the resource. /// </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 Microsoft.Rest.Azure.IPage<PolicyAssignment> ListForResourceNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListForResourceNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets policy assignments of the resource. /// </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<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListForResourceNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListForResourceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<PolicyAssignment> ListNext(this IPolicyAssignmentsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all the policy assignments of a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<PolicyAssignment>> ListNextAsync(this IPolicyAssignmentsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright (c) .NET Foundation and contributors. 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.IO; using System.Linq; using Microsoft.Build.Construction; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectJsonMigration.Transforms; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Common; using NuGet.Frameworks; using NuGet.LibraryModel; namespace Microsoft.DotNet.ProjectJsonMigration.Rules { public class MigratePackageDependenciesAndToolsRule : IMigrationRule { private readonly ITransformApplicator _transformApplicator; private readonly ProjectDependencyFinder _projectDependencyFinder; private string _projectDirectory; public MigratePackageDependenciesAndToolsRule(ITransformApplicator transformApplicator = null) { _transformApplicator = transformApplicator ?? new TransformApplicator(); _projectDependencyFinder = new ProjectDependencyFinder(); } public void Apply(MigrationSettings migrationSettings, MigrationRuleInputs migrationRuleInputs) { CleanExistingPackageReferences(migrationRuleInputs.OutputMSBuildProject); _projectDirectory = migrationSettings.ProjectDirectory; var project = migrationRuleInputs.DefaultProjectContext.ProjectFile; var tfmDependencyMap = new Dictionary<string, IEnumerable<ProjectLibraryDependency>>(); var targetFrameworks = project.GetTargetFrameworks(); // Inject Sdk dependency _transformApplicator.Execute( PackageDependencyInfoTransform.Transform( new PackageDependencyInfo { Name = ConstantPackageNames.CSdkPackageName, Version = migrationSettings.SdkPackageVersion, PrivateAssets = "All" }), migrationRuleInputs.CommonItemGroup); // Migrate Direct Deps first MigrateDependencies( project, migrationRuleInputs.OutputMSBuildProject, null, project.Dependencies, migrationRuleInputs.ProjectXproj); MigrationTrace.Instance.WriteLine($"Migrating {targetFrameworks.Count()} target frameworks"); foreach (var targetFramework in targetFrameworks) { MigrationTrace.Instance.WriteLine($"Migrating framework {targetFramework.FrameworkName.GetShortFolderName()}"); MigrateImports(migrationRuleInputs.CommonPropertyGroup, targetFramework); MigrateDependencies( project, migrationRuleInputs.OutputMSBuildProject, targetFramework.FrameworkName, targetFramework.Dependencies, migrationRuleInputs.ProjectXproj); } MigrateTools(project, migrationRuleInputs.OutputMSBuildProject); } private void MigrateImports(ProjectPropertyGroupElement commonPropertyGroup, TargetFrameworkInformation targetFramework) { var transform = ImportsTransformation.Transform(targetFramework); if (transform != null) { transform.Condition = targetFramework.FrameworkName.GetMSBuildCondition(); _transformApplicator.Execute(transform, commonPropertyGroup); } else { MigrationTrace.Instance.WriteLine($"{nameof(MigratePackageDependenciesAndToolsRule)}: imports transform null for {targetFramework.FrameworkName.GetShortFolderName()}"); } } private void CleanExistingPackageReferences(ProjectRootElement outputMSBuildProject) { var packageRefs = outputMSBuildProject.Items.Where(i => i.ItemType == "PackageReference").ToList(); foreach (var packageRef in packageRefs) { var parent = packageRef.Parent; packageRef.Parent.RemoveChild(packageRef); parent.RemoveIfEmpty(); } } private void MigrateTools( Project project, ProjectRootElement output) { if (project.Tools == null || !project.Tools.Any()) { return; } var itemGroup = output.AddItemGroup(); foreach (var tool in project.Tools) { _transformApplicator.Execute(ToolTransform.Transform(tool), itemGroup); } } private void MigrateDependencies( Project project, ProjectRootElement output, NuGetFramework framework, IEnumerable<ProjectLibraryDependency> dependencies, ProjectRootElement xproj) { var projectDependencies = new HashSet<string>(GetAllProjectReferenceNames(project, framework, xproj)); var packageDependencies = dependencies.Where(d => !projectDependencies.Contains(d.Name)); string condition = framework?.GetMSBuildCondition() ?? ""; var itemGroup = output.ItemGroups.FirstOrDefault(i => i.Condition == condition) ?? output.AddItemGroup(); itemGroup.Condition = condition; foreach (var packageDependency in packageDependencies) { MigrationTrace.Instance.WriteLine(packageDependency.Name); AddItemTransform<ProjectLibraryDependency> transform; if (packageDependency.LibraryRange.TypeConstraint == LibraryDependencyTarget.Reference) { transform = FrameworkDependencyTransform; } else { transform = PackageDependencyTransform(); if (packageDependency.Type.Equals(LibraryDependencyType.Build)) { transform = transform.WithMetadata("PrivateAssets", "All"); } else if (packageDependency.SuppressParent != LibraryIncludeFlagUtils.DefaultSuppressParent) { var metadataValue = ReadLibraryIncludeFlags(packageDependency.SuppressParent); transform = transform.WithMetadata("PrivateAssets", metadataValue); } if (packageDependency.IncludeType != LibraryIncludeFlags.All) { var metadataValue = ReadLibraryIncludeFlags(packageDependency.IncludeType); transform = transform.WithMetadata("IncludeAssets", metadataValue); } } _transformApplicator.Execute(transform.Transform(packageDependency), itemGroup); } } private string ReadLibraryIncludeFlags(LibraryIncludeFlags includeFlags) { if ((includeFlags ^ LibraryIncludeFlags.All) == 0) { return "All"; } if ((includeFlags ^ LibraryIncludeFlags.None) == 0) { return "None"; } var flagString = ""; var allFlagsAndNames = new List<Tuple<string, LibraryIncludeFlags>> { Tuple.Create("Analyzers", LibraryIncludeFlags.Analyzers), Tuple.Create("Build", LibraryIncludeFlags.Build), Tuple.Create("Compile", LibraryIncludeFlags.Compile), Tuple.Create("ContentFiles", LibraryIncludeFlags.ContentFiles), Tuple.Create("Native", LibraryIncludeFlags.Native), Tuple.Create("Runtime", LibraryIncludeFlags.Runtime) }; foreach (var flagAndName in allFlagsAndNames) { var name = flagAndName.Item1; var flag = flagAndName.Item2; if ((includeFlags & flag) == flag) { if (!string.IsNullOrEmpty(flagString)) { flagString += ";"; } flagString += name; } } return flagString; } private IEnumerable<string> GetAllProjectReferenceNames(Project project, NuGetFramework framework, ProjectRootElement xproj) { var csprojReferenceItems = _projectDependencyFinder.ResolveXProjProjectDependencies(xproj); var migratedXProjDependencyPaths = csprojReferenceItems.SelectMany(p => p.Includes()); var migratedXProjDependencyNames = new HashSet<string>(migratedXProjDependencyPaths.Select(p => Path.GetFileNameWithoutExtension( PathUtility.GetPathWithDirectorySeparator(p)))); var projectDependencies = _projectDependencyFinder.ResolveProjectDependenciesForFramework( project, framework, preResolvedProjects: migratedXProjDependencyNames); return projectDependencies.Select(p => p.Name).Concat(migratedXProjDependencyNames); } private AddItemTransform<ProjectLibraryDependency> FrameworkDependencyTransform => new AddItemTransform<ProjectLibraryDependency>( "Reference", dep => dep.Name, dep => "", dep => true); private Func<AddItemTransform<ProjectLibraryDependency>> PackageDependencyTransform => () => new AddItemTransform<ProjectLibraryDependency>( "PackageReference", dep => dep.Name, dep => "", dep => true) .WithMetadata("Version", r => r.LibraryRange.VersionRange.OriginalString); private AddItemTransform<PackageDependencyInfo> PackageDependencyInfoTransform => new AddItemTransform<PackageDependencyInfo>( "PackageReference", dep => dep.Name, dep => "", dep => true) .WithMetadata("Version", r => r.Version) .WithMetadata("PrivateAssets", r => r.PrivateAssets, r => !string.IsNullOrEmpty(r.PrivateAssets)); private AddItemTransform<ProjectLibraryDependency> ToolTransform => new AddItemTransform<ProjectLibraryDependency>( "DotNetCliToolReference", dep => dep.Name, dep => "", dep => true) .WithMetadata("Version", r => r.LibraryRange.VersionRange.OriginalString); private AddPropertyTransform<TargetFrameworkInformation> ImportsTransformation => new AddPropertyTransform<TargetFrameworkInformation>( "PackageTargetFallback", t => $"$(PackageTargetFallback);{string.Join(";", t.Imports)}", t => t.Imports.OrEmptyIfNull().Any()); private class PackageDependencyInfo { public string Name {get; set;} public string Version {get; set;} public string PrivateAssets {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. /*============================================================ ** ** ** ** ** ** Purpose: Searches for resources in Assembly manifest, used ** for assembly-based resource lookup. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Diagnostics; using Microsoft.Win32; // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // internal partial class ManifestBasedResourceGroveler : IResourceGroveler { private ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. Debug.Assert(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; Assembly satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); // 2. Look for satellite assembly or main assembly, as appropriate if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { // don't bother looking in satellites in this case satellite = _mediator.MainAssembly; } else { satellite = GetSatelliteAssembly(lookForCulture); if (satellite == null) { bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)); // didn't find satellite, give error if necessary if (raiseException) { HandleSatelliteMissing(); } } } // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. string fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) { // Handle case in here where someone added a callback for assembly load events. // While no other threads have called into GetResourceSet, our own thread can! // At that point, we could already have an RS in our hash table, and we don't // want to add it twice. lock (localResourceSets) { localResourceSets.TryGetValue(culture.Name, out rs); } stream = GetManifestResourceStream(satellite, fileName); } // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) { // 4b. Didn't find stream; give error if necessary bool raiseException = culture.HasInvariantCultureName; if (raiseException) { HandleResourceStreamMissing(fileName); } } return rs; } private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { CultureInfo returnCulture = lookForCulture; // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { returnCulture = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { returnCulture = _mediator.NeutralResourcesCulture; } return returnCulture; } internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, out UltimateResourceFallbackLocation fallbackLocation) { Debug.Assert(a != null, "assembly != null"); var attr = a.GetCustomAttribute<NeutralResourcesLanguageAttribute>(); if (attr == null) { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } fallbackLocation = attr.Location; if (fallbackLocation < UltimateResourceFallbackLocation.MainAssembly || fallbackLocation > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, fallbackLocation)); } try { return CultureInfo.GetCultureInfo(attr.CultureName); } catch (ArgumentException e) { // we should catch ArgumentException only. // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. if (a == typeof(object).Assembly) { Debug.Fail(System.CoreLib.Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + attr.CultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_Asm_Culture, a, attr.CultureName), e); } } // Constructs a new ResourceSet for a given file name. // Use the assembly to resolve assembly manifest resource references. // Note that is can be null, but probably shouldn't be. // This method could use some refactoring. One thing at a time. internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { Debug.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) { long startPos = store.Position; // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); // Look for our magic number as a little endian int. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); string readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); } else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber) { // Assume that the future ResourceManager headers will // have two strings for us - the reader type name and // resource set type name. Read those, then use the num // bytes to skip field to correct our position. int numBytesToSkip = br.ReadInt32(); long endPosition = br.BaseStream.Position + numBytesToSkip; readerTypeName = br.ReadString(); resSetTypeName = br.ReadString(); br.BaseStream.Seek(endPosition, SeekOrigin.Begin); } else { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name)); } store.Position = startPos; // Perf optimization - Don't use Reflection for our defaults. // Note there are two different sets of strings here - the // assembly qualified strings emitted by ResourceWriter, and // the abbreviated ones emitted by InternalResGen. if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName)) { return new RuntimeResourceSet(store, permitDeserialization: true); } else { Type readerType = Type.GetType(readerTypeName, throwOnError: true); object[] args = new object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); object[] resourceSetArgs = new object[1]; resourceSetArgs[0] = reader; Type resSetType; if (_mediator.UserResourceSet == null) { Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else resSetType = _mediator.UserResourceSet; ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, null); return rs; } } else { store.Position = startPos; } } if (_mediator.UserResourceSet == null) { return new RuntimeResourceSet(store, permitDeserialization:true); } else { object[] args = new object[2]; args[0] = store; args[1] = assembly; try { ResourceSet rs = null; // Add in a check for a constructor taking in an assembly first. try { rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException) { } args = new object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException e) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e); } } } private Stream GetManifestResourceStream(Assembly satellite, string fileName) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(fileName != null, "fileName shouldn't be null; check caller"); Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } return stream; } // Looks up a .resources file in the assembly manifest using // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) { Debug.Assert(satellite != null, "satellite shouldn't be null; check caller"); Debug.Assert(name != null, "name shouldn't be null; check caller"); string nameSpace = _mediator.LocationInfo?.Namespace; char c = Type.Delimiter; string resourceName = nameSpace != null && name != null ? string.Concat(nameSpace, new ReadOnlySpan<char>(ref c, 1), name) : string.Concat(nameSpace, name); string canonicalName = null; foreach (string existingName in satellite.GetManifestResourceNames()) { if (string.Equals(existingName, resourceName, StringComparison.InvariantCultureIgnoreCase)) { if (canonicalName == null) { canonicalName = existingName; } else { throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_MultipleBlobs, resourceName, satellite.ToString())); } } } if (canonicalName == null) { return null; } return satellite.GetManifestResourceStream(canonicalName); } private Assembly GetSatelliteAssembly(CultureInfo lookForCulture) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } Assembly satellite = null; // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. try { satellite = InternalGetSatelliteAssembly(_mediator.MainAssembly, lookForCulture, _mediator.SatelliteContractVersion); } catch (FileLoadException) { } catch (BadImageFormatException) { // Don't throw for zero-length satellite assemblies, for compat with v1 } return satellite; } // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can avoid // creating a ResourceReader via Reflection. This would incur // a security check (since the link-time check on the constructor that // takes a String is turned into a full demand with a stack walk) // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(string readerTypeName, string resSetTypeName) { Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; // Ignore the actual version of the ResourceReader and // RuntimeResourceSet classes. Let those classes deal with // versioning themselves. if (readerTypeName != null) { if (!ResourceManager.IsDefaultType(readerTypeName, ResourceManager.ResReaderTypeName)) return false; } if (resSetTypeName != null) { if (!ResourceManager.IsDefaultType(resSetTypeName, ResourceManager.ResSetTypeName)) return false; } return true; } private void HandleSatelliteMissing() { string satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); } byte[] token = _mediator.MainAssembly.GetName().GetPublicKeyToken(); int iLen = token.Length; StringBuilder publicKeyTok = new StringBuilder(iLen * 2); for (int i = 0; i < iLen; i++) { publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture)); } satAssemName += ", PublicKeyToken=" + publicKeyTok; string missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = "<invariant>"; } throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } private void HandleResourceStreamMissing(string fileName) { // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. Debug.Fail("Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; System.Environment.FailFast(mesgFailFast); } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. string resName = string.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_NoNeutralAsm, resName, _mediator.MainAssembly.GetName().Name)); } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Xml; using System.IO; using System.Collections; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Calendar { ////////////////////////////////////////////////////////////////////// /// <summary> /// CalendarEntry API customization class for defining entries in a calendar feed. /// </summary> ////////////////////////////////////////////////////////////////////// public class CalendarEntry : AbstractEntry { /// <summary> /// Constructs a new CalenderEntry instance /// </summary> public CalendarEntry() : base() { this.AddExtension(new GCalHidden()); this.AddExtension(new GCalColor()); this.AddExtension(new GCalSelected()); this.AddExtension(new GCalAccessLevel()); this.AddExtension(new Where()); this.AddExtension(new TimeZone()); } /// <summary> /// Basic method for retrieving Calendar extension elements. /// </summary> /// <param name="extension">The name of the extension element to look for</param> /// <returns>SimpleAttribute, or NULL if the extension was not found</returns> public SimpleAttribute getCalendarExtension(string extension) { return FindExtension(extension, GDataParserNameTable.NSGCal) as SimpleAttribute; } /// <summary> /// Base method for retrieving Calendar extension element values. /// </summary> /// <param name="extension">The name of the Calendar extension element to look for</param> /// <returns>value as string, or NULL if the extension was not found</returns> public string getCalendarExtensionValue(string extension) { SimpleAttribute e = getCalendarExtension(extension); if (e != null) { return (string) e.Value; } return null; } /// <summary> /// Base method for setting Calendar extension element values. /// </summary> /// <param name="extension">the name of the extension to look for</param> /// <param name="newValue">the new value for this extension element</param> /// <returns>SimpleAttribute, either a brand new one, or the one /// returned by the service</returns> public SimpleElement setCalendarExtension(string extension, string newValue) { if (extension == null) { throw new System.ArgumentNullException("extension"); } SimpleAttribute ele = getCalendarExtension(extension); if (ele == null) { ele = CreateExtension(extension, GDataParserNameTable.NSGCal) as SimpleAttribute; this.ExtensionElements.Add(ele); } ele.Value = newValue; return ele; } /// <summary> /// This field tells if the calendar is currently hidden in the UI list /// </summary> public bool Hidden { get { bool value; if (!bool.TryParse(getCalendarExtensionValue(GDataParserNameTable.XmlHiddenElement), out value)) { value = false; } return value; } set { setCalendarExtension(GDataParserNameTable.XmlHiddenElement, Utilities.ConvertBooleanToXSDString(value)); } } /// <summary> /// This field tells if the calendar is currently selected in the UI /// </summary> public bool Selected { get { bool value; if (!bool.TryParse(getCalendarExtensionValue(GDataParserNameTable.XmlSelectedElement), out value)) { value = false; } return value; } set { setCalendarExtension(GDataParserNameTable.XmlSelectedElement, Utilities.ConvertBooleanToXSDString(value)); } } /// <summary> /// This field manages the color of the calendar. /// </summary> public string Color { get { return getCalendarExtensionValue(GDataParserNameTable.XmlColorElement); } set { setCalendarExtension(GDataParserNameTable.XmlColorElement, value); } } /// <summary> /// This field deals with the access level of the current user on the calendar. /// </summary> public string AccessLevel { get { return getCalendarExtensionValue(GDataParserNameTable.XmlAccessLevelElement); } } /// <summary> /// This field controls the time zone of the calendar. /// </summary> public string TimeZone { get { return getCalendarExtensionValue(GDataParserNameTable.XmlTimeZoneElement); } set { setCalendarExtension(GDataParserNameTable.XmlTimeZoneElement, value); } } /// <summary> /// This field controls the location of the calendar. /// </summary> public Where Location { get { return FindExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace) as Where; } set { ReplaceExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace, value); } } } /// <summary> /// Color schema describing a gCal:color /// </summary> public class GCalColor : SimpleAttribute { /// <summary> /// default calendar color constructor /// </summary> public GCalColor() : base(GDataParserNameTable.XmlColorElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal) { } /// <summary> /// default calendar color constructor with an initial value /// </summary> /// <param name="initValue"></param> public GCalColor(string initValue) : base(GDataParserNameTable.XmlColorElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal, initValue) { } } /// <summary> /// Color schema describing a gCal:hidden /// </summary> public class GCalHidden : SimpleAttribute { /// <summary> /// default calendar hidden constructor /// </summary> public GCalHidden() : base(GDataParserNameTable.XmlHiddenElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal) { } /// <summary> /// default calendar hidden constructor with an initial value /// </summary> /// <param name="initValue"></param> public GCalHidden(string initValue) : base(GDataParserNameTable.XmlHiddenElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal, initValue) { } } /// <summary> /// Color schema describing a gCal:selected /// </summary> public class GCalSelected : SimpleAttribute { /// <summary> /// default calendar selected constructor /// </summary> public GCalSelected() : base(GDataParserNameTable.XmlSelectedElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal) { } /// <summary> /// default calendar selected constructor with an initial value /// </summary> /// <param name="initValue"></param> public GCalSelected(string initValue) : base(GDataParserNameTable.XmlSelectedElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal, initValue) { } } /// <summary> /// Color schema describing a gCal:accesslevel /// </summary> public class GCalAccessLevel : SimpleAttribute { /// <summary> /// default calendar access level constructor /// </summary> public GCalAccessLevel() : base(GDataParserNameTable.XmlAccessLevelElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal) { } /// <summary> /// default calendar acccess level /// constructor with an initial value /// </summary> /// <param name="initValue"></param> public GCalAccessLevel(string initValue) : base(GDataParserNameTable.XmlAccessLevelElement, GDataParserNameTable.gCalPrefix, GDataParserNameTable.NSGCal, initValue) { } } }
// 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; using System; using System.Reflection; using System.Collections.Generic; #pragma warning disable 0414 #pragma warning disable 0067 namespace System.Reflection.Tests { [System.Runtime.InteropServices.Guid("FD80F123-BEDD-4492-B50A-5D46AE94DD4E")] public class TypeInfoPropertyTests { // Verify BaseType() method [Fact] public static void TestBaseType1() { Type t = typeof(TypeInfoPropertyDerived); TypeInfo ti = t.GetTypeInfo(); Type basetype = ti.BaseType; Assert.Equal(basetype, typeof(TypeInfoPropertyBase)); } // Verify BaseType() method [Fact] public static void TestBaseType2() { Type t = typeof(TypeInfoPropertyBase); TypeInfo ti = t.GetTypeInfo(); Type basetype = ti.BaseType; Assert.Equal(basetype, typeof(object)); } // Verify ContainsGenericParameter [Fact] public static void TestContainsGenericParameter1() { Type t = typeof(ClassWithConstraints<,>); TypeInfo ti = t.GetTypeInfo(); bool hasgenericParam = ti.ContainsGenericParameters; Assert.True(hasgenericParam, String.Format("Failed!! TestContainsGenericParameter did not return correct result. ")); } // Verify ContainsGenericParameter [Fact] public static void TestContainsGenericParameter2() { Type t = typeof(TypeInfoPropertyBase); TypeInfo ti = t.GetTypeInfo(); bool hasgenericParam = ti.ContainsGenericParameters; Assert.False(hasgenericParam, String.Format("Failed!! TestContainsGenericParameter did not return correct result. ")); } // Verify FullName [Fact] public static void TestFullName() { Type t = typeof(int); TypeInfo ti = t.GetTypeInfo(); string fname = ti.FullName; Assert.Equal(fname, "System.Int32"); } // Verify Guid [Fact] public static void TestGuid() { Type t = typeof(TypeInfoPropertyTests); TypeInfo ti = t.GetTypeInfo(); Guid myguid = ti.GUID; Assert.NotNull(myguid); } // Verify HasElementType [Fact] public static void TestHasElementType() { Type t = typeof(int); TypeInfo ti = t.GetTypeInfo(); Assert.False(ti.HasElementType, "Failed!! .HasElementType returned true for a type that does not contain element "); int[] nums = { 1, 1, 2, 3 }; Type te = nums.GetType(); TypeInfo tei = te.GetTypeInfo(); Assert.True(tei.HasElementType, "Failed!! .HasElementType returned false for a type that contains element "); } //Verify IsAbstract [Fact] public static void TestIsAbstract() { Assert.True(typeof(abstractClass).GetTypeInfo().IsAbstract, "Failed!! .IsAbstract returned false for a type that is abstract."); Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsAbstract, "Failed!! .IsAbstract returned true for a type that is not abstract."); } //Verify IsAnsiClass [Fact] public static void TestIsAnsiClass() { String mystr = "A simple string"; Type t = mystr.GetType(); TypeInfo ti = t.GetTypeInfo(); Assert.True(ti.IsAnsiClass, "Failed!! .IsAnsiClass returned false."); } //Verify IsArray [Fact] public static void TestIsArray() { int[] myarray = { 1, 2, 3 }; Type arraytype = myarray.GetType(); Assert.True(arraytype.GetTypeInfo().IsArray, "Failed!! .IsArray returned false for a type that is array."); Assert.False(typeof(int).GetTypeInfo().IsArray, "Failed!! .IsArray returned true for a type that is not an array."); } // VerifyIsByRef [Fact] public static void TestIsByRefType() { TypeInfo ti = typeof(Int32).GetTypeInfo(); Type byreftype = ti.MakeByRefType(); Assert.NotNull(byreftype); Assert.True(byreftype.IsByRef, "Failed!! IsByRefType() returned false"); Assert.False(typeof(int).GetTypeInfo().IsByRef, "Failed!! IsByRefType() returned true"); } // VerifyIsClass [Fact] public static void TestIsClass() { Assert.True(typeof(TypeInfoPropertyBase).GetTypeInfo().IsClass, "Failed!! IsClass returned false for a class Type"); Assert.False(typeof(MYENUM).GetTypeInfo().IsClass, "Failed!! IsClass returned true for a non-class Type"); } // VerifyIsEnum [Fact] public static void TestIsEnum() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsEnum, "Failed!! IsEnum returned true for a class Type"); Assert.True(typeof(MYENUM).GetTypeInfo().IsEnum, "Failed!! IsEnum returned false for a Enum Type"); } // VerifyIsInterface [Fact] public static void TestIsInterface() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsInterface, "Failed!! IsInterface returned true for a class Type"); Assert.True(typeof(ITest).GetTypeInfo().IsInterface, "Failed!! IsInterface returned false for a interface Type"); } // VerifyIsNested [Fact] public static void TestIsNested() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsNested, "Failed!! IsNested returned true for a non nested class Type"); Assert.True(typeof(PublicClass.PublicNestedType).GetTypeInfo().IsNested, "Failed!! IsNested returned false for a nested class Type"); } // Verify IsPointer [Fact] public static void TestIsPointer() { TypeInfo ti = typeof(Int32).GetTypeInfo(); Type ptrtype = ti.MakePointerType(); Assert.NotNull(ptrtype); Assert.True(ptrtype.IsPointer, "Failed!! IsPointer returned false for pointer type"); Assert.False(typeof(int).GetTypeInfo().IsPointer, "Failed!! IsPointer returned true for non -pointer type"); } // VerifyIsPrimitive [Fact] public static void TestIsPrimitive() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a non primitive Type"); Assert.True(typeof(int).GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a primitive Type"); Assert.True(typeof(char).GetTypeInfo().IsPrimitive, "Failed!! IsPrimitive returned true for a primitive Type"); } // VerifyIsPublic [Fact] public static void TestIsPublic() { Assert.True(typeof(TypeInfoPropertyBase).GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(TypeInfoPropertyDerived).GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(PublicClass).GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(ITest).GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); Assert.True(typeof(ImplClass).GetTypeInfo().IsPublic, "Failed!! IsPublic returned false for a public Type"); } // VerifyIsNotPublic [Fact] public static void TestIsNotPublic() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(TypeInfoPropertyDerived).GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(PublicClass).GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(ITest).GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); Assert.False(typeof(ImplClass).GetTypeInfo().IsNotPublic, "Failed!! IsNotPublic returned false for a public Type"); } // VerifyIsNestedPublic [Fact] public static void TestIsNestedPublic() { Assert.True(typeof(PublicClass.publicNestedClass).GetTypeInfo().IsNestedPublic, "Failed!! IsNestedPublic returned false for a nested public Type"); } // VerifyIsNestedPrivate [Fact] public static void TestIsNestedPrivate() { Assert.False(typeof(PublicClass.publicNestedClass).GetTypeInfo().IsNestedPrivate, "Failed!! IsNestedPrivate returned true for a nested public Type"); } // Verify IsSealed [Fact] public static void TestIsSealed() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsSealed, "Failed!! IsSealed returned true for a Type that is not sealed"); Assert.True(typeof(sealedClass).GetTypeInfo().IsSealed, "Failed!! IsSealed returned false for a Type that is sealed"); } // Verify IsSerializable [Fact] public static void TestIsSerializable() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsSerializable, "Failed!! IsSerializable returned true for a Type that is not serializable"); } // VerifyIsValueType [Fact] public static void TestIsValueType() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsValueType, "Failed!! IsValueType returned true for a class Type"); Assert.True(typeof(MYENUM).GetTypeInfo().IsValueType, "Failed!! IsValueType returned false for a Enum Type"); } // VerifyIsValueType [Fact] public static void TestIsVisible() { Assert.True(typeof(TypeInfoPropertyBase).GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(ITest).GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(MYENUM).GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(PublicClass).GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); Assert.True(typeof(PublicClass.publicNestedClass).GetTypeInfo().IsVisible, "Failed!! IsVisible returned false"); } // Verify Namespace property [Fact] public static void TestNamespace() { Assert.Equal(typeof(TypeInfoPropertyBase).GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(ITest).GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(MYENUM).GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(PublicClass).GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(PublicClass.publicNestedClass).GetTypeInfo().Namespace, "System.Reflection.Tests"); Assert.Equal(typeof(int).GetTypeInfo().Namespace, "System"); } // VerifyIsImport [Fact] public static void TestIsImport() { Assert.False(typeof(TypeInfoPropertyBase).GetTypeInfo().IsImport, "Failed!! IsImport returned true for a class Type that is not imported."); Assert.False(typeof(MYENUM).GetTypeInfo().IsImport, "Failed!! IsImport returned true for a non-class Type that is not imported."); } // VerifyIsUnicodeClass [Fact] public static void TestIsUnicodeClass() { String str = "mystring"; Type type = str.GetType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsUnicodeClass, "Failed!! IsUnicodeClass returned true for string."); Assert.False(ref_type.GetTypeInfo().IsUnicodeClass, "Failed!! IsUnicodeClass returned true for string."); } // Verify IsAutoClass [Fact] public static void TestIsAutoClass() { String str = "mystring"; Type type = str.GetType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsAutoClass, "Failed!! IsAutoClass returned true for string."); Assert.False(ref_type.GetTypeInfo().IsAutoClass, "Failed!! IsAutoClass returned true for string."); } [Fact] public static void TestIsMarshalByRef() { String str = "mystring"; Type type = str.GetType(); Type ptr_type = type.MakePointerType(); Type ref_type = type.MakeByRefType(); Assert.False(type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); Assert.False(ptr_type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); Assert.False(ref_type.GetTypeInfo().IsMarshalByRef, "Failed!! IsMarshalByRef returned true."); } // VerifyIsNestedAssembly [Fact] public static void TestIsNestedAssembly() { Assert.False(typeof(PublicClass).GetTypeInfo().IsNestedAssembly, "Failed!! IsNestedAssembly returned true for a class with public visibility."); } // VerifyIsNestedFamily [Fact] public static void TestIsNestedFamily() { Assert.False(typeof(PublicClass).GetTypeInfo().IsNestedFamily, "Failed!! IsNestedFamily returned true for a class with private visibility."); } // VerifyIsNestedFamANDAssem [Fact] public static void TestIsNestedFamAndAssem() { Assert.False(typeof(PublicClass).GetTypeInfo().IsNestedFamANDAssem, "Failed!! IsNestedFamAndAssem returned true for a class with private visibility."); } // VerifyIsNestedFamOrAssem [Fact] public static void TestIsNestedFamOrAssem() { Assert.False(typeof(PublicClass).GetTypeInfo().IsNestedFamORAssem, "Failed!! IsNestedFamOrAssem returned true for a class with private visibility."); } } //Metadata for Reflection public class PublicClass { public int PublicField; public static int PublicStaticField; public PublicClass() { } public void PublicMethod() { } public void overRiddenMethod() { } public void overRiddenMethod(int i) { } public void overRiddenMethod(string s) { } public void overRiddenMethod(Object o) { } public static void PublicStaticMethod() { } public class PublicNestedType { } public int PublicProperty { get { return default(int); } set { } } public class publicNestedClass { } } public sealed class sealedClass { } public abstract class abstractClass { } public interface ITest { } public class TypeInfoPropertyBase { } public class TypeInfoPropertyDerived : TypeInfoPropertyBase { } public class ImplClass : ITest { } public class TypeInfoPropertyGenericClass<T> { } public class ClassWithConstraints<T, U> where T : TypeInfoPropertyBase, ITest where U : class, new() { } public enum MYENUM { one = 1, Two = 2 } }
using System; using System.Reflection; using KSP.Localization; using UnityEngine; namespace Starstrider42.CustomAsteroids { /// <summary> /// Represents the types of spawning behaviour supported by Custom Asteroids. /// </summary> internal enum SpawnerType { Stock, FixedRate } /// <summary> /// Stores a set of configuration options for Custom Asteroids. ConfigNodes are used to manage /// option persistence. /// </summary> internal class Options { /// <summary>Whether or not make to asteroid names match their population.</summary> [Persistent (name = "RenameAsteroids")] bool renameAsteroids; /// <summary>The spawner to use for creating and removing asteroids.</summary> [Persistent (name = "Spawner")] SpawnerType spawner; /// <summary> /// Whether or not to report failed asteroid spawns in the game. /// The errors will be logged regardless. /// </summary> [Persistent (name = "ErrorsOnScreen")] bool errorsOnScreen; /// <summary>Minimum number of days an asteroid goes untracked.</summary> [Persistent (name = "MinUntrackedTime")] float minUntrackedLifetime; /// <summary>Maximum number of days an asteroid goes untracked.</summary> [Persistent (name = "MaxUntrackedTime")] float maxUntrackedLifetime; /// <summary>The plugin version for which the settings file was written.</summary> [Persistent (name = "VersionNumber")] string versionNumber; /// <summary> /// Sets all options to their default values. Does not throw exceptions. /// </summary> Options () { versionNumber = latestVersion (); renameAsteroids = true; minUntrackedLifetime = 1.0f; maxUntrackedLifetime = 20.0f; spawner = SpawnerType.FixedRate; errorsOnScreen = true; } /// <summary> /// Stores current Custom Asteroids options in a config file. The version is stored as well. /// The program is in a consistent state in the event of an exception. /// </summary> internal void save () { // File may have been loaded from a previous version string trueVersion = versionNumber; try { versionNumber = latestVersion (); var parentNode = new ConfigNode (); ConfigNode allData = parentNode.AddNode ("CustomAsteroidSettings"); ConfigNode.CreateConfigFromObject (this, allData); // Only overload that works! // Create directories if necessary var outFile = new System.IO.FileInfo (optionFile ()); System.IO.Directory.CreateDirectory (outFile.DirectoryName); parentNode.Save (outFile.FullName); Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOptionsSave")); } finally { versionNumber = trueVersion; } } /// <summary> /// Factory method obtaining Custom Asteroids settings from a config file. Will not throw /// exceptions. /// </summary> /// <returns>A newly constructed Options object containing up-to-date settings from the /// Custom Asteroids config file, or the default settings if no such file exists or the /// file is corrupted.</returns> internal static Options load () { try { Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOptionsLoad1")); Options allOptions = loadNewStyleOptions (); if (allOptions == null) { allOptions = loadOldStyleOptions (); } if (allOptions.versionNumber != latestVersion ()) { // Config file is either missing or out of date, make a new one // Any information loaded from previous config file will be preserved updateOptionFile (allOptions); } Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOptionsLoad2")); return allOptions; } catch (ArgumentException e) { Debug.LogError ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOptionsNoLoad")); Debug.LogException (e); ScreenMessages.PostScreenMessage ( "[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_ErrorBasic", "#autoLOC_CustomAsteroids_LogOptionsNoLoad", e.Message), 10.0f, ScreenMessageStyle.UPPER_CENTER); return new Options (); } catch { return new Options (); } } /// <summary> /// Reads a modern (MM-compatible) options file. /// </summary> /// <returns>The options stored in the game databse, or <c>null</c> if none were /// found.</returns> /// <exception cref="ArgumentException">Thrown if there is a syntax error in one of the /// options.</exception> static Options loadNewStyleOptions () { UrlDir.UrlConfig [] configList = GameDatabase.Instance.GetConfigs ("CustomAsteroidSettings"); if (configList.Length > 0) { // Start with the default options var options = new Options (); foreach (UrlDir.UrlConfig settings in configList) { ConfigNode.LoadObjectFromConfig (options, settings.config); } return options; } return null; } /// <summary> /// Reads a pre-MM options file. /// </summary> /// <returns>The options in <c>oldOptionFile()</c>, or the default for any unspecified /// option. The <c>versionNumber</c> field shall contain the version number /// of the options file, or "" if no such file exists.</returns> /// <exception cref="ArgumentException">Thrown if there is a syntax error in /// the options file.</exception> static Options loadOldStyleOptions () { // Start with the default options var options = new Options (); ConfigNode optFile = ConfigNode.Load (oldOptionFile ()); if (optFile != null) { ConfigNode.LoadObjectFromConfig (options, optFile); // Backward-compatible with initial release if (!optFile.HasValue ("VersionNumber")) { options.versionNumber = "0.1.0"; } // Backward-compatible with versions 1.1.0 and earlier if (!optFile.HasValue ("Spawner") && optFile.HasValue ("UseCustomSpawner")) { options.spawner = optFile.GetValue ("UseCustomSpawner").Equals ("False") ? SpawnerType.Stock : SpawnerType.FixedRate; } } else { options.versionNumber = ""; } return options; } /// <summary> /// Replaces a missing or out-of-date preferences file. Failures to write the file to disk /// are logged and ignored. /// </summary> /// <param name="oldData">The data to store in the new file.</param> static void updateOptionFile (Options oldData) { try { oldData.save (); if (oldData.versionNumber.Length == 0) { Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogNoOptions", optionFile ())); } else { Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOldOptions", oldData.versionNumber, latestVersion ())); } } catch (Exception e) { Debug.LogError ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOptionsNoSave")); Debug.LogException (e); } } /// <summary> /// Returns whether or not asteroids may be renamed by their population. Does not throw /// exceptions. /// </summary> /// <returns><c>true</c> if renaming allowed, <c>false</c> otherwise.</returns> internal bool getRenameOption () { return renameAsteroids; } /// <summary> /// Returns the spawner chosen in the settings. Does not throw exceptions. /// </summary> /// <returns>The spawner.</returns> internal SpawnerType getSpawner () { return spawner; } /// <summary> /// Returns whether or not asteroid spawning errors should appear in the game. Does not /// throw exceptions. /// </summary> /// <returns><c>true</c> if errors should be put on screen, <c>false</c> if logged /// only.</returns> internal bool getErrorReporting () { return errorsOnScreen; } /// <summary> /// Returns the time range in which untracked asteroids will disappear. The program state /// is unchanged in the event of an exception. /// </summary> /// <returns>The minimum (<c>first</c>) and maximum (<c>second</c>) number of days an /// asteroid can go untracked.</returns> /// <exception cref="InvalidOperationException">Thrown if <c>first</c> is negative, /// <c>second</c> is nonpositive, /// or <c>first &gt; second</c>.</exception> internal Tuple<float, float> getUntrackedTimes () { if (minUntrackedLifetime < 0.0f) { throw new InvalidOperationException ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorOptionsBadMin", minUntrackedLifetime)); } if (maxUntrackedLifetime <= 0.0f) { throw new InvalidOperationException ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorOptionsBadMax", maxUntrackedLifetime)); } if (maxUntrackedLifetime < minUntrackedLifetime) { throw new InvalidOperationException ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorOptionsBadRange", minUntrackedLifetime, maxUntrackedLifetime)); } return Tuple.Create (minUntrackedLifetime, maxUntrackedLifetime); } /// <summary> /// Identifies the version 1.4 and earlier Custom Asteroids config file. Does not throw /// exceptions. /// </summary> /// <returns>An absolute path to the config file.</returns> static string oldOptionFile () { return KSPUtil.ApplicationRootPath + "GameData/CustomAsteroids/PluginData/Custom Asteroids Settings.cfg"; } /// <summary> /// Identifies the MM-compatible Custom Asteroids config file. Does not throw exceptions. /// </summary> /// <returns>An absolute path to the config file.</returns> static string optionFile () { return KSPUtil.ApplicationRootPath + "GameData/CustomAsteroids/Custom Asteroids Settings.cfg"; } /// <summary> /// Returns the mod's current version number. Does not throw exceptions. /// </summary> /// <returns>A version number in major.minor.patch form.</returns> static string latestVersion () { return Assembly.GetExecutingAssembly ().GetName ().Version.ToString (3); } } }
// Copyright (c) 2015 James Liu // // See the LISCENSE file for copying permission. using System.Collections.Generic; using UnityEngine; namespace Hourai.DanmakU { [ExecuteInEditMode] [DisallowMultipleComponent] [AddComponentMenu("Hourai.DanmakU/Danmaku Field")] public class DanmakuField : MonoBehaviour, IFireBindable { public enum CoordinateSystem { View, ViewRelative, Relative, World } private static List<DanmakuField> _fields; private static readonly Vector2 InfiniteSize = float.PositiveInfinity* Vector2.one; internal Bounds2D bounds; [SerializeField] private Camera camera2D; private Transform camera2DTransform; [SerializeField] private float clipBoundary = 1f; [SerializeField] private Vector2 fieldSize = new Vector2(20f, 20f); private Bounds2D movementBounds; [SerializeField] private List<Camera> otherCameras; [SerializeField] private bool useClipBoundary = true; public bool UseClipBoundary { get { return useClipBoundary; } set { useClipBoundary = value; } } public float ClipBoundary { get { return clipBoundary; } set { clipBoundary = value; } } public Vector2 FieldSize { get { return fieldSize; } set { fieldSize = value; } } public DanmakuField TargetField { get; set; } public Camera Camera2D { get { return camera2D; } set { camera2D = value; } } public List<Camera> OtherCameras { get { return otherCameras; } } public float Camera2DRotation { get { if (camera2D == null) return float.NaN; if (camera2DTransform == null) camera2DTransform = camera2D.transform; return camera2DTransform.eulerAngles.z; } set { camera2DTransform.rotation = Quaternion.Euler(0f, 0f, value); } } public Bounds2D Bounds { get { return bounds; } } public Bounds2D MovementBounds { get { return movementBounds; } } /// <summary> /// Finds the closest DanmakuField to a GameObject's position. /// </summary> /// <returns>The closest DanmakuField to the GameObject.</returns> /// <param name="gameObject">the GameObject used to find the closest DanmakuField.</param> public static DanmakuField FindClosest(GameObject gameObject) { return FindClosest(gameObject.transform.position); } /// <summary> /// Finds the closest DanmakuField to a Component's GameObject's position. /// </summary> /// <returns>The closest DanmakuField to the Component and it's GameObject.</returns> /// <param name="component">the Component used to find the closest DanmakuField.</param> public static DanmakuField FindClosest(Component component) { return FindClosest(component.transform.position); } /// <summary> /// Finds the closest DanmakuField to the point specified by a Transform's position. /// </summary> /// <returns>The closest DanmakuField to the Transform's position.</returns> /// <param name="transform">the Transform used to find the closest DanmakuField.</param> public static DanmakuField FindClosest(Transform transform) { return FindClosest(transform.position); } public static DanmakuField FindClosest(Vector2 position) { if (_fields == null) { _fields = new List<DanmakuField>(); _fields.AddRange(FindObjectsOfType<DanmakuField>()); } if (_fields.Count == 0) { DanmakuField encompassing = new GameObject("Danmaku Field").AddComponent<DanmakuField>(); encompassing.useClipBoundary = false; _fields.Add(encompassing); } if (_fields.Count == 1) return _fields[0]; DanmakuField closest = null; float minDist = float.MaxValue; foreach (var field in _fields) { Vector2 diff = field.bounds.Center - position; float distance = diff.sqrMagnitude; if (distance >= minDist) continue; closest = field; minDist = distance; } return closest; } public virtual void Awake() { if (_fields == null) _fields = new List<DanmakuField>(); _fields.Add(this); TargetField = this; } public virtual void Update() { if (camera2D != null) { camera2DTransform = camera2D.transform; camera2D.orthographic = true; movementBounds.Center = bounds.Center = camera2DTransform.position; float size = camera2D.orthographicSize; movementBounds.Extents = new Vector2(camera2D.aspect*size, size); foreach (Camera t in otherCameras) { if (t != null) t.rect = camera2D.rect; } } else { camera2DTransform = null; movementBounds.Center = bounds.Center = transform.position; movementBounds.Extents = fieldSize*0.5f; } if (useClipBoundary) { bounds.Extents = movementBounds.Extents + Vector2.one*clipBoundary* movementBounds.Extents.Max(); } else bounds.Extents = InfiniteSize; } private void OnDestroy() { if (_fields != null) _fields.Remove(this); } public Vector2 WorldPoint(Vector2 point, CoordinateSystem coordSys = CoordinateSystem.View) { switch (coordSys) { case CoordinateSystem.World: return point; case CoordinateSystem.Relative: return movementBounds.Min + point; case CoordinateSystem.ViewRelative: return point.Hadamard2(movementBounds.Size); default: return movementBounds.Min + point.Hadamard2(movementBounds.Size); } } public Vector2 RelativePoint(Vector2 point, CoordinateSystem coordSys = CoordinateSystem.View) { switch (coordSys) { case CoordinateSystem.World: return point - movementBounds.Min; case CoordinateSystem.Relative: return point; default: case CoordinateSystem.View: Vector2 size = movementBounds.Size; var inverse = new Vector2(1/size.x, 1/size.y); return (point - movementBounds.Min).Hadamard2(inverse); } } public Vector2 ViewPoint(Vector2 point, CoordinateSystem coordSys = CoordinateSystem.World) { Vector2 size = bounds.Size; switch (coordSys) { default: case CoordinateSystem.World: Vector2 offset = point - movementBounds.Min; return new Vector2(offset.x/size.x, offset.y/size.y); case CoordinateSystem.Relative: return new Vector2(point.x/size.x, point.y/size.y); case CoordinateSystem.View: return point; } } public GameObject SpawnGameObject(GameObject prefab, Vector2 location, CoordinateSystem coordSys = CoordinateSystem.View) { if (TargetField == null) TargetField = this; Quaternion rotation = prefab.transform.rotation; return Instantiate(gameObject, TargetField.WorldPoint(location, coordSys), rotation) as GameObject; } public T SpawnObject<T>(T prefab, Vector2 location, CoordinateSystem coordSys = CoordinateSystem.View) where T : Component { if (TargetField == null) TargetField = this; Quaternion rotation = prefab.transform.rotation; T clone = Instantiate(prefab, TargetField.WorldPoint(location, coordSys), rotation) as T; return clone; } #if UNITY_EDITOR private void OnDrawGizmos() { Gizmos.color = Color.yellow; Gizmos.DrawWireCube(bounds.Center, bounds.Size); Gizmos.color = Color.cyan; Gizmos.DrawWireCube(movementBounds.Center, movementBounds.Size); } #endif public void Bind(FireData fireData) { fireData.Controller += DestroyOnLeave; } public void Unbind(FireData fireData) { fireData.Controller -= DestroyOnLeave; } void DestroyOnLeave(Danmaku danmaku) { if (!bounds.Contains(danmaku.Position)) danmaku.Destroy(); } } }
// 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.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Data.SqlTypes; using System.Data.SqlClient; using System.Diagnostics; namespace Microsoft.SqlServer.Server { public class SqlDataRecord { private SmiRecordBuffer _recordBuffer; private SmiExtendedMetaData[] _columnSmiMetaData; private SmiEventSink_Default _eventSink; private SqlMetaData[] _columnMetaData; private FieldNameLookup _fieldNameLookup; private bool _usesStringStorageForXml; private static readonly SmiMetaData s_maxNVarCharForXml = new SmiMetaData(SqlDbType.NVarChar, SmiMetaData.UnlimitedMaxLengthIndicator, SmiMetaData.DefaultNVarChar_NoCollation.Precision, SmiMetaData.DefaultNVarChar_NoCollation.Scale, SmiMetaData.DefaultNVarChar.LocaleId, SmiMetaData.DefaultNVarChar.CompareOptions ); public virtual int FieldCount { get { EnsureSubclassOverride(); return _columnMetaData.Length; } } public virtual String GetName(int ordinal) { EnsureSubclassOverride(); return GetSqlMetaData(ordinal).Name; } public virtual String GetDataTypeName(int ordinal) { EnsureSubclassOverride(); SqlMetaData metaData = GetSqlMetaData(ordinal); if (SqlDbType.Udt == metaData.SqlDbType) { Debug.Assert(false, "Udt is not supported"); return null; } else { return MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, false).TypeName; } } public virtual Type GetFieldType(int ordinal) { EnsureSubclassOverride(); { SqlMetaData md = GetSqlMetaData(ordinal); return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).ClassType; } } public virtual Object GetValue(int ordinal) { EnsureSubclassOverride(); SmiMetaData metaData = GetSmiMetaData(ordinal); return ValueUtilsSmi.GetValue200( _eventSink, _recordBuffer, ordinal, metaData ); } public virtual int GetValues(object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull("values"); } int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount; for (int i = 0; i < copyLength; i++) { values[i] = GetValue(i); } return copyLength; } public virtual int GetOrdinal(string name) { EnsureSubclassOverride(); if (null == _fieldNameLookup) { string[] names = new string[FieldCount]; for (int i = 0; i < names.Length; i++) { names[i] = GetSqlMetaData(i).Name; } _fieldNameLookup = new FieldNameLookup(names, -1); } return _fieldNameLookup.GetOrdinal(name); } public virtual object this[int ordinal] { get { EnsureSubclassOverride(); return GetValue(ordinal); } } public virtual object this[String name] { get { EnsureSubclassOverride(); return GetValue(GetOrdinal(name)); } } public virtual bool GetBoolean(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual byte GetByte(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); return ValueUtilsSmi.GetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length, true); } public virtual char GetChar(int ordinal) { EnsureSubclassOverride(); throw ADP.NotSupported(); } public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); return ValueUtilsSmi.GetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual Guid GetGuid(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual Int16 GetInt16(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual Int32 GetInt32(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual Int64 GetInt64(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual float GetFloat(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual double GetDouble(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual string GetString(int ordinal) { EnsureSubclassOverride(); SmiMetaData colMeta = GetSmiMetaData(ordinal); if (_usesStringStorageForXml && SqlDbType.Xml == colMeta.SqlDbType) { return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, s_maxNVarCharForXml); } else { return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } } public virtual Decimal GetDecimal(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual DateTime GetDateTime(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual DateTimeOffset GetDateTimeOffset(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual TimeSpan GetTimeSpan(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual bool IsDBNull(int ordinal) { EnsureSubclassOverride(); ThrowIfInvalidOrdinal(ordinal); return ValueUtilsSmi.IsDBNull(_eventSink, _recordBuffer, ordinal); } // // ISqlRecord implementation // public virtual SqlMetaData GetSqlMetaData(int ordinal) { EnsureSubclassOverride(); return _columnMetaData[ordinal]; } public virtual Type GetSqlFieldType(int ordinal) { EnsureSubclassOverride(); SqlMetaData md = GetSqlMetaData(ordinal); return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).SqlType; } public virtual object GetSqlValue(int ordinal) { EnsureSubclassOverride(); SmiMetaData metaData = GetSmiMetaData(ordinal); return ValueUtilsSmi.GetSqlValue200(_eventSink, _recordBuffer, ordinal, metaData); } public virtual int GetSqlValues(object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull("values"); } int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount; for (int i = 0; i < copyLength; i++) { values[i] = GetSqlValue(i); } return copyLength; } public virtual SqlBinary GetSqlBinary(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlBytes GetSqlBytes(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlXml GetSqlXml(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlBoolean GetSqlBoolean(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlByte GetSqlByte(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlChars GetSqlChars(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt16 GetSqlInt16(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt32 GetSqlInt32(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt64 GetSqlInt64(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlSingle GetSqlSingle(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDouble GetSqlDouble(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlMoney GetSqlMoney(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDateTime GetSqlDateTime(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDecimal GetSqlDecimal(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlString GetSqlString(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlGuid GetSqlGuid(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } // // ISqlUpdateableRecord Implementation // public virtual int SetValues(params object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull("values"); } // Allow values array longer than FieldCount, just ignore the extra cells. int copyLength = (values.Length > FieldCount) ? FieldCount : values.Length; ExtendedClrTypeCode[] typeCodes = new ExtendedClrTypeCode[copyLength]; // Verify all data values as acceptable before changing current state. for (int i = 0; i < copyLength; i++) { SqlMetaData metaData = GetSqlMetaData(i); typeCodes[i] = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType( metaData.SqlDbType, false /* isMultiValued */, values[i] ); if (ExtendedClrTypeCode.Invalid == typeCodes[i]) { throw ADP.InvalidCast(); } } // Now move the data (it'll only throw if someone plays with the values array between // the validation loop and here, or if an invalid UDT was sent). for (int i = 0; i < copyLength; i++) { ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, i, GetSmiMetaData(i), values[i], typeCodes[i], 0, 0, null); } return copyLength; } public virtual void SetValue(int ordinal, object value) { EnsureSubclassOverride(); SqlMetaData metaData = GetSqlMetaData(ordinal); ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType( metaData.SqlDbType, false /* isMultiValued */, value ); if (ExtendedClrTypeCode.Invalid == typeCode) { throw ADP.InvalidCast(); } ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value, typeCode, 0, 0, null); } public virtual void SetBoolean(int ordinal, bool value) { EnsureSubclassOverride(); ValueUtilsSmi.SetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetByte(int ordinal, byte value) { EnsureSubclassOverride(); ValueUtilsSmi.SetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); ValueUtilsSmi.SetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual void SetChar(int ordinal, char value) { EnsureSubclassOverride(); throw ADP.NotSupported(); } public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); ValueUtilsSmi.SetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual void SetInt16(int ordinal, System.Int16 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetInt32(int ordinal, System.Int32 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetInt64(int ordinal, System.Int64 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetFloat(int ordinal, float value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDouble(int ordinal, double value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetString(int ordinal, string value) { EnsureSubclassOverride(); ValueUtilsSmi.SetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDecimal(int ordinal, Decimal value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDateTime(int ordinal, DateTime value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetTimeSpan(int ordinal, TimeSpan value) { EnsureSubclassOverride(); ValueUtilsSmi.SetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDateTimeOffset(int ordinal, DateTimeOffset value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDBNull(int ordinal) { EnsureSubclassOverride(); ValueUtilsSmi.SetDBNull(_eventSink, _recordBuffer, ordinal, true); } public virtual void SetGuid(int ordinal, Guid value) { EnsureSubclassOverride(); ValueUtilsSmi.SetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBoolean(int ordinal, SqlBoolean value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlByte(int ordinal, SqlByte value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt16(int ordinal, SqlInt16 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt32(int ordinal, SqlInt32 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt64(int ordinal, SqlInt64 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlSingle(int ordinal, SqlSingle value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDouble(int ordinal, SqlDouble value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlMoney(int ordinal, SqlMoney value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDateTime(int ordinal, SqlDateTime value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlXml(int ordinal, SqlXml value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDecimal(int ordinal, SqlDecimal value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlString(int ordinal, SqlString value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBinary(int ordinal, SqlBinary value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlGuid(int ordinal, SqlGuid value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlChars(int ordinal, SqlChars value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBytes(int ordinal, SqlBytes value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } // // SqlDataRecord public API // public SqlDataRecord(params SqlMetaData[] metaData) { // Initial consistency check if (null == metaData) { throw ADP.ArgumentNull("metadata"); } _columnMetaData = new SqlMetaData[metaData.Length]; _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length]; for (int i = 0; i < _columnSmiMetaData.Length; i++) { if (null == metaData[i]) { throw ADP.ArgumentNull("metadata[" + i + "]"); } _columnMetaData[i] = metaData[i]; _columnSmiMetaData[i] = MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(_columnMetaData[i]); } _eventSink = new SmiEventSink_Default(); _recordBuffer = new MemoryRecordBuffer(_columnSmiMetaData); _usesStringStorageForXml = true; _eventSink.ProcessMessagesAndThrow(); } internal SqlDataRecord(SmiRecordBuffer recordBuffer, params SmiExtendedMetaData[] metaData) { Debug.Assert(null != recordBuffer, "invalid attempt to instantiate SqlDataRecord with null SmiRecordBuffer"); Debug.Assert(null != metaData, "invalid attempt to instantiate SqlDataRecord with null SmiExtendedMetaData[]"); _columnMetaData = new SqlMetaData[metaData.Length]; _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length]; for (int i = 0; i < _columnSmiMetaData.Length; i++) { _columnSmiMetaData[i] = metaData[i]; _columnMetaData[i] = MetaDataUtilsSmi.SmiExtendedMetaDataToSqlMetaData(_columnSmiMetaData[i]); } _eventSink = new SmiEventSink_Default(); _recordBuffer = recordBuffer; _eventSink.ProcessMessagesAndThrow(); } // // SqlDataRecord private members // internal SmiRecordBuffer RecordBuffer { // used by SqlPipe get { return _recordBuffer; } } internal SqlMetaData[] InternalGetMetaData() { return _columnMetaData; } internal SmiExtendedMetaData[] InternalGetSmiMetaData() { return _columnSmiMetaData; } internal SmiExtendedMetaData GetSmiMetaData(int ordinal) { return _columnSmiMetaData[ordinal]; } internal void ThrowIfInvalidOrdinal(int ordinal) { if (0 > ordinal || FieldCount <= ordinal) { throw ADP.IndexOutOfRange(ordinal); } } private void EnsureSubclassOverride() { if (null == _recordBuffer) { throw SQL.SubclassMustOverride(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Newtonsoft.Json; using NFluent; using WireMock.Admin.Mappings; using WireMock.Matchers; using WireMock.Net.Tests.Serialization; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; using WireMock.Server; using WireMock.Settings; using WireMock.Types; using WireMock.Util; using Xunit; namespace WireMock.Net.Tests { public partial class WireMockServerTests { [Fact] public async Task WireMockServer_Should_reset_requestlogs() { // given var server = WireMockServer.Start(); // when await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false); server.ResetLogEntries(); // then Check.That(server.LogEntries).IsEmpty(); server.Stop(); } [Fact] public void WireMockServer_Should_reset_mappings() { // given string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath(path) .UsingGet()) .RespondWith(Response.Create() .WithBody(@"{ msg: ""Hello world!""}")); // when server.ResetMappings(); // then Check.That(server.Mappings).IsEmpty(); Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny(); server.Stop(); } [Fact] public async Task WireMockServer_Should_respond_a_redirect_without_body() { // Assign string path = $"/foo_{Guid.NewGuid()}"; string pathToRedirect = $"/bar_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath(path) .UsingGet()) .RespondWith(Response.Create() .WithStatusCode(307) .WithHeader("Location", pathToRedirect)); server .Given(Request.Create() .WithPath(pathToRedirect) .UsingGet()) .RespondWith(Response.Create() .WithStatusCode(200) .WithBody("REDIRECT SUCCESSFUL")); // Act var response = await new HttpClient().GetStringAsync($"http://localhost:{server.Ports[0]}{path}").ConfigureAwait(false); // Assert Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL"); server.Stop(); } #if NETCOREAPP3_1 || NET5_0 || NET6_0 [Fact] public async Task WireMockServer_WithCorsPolicyOptions_Should_Work_Correct() { // Arrange var settings = new WireMockServerSettings { CorsPolicyOptions = CorsPolicyOptions.AllowAll }; var server = WireMockServer.Start(settings); server.Given(Request.Create().WithPath("/*")).RespondWith(Response.Create().WithBody("x")); // Act var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false); // Asser. response.Should().Be("x"); server.Stop(); } #endif [Fact] public async Task WireMockServer_Should_delay_responses_for_a_given_route() { // Arrange var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath("/*")) .RespondWith(Response.Create() .WithBody(@"{ msg: ""Hello world!""}") .WithDelay(TimeSpan.FromMilliseconds(200))); // Act var watch = new Stopwatch(); watch.Start(); await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false); watch.Stop(); // Asser. watch.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(0); server.Stop(); } [Fact] public async Task WireMockServer_Should_randomly_delay_responses_for_a_given_route() { // Arrange var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath("/*")) .RespondWith(Response.Create() .WithBody(@"{ msg: ""Hello world!""}") .WithRandomDelay(10, 1000)); var watch = new Stopwatch(); watch.Start(); var httClient = new HttpClient(); async Task<long> ExecuteTimedRequestAsync() { watch.Reset(); await httClient.GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false); return watch.ElapsedMilliseconds; } // Act await ExecuteTimedRequestAsync().ConfigureAwait(false); await ExecuteTimedRequestAsync().ConfigureAwait(false); await ExecuteTimedRequestAsync().ConfigureAwait(false); server.Stop(); } [Fact] public async Task WireMockServer_Should_delay_responses() { // Arrange var server = WireMockServer.Start(); server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200)); server .Given(Request.Create().WithPath("/*")) .RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}")); // Act var watch = new Stopwatch(); watch.Start(); await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false); watch.Stop(); // Assert watch.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(0); server.Stop(); } //Leaving commented as this requires an actual certificate with password, along with a service that expects a client certificate //[Fact] //public async Task Should_proxy_responses_with_client_certificate() //{ // // given // var _server = WireMockServer.Start(); // _server // .Given(Request.Create().WithPath("/*")) // .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword")); // // when // var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/someurl?someQuery=someValue"); // // then // Check.That(result).Contains("google"); //} [Fact] public async Task WireMockServer_Should_exclude_restrictedResponseHeader() { // Assign string path = $"/foo_{Guid.NewGuid()}"; var server = WireMockServer.Start(); server .Given(Request.Create().WithPath(path).UsingGet()) .RespondWith(Response.Create().WithHeader("Transfer-Encoding", "chunked").WithHeader("test", "t")); // Act var response = await new HttpClient().GetAsync("http://localhost:" + server.Ports[0] + path).ConfigureAwait(false); // Assert Check.That(response.Headers.Contains("test")).IsTrue(); Check.That(response.Headers.Contains("Transfer-Encoding")).IsFalse(); server.Stop(); } #if !NET452 && !NET461 [Theory] [InlineData("TRACE")] [InlineData("GET")] public async Task WireMockServer_Should_exclude_body_for_methods_where_body_is_definitely_disallowed(string method) { // Assign string content = "hello"; var server = WireMockServer.Start(); server .Given(Request.Create().WithBody((byte[] bodyBytes) => bodyBytes != null)) .AtPriority(0) .RespondWith(Response.Create().WithStatusCode(400)); server .Given(Request.Create()) .AtPriority(1) .RespondWith(Response.Create().WithStatusCode(200)); // Act var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); request.Content = new StringContent(content); var response = await new HttpClient().SendAsync(request).ConfigureAwait(false); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.OK); server.Stop(); } #endif [Theory] [InlineData("POST")] [InlineData("PUT")] [InlineData("OPTIONS")] [InlineData("REPORT")] [InlineData("DELETE")] [InlineData("SOME-UNKNOWN-METHOD")] // default behavior for unknown methods is to allow a body (see BodyParser.ShouldParseBody) public async Task WireMockServer_Should_not_exclude_body_for_supported_methods(string method) { // Assign string content = "hello"; var server = WireMockServer.Start(); server .Given(Request.Create().WithBody(content)) .AtPriority(0) .RespondWith(Response.Create().WithStatusCode(200)); server .Given(Request.Create()) .AtPriority(1) .RespondWith(Response.Create().WithStatusCode(400)); // Act var request = new HttpRequestMessage(new HttpMethod(method), "http://localhost:" + server.Ports[0] + "/"); request.Content = new StringContent(content); var response = await new HttpClient().SendAsync(request).ConfigureAwait(false); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.OK); server.Stop(); } [Theory] [InlineData("application/json")] [InlineData("application/json; charset=ascii")] [InlineData("application/json; charset=utf-8")] [InlineData("application/json; charset=UTF-8")] public async Task WireMockServer_Should_AcceptPostMappingsWithContentTypeJsonAndAnyCharset(string contentType) { // Arrange string message = @"{ ""request"": { ""method"": ""GET"", ""url"": ""/some/thing"" }, ""response"": { ""status"": 200, ""body"": ""Hello world!"", ""headers"": { ""Content-Type"": ""text/plain"" } } }"; var stringContent = new StringContent(message); stringContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); var server = WireMockServer.StartWithAdminInterface(); // Act var response = await new HttpClient().PostAsync($"{server.Urls[0]}/__admin/mappings", stringContent).ConfigureAwait(false); // Assert Check.That(response.StatusCode).Equals(HttpStatusCode.Created); Check.That(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Contains("Mapping added"); server.Stop(); } [Theory] [InlineData("gzip")] [InlineData("deflate")] public async Task WireMockServer_Should_SupportRequestGZipAndDeflate(string contentEncoding) { // Arrange const string body = "hello wiremock"; byte[] compressed = CompressionUtils.Compress(contentEncoding, Encoding.UTF8.GetBytes(body)); var server = WireMockServer.Start(); server.Given( Request.Create() .WithPath("/foo") .WithBody("hello wiremock") ) .RespondWith( Response.Create().WithBody("OK") ); var content = new StreamContent(new MemoryStream(compressed)); content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); content.Headers.ContentEncoding.Add(contentEncoding); // Act var response = await new HttpClient().PostAsync($"{server.Urls[0]}/foo", content).ConfigureAwait(false); // Assert Check.That(await response.Content.ReadAsStringAsync().ConfigureAwait(false)).Contains("OK"); server.Stop(); } #if !NET452 [Fact] public async Task WireMockServer_Should_respond_to_ipv4_loopback() { // Assign var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath("/*")) .RespondWith(Response.Create() .WithStatusCode(200) .WithBody("from ipv4 loopback")); // Act var response = await new HttpClient().GetStringAsync($"http://127.0.0.1:{server.Ports[0]}/foo").ConfigureAwait(false); // Assert Check.That(response).IsEqualTo("from ipv4 loopback"); server.Stop(); } [Fact] public async Task WireMockServer_Should_respond_to_ipv6_loopback() { // Assign var server = WireMockServer.Start(); server .Given(Request.Create() .WithPath("/*")) .RespondWith(Response.Create() .WithStatusCode(200) .WithBody("from ipv6 loopback")); // Act var response = await new HttpClient().GetStringAsync($"http://[::1]:{server.Ports[0]}/foo").ConfigureAwait(false); // Assert Check.That(response).IsEqualTo("from ipv6 loopback"); server.Stop(); } [Fact] public async Task WireMockServer_Using_JsonMapping_And_CustomMatcher_WithCorrectParams_ShouldMatch() { // Arrange var settings = new WireMockServerSettings(); settings.WatchStaticMappings = true; settings.WatchStaticMappingsInSubdirectories = true; settings.CustomMatcherMappings = new Dictionary<string, Func<MatcherModel, IMatcher>>(); settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel => { var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern); return new CustomPathParamMatcher( matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch, matcherParams.Path, matcherParams.PathParams, settings.ThrowExceptionWhenMatcherFails == true ); }; var server = WireMockServer.Start(settings); server.WithMapping(@"{ ""Request"": { ""Path"": { ""Matchers"": [ { ""Name"": ""CustomPathParamMatcher"", ""Pattern"": ""{\""path\"":\""/customer/{customerId}/document/{documentId}\"",\""pathParams\"":{\""customerId\"":\""^[0-9]+$\"",\""documentId\"":\""^[0-9a-zA-Z\\\\-_]+\\\\.[a-zA-Z]+$\""}}"" } ] } }, ""Response"": { ""StatusCode"": 200, ""Headers"": { ""Content-Type"": ""application/json"" }, ""Body"": ""OK"" } }"); // Act var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic.jpg", new StringContent("{ Hi = \"Hello World\" }")).ConfigureAwait(false); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); server.Stop(); } [Fact] public async Task WireMockServer_Using_JsonMapping_And_CustomMatcher_WithIncorrectParams_ShouldNotMatch() { // Arrange var settings = new WireMockServerSettings(); settings.WatchStaticMappings = true; settings.WatchStaticMappingsInSubdirectories = true; settings.CustomMatcherMappings = new Dictionary<string, Func<MatcherModel, IMatcher>>(); settings.CustomMatcherMappings[nameof(CustomPathParamMatcher)] = matcherModel => { var matcherParams = JsonConvert.DeserializeObject<CustomPathParamMatcherModel>((string)matcherModel.Pattern); return new CustomPathParamMatcher( matcherModel.RejectOnMatch == true ? MatchBehaviour.RejectOnMatch : MatchBehaviour.AcceptOnMatch, matcherParams.Path, matcherParams.PathParams, settings.ThrowExceptionWhenMatcherFails == true ); }; var server = WireMockServer.Start(settings); server.WithMapping(@"{ ""Request"": { ""Path"": { ""Matchers"": [ { ""Name"": ""CustomPathParamMatcher"", ""Pattern"": ""{\""path\"":\""/customer/{customerId}/document/{documentId}\"",\""pathParams\"":{\""customerId\"":\""^[0-9]+$\"",\""documentId\"":\""^[0-9a-zA-Z\\\\-_]+\\\\.[a-zA-Z]+$\""}}"" } ] } }, ""Response"": { ""StatusCode"": 200, ""Headers"": { ""Content-Type"": ""application/json"" }, ""Body"": ""OK"" } }"); // Act var response = await new HttpClient().PostAsync("http://localhost:" + server.Ports[0] + "/customer/132/document/pic", new StringContent("{ Hi = \"Hello World\" }")).ConfigureAwait(false); // Assert response.StatusCode.Should().Be(HttpStatusCode.NotFound); server.Stop(); } #endif } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using MartinCostello.LondonTravel.Site.Options; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.Extensions.Localization; namespace MartinCostello.LondonTravel.Site; /// <summary> /// A class representing the container for site resource strings. /// </summary> public class SiteResources { private readonly IHtmlLocalizer<SiteResources> _htmlLocalizer; private readonly IStringLocalizer<SiteResources> _localizer; private readonly SiteOptions _options; public SiteResources( IHtmlLocalizer<SiteResources> htmlLocalizer, IStringLocalizer<SiteResources> localizer, SiteOptions options) { _htmlLocalizer = htmlLocalizer; _localizer = localizer; _options = options; } public string? AccountCreatedTitle => _localizer[nameof(AccountCreatedTitle)]; public string? AccountDeletedTitle => _localizer[nameof(AccountDeletedTitle)]; public string? AccountDeletedContent => _localizer[nameof(AccountDeletedContent)]; public string? AccessDeniedTitle => _localizer[nameof(AccessDeniedTitle)]; public string? AccessDeniedSubtitle => _localizer[nameof(AccessDeniedSubtitle)]; public string? AccountLinkDeniedTitle => _localizer[nameof(AccountLinkDeniedTitle)]; public string? AccountLinkDeniedContent => _localizer[nameof(AccountLinkDeniedContent)]; public string? AccountLinkFailedTitle => _localizer[nameof(AccountLinkFailedTitle)]; public string? AccountLinkFailedContent => _localizer[nameof(AccountLinkFailedContent)]; public string? AccountLockedTitle => _localizer[nameof(AccountLockedTitle)]; public string? AccountLockedSubtitle => _localizer[nameof(AccountLockedSubtitle)]; public string? AlreadyRegisteredTitle => _localizer[nameof(AlreadyRegisteredTitle)]; public string? AlreadyRegisteredContent1 => _localizer[nameof(AlreadyRegisteredContent1)]; public string? AlreadyRegisteredContent2 => _localizer[nameof(AlreadyRegisteredContent2)]; public string? BrandName => _localizer[nameof(BrandName)]; public string? CancelButtonText => _localizer[nameof(CancelButtonText)]; public string? CancelButtonAltText => _localizer[nameof(CancelButtonAltText)]; public string? CloseButtonText => _localizer[nameof(CloseButtonText)]; public string? CommuteSkillInvocation => _localizer[nameof(CommuteSkillInvocation)]; public LocalizedHtmlString CopyrightText => _htmlLocalizer[nameof(CopyrightText), _options?.Metadata?.Author?.Name!, DateTimeOffset.UtcNow.Year]; public string? DeleteAccountButtonText => _localizer[nameof(DeleteAccountButtonText)]; public string? DeleteAccountButtonAltText => _localizer[nameof(DeleteAccountButtonAltText)]; public string? DeleteAccountConfirmationButtonText => _localizer[nameof(DeleteAccountConfirmationButtonText)]; public string? DeleteAccountConfirmationButtonAltText => _localizer[nameof(DeleteAccountConfirmationButtonAltText)]; public string? DeleteAccountModalTitle => _localizer[nameof(DeleteAccountModalTitle)]; public string? DeleteAccountWarning => _localizer[nameof(DeleteAccountWarning)]; public LocalizedHtmlString DeleteAccountParagraph1Html => _htmlLocalizer[nameof(DeleteAccountParagraph1Html)]; public string? DeleteAccountParagraph2 => _localizer[nameof(DeleteAccountParagraph2)]; public LocalizedHtmlString DeleteAccountParagraph3Html => _htmlLocalizer[nameof(DeleteAccountParagraph3Html)]; public string? DeleteInProgressText => _localizer[nameof(DeleteInProgressText)]; public string? ErrorTitle => _localizer[nameof(ErrorTitle)]; public string? ErrorMessage => _localizer[nameof(ErrorMessage)]; public string? ErrorRequestId => _localizer[nameof(ErrorRequestId)]; public string? HelpTitle => _localizer[nameof(HelpTitle)]; public string? HelpMetaDescription => _localizer[nameof(HelpMetaDescription)]; public string? HelpLinkText => _localizer[nameof(HelpLinkText)]; public string? HelpLinkAltText => _localizer[nameof(HelpLinkAltText)]; public string? HomepageTitle => _localizer[nameof(HomepageTitle)]; public string? HomepageLinkText => _localizer[nameof(HomepageLinkText)]; public string? HomepageLinkAltText => _localizer[nameof(HomepageLinkAltText)]; public string? HomepageLead => _localizer[nameof(HomepageLead)]; public string? InstallLinkText => _localizer[nameof(InstallLinkText)]; public string? InstallLinkAltText => _localizer[nameof(InstallLinkAltText)]; public string? ManageTitle => _localizer[nameof(ManageTitle)]; public string? ManageLinkText => _localizer[nameof(ManageLinkText)]; public string? ManageLinkAltText => _localizer[nameof(ManageLinkAltText)]; public string? ManageMetaDescription => _localizer[nameof(ManageMetaDescription)]; public string? ManageLinkedAccountsSubtitle => _localizer[nameof(ManageLinkedAccountsSubtitle)]; public string? ManageLinkedAccountsContent => _localizer[nameof(ManageLinkedAccountsContent)]; public string? ManageLinkOtherAccountsSubtitle => _localizer[nameof(ManageLinkOtherAccountsSubtitle)]; public string? ManagePreferencesTitle => _localizer[nameof(ManagePreferencesTitle)]; public string? ManageLinkedToAlexa => _localizer[nameof(ManageLinkedToAlexa)]; public string? ManageNotLinkedToAlexa => _localizer[nameof(ManageNotLinkedToAlexa)]; public string? ManageUnlinkAlexaButtonText => _localizer[nameof(ManageUnlinkAlexaButtonText)]; public string? ManageUnlinkAlexaButtonAltText => _localizer[nameof(ManageUnlinkAlexaButtonAltText)]; public string? ManageUnlinkAlexaModalTitle => _localizer[nameof(ManageUnlinkAlexaModalTitle)]; public string? ManageUnlinkAlexaModalContent1 => _localizer[nameof(ManageUnlinkAlexaModalContent1)]; public string? ManageUnlinkAlexaModalContent2 => _localizer[nameof(ManageUnlinkAlexaModalContent2)]; public string? ManageUnlinkAlexaModalLoading => _localizer[nameof(ManageUnlinkAlexaModalLoading)]; public string? ManageUnlinkAlexaModalConfirmButtonText => _localizer[nameof(ManageUnlinkAlexaModalConfirmButtonText)]; public string? ManageUnlinkAlexaModalConfirmButtonAltText => _localizer[nameof(ManageUnlinkAlexaModalConfirmButtonAltText)]; public string? NavbarCollapseAltText => _localizer[nameof(NavbarCollapseAltText)]; public string? NavbarMenuText => _localizer[nameof(NavbarMenuText)]; public string? PermissionDeniedTitle => _localizer[nameof(PermissionDeniedTitle)]; public string? PermissionDeniedContent => _localizer[nameof(PermissionDeniedContent)]; public string? PrivacyPolicyTitle => _localizer[nameof(PrivacyPolicyTitle)]; public string? PrivacyPolicyMetaTitle => _localizer[nameof(PrivacyPolicyMetaTitle)]; public string? PrivacyPolicyMetaDescription => _localizer[nameof(PrivacyPolicyMetaDescription)]; public string? PrivacyPolicyLinkText => _localizer[nameof(PrivacyPolicyLinkText)]; public string? PrivacyPolicyLinkAltText => _localizer[nameof(PrivacyPolicyLinkAltText)]; public string? RegisterTitle => _localizer[nameof(RegisterTitle)]; public string? RegisterSubtitle => _localizer[nameof(RegisterSubtitle)]; public string? RegisterMetaDescription => _localizer[nameof(RegisterMetaDescription)]; public string? RegisterLead => _localizer[nameof(RegisterLead)]; public string? RegisterParagraph1 => _localizer[nameof(RegisterParagraph1)]; public string? RegisterParagraph2 => _localizer[nameof(RegisterParagraph2)]; public string? RegisterParagraph3 => _localizer[nameof(RegisterParagraph3)]; public string? RegisterLinkText => _localizer[nameof(RegisterLinkText)]; public string? RegisterLinkAltText => _localizer[nameof(RegisterLinkAltText)]; public string? RegisterSignInSubtitle => _localizer[nameof(RegisterSignInSubtitle)]; public string? RemoveAccountButtonText => _localizer[nameof(RemoveAccountButtonText)]; public string? RemoveAccountLinkModalTitle => _localizer[nameof(RemoveAccountLinkModalTitle)]; public string? RemoveAccountLinkModalDescription => _localizer[nameof(RemoveAccountLinkModalDescription)]; public string? SavePreferencesButtonText => _localizer[nameof(SavePreferencesButtonText)]; public string? SavePreferencesButtonAltText => _localizer[nameof(SavePreferencesButtonAltText)]; public string? SkillNotLinkedTitle => _localizer[nameof(SkillNotLinkedTitle)]; public string? SkillNotLinkedDescription => _localizer[nameof(SkillNotLinkedDescription)]; public string? ClearPreferencesButtonText => _localizer[nameof(ClearPreferencesButtonText)]; public string? ClearPreferencesButtonAltText => _localizer[nameof(ClearPreferencesButtonAltText)]; public string? ResetPreferencesButtonText => _localizer[nameof(ResetPreferencesButtonText)]; public string? ResetPreferencesButtonAltText => _localizer[nameof(ResetPreferencesButtonAltText)]; public string? SignInTitle => _localizer[nameof(SignInTitle)]; public string? SignInMetaDescription => _localizer[nameof(SignInMetaDescription)]; public string? SignInSubtitle => _localizer[nameof(SignInSubtitle)]; public string? SignInRegisterSubtitle => _localizer[nameof(SignInRegisterSubtitle)]; public string? SignInRegisterText => _localizer[nameof(SignInRegisterText)]; public string? SignInLinkText => _localizer[nameof(SignInLinkText)]; public string? SignInLinkAltText => _localizer[nameof(SignInLinkAltText)]; public string? SignInErrorTitle => _localizer[nameof(SignInErrorTitle)]; public string? SignInErrorSubtitle => _localizer[nameof(SignInErrorSubtitle)]; public string? SigningInModalTitle => _localizer[nameof(SigningInModalTitle)]; public string? SigningInModalDescription => _localizer[nameof(SigningInModalDescription)]; public string? SignOutLinkText => _localizer[nameof(SignOutLinkText)]; public string? TermsOfServiceTitle => _localizer[nameof(TermsOfServiceTitle)]; public string? TermsOfServiceMetaDescription => _localizer[nameof(TermsOfServiceMetaDescription)]; public string? TermsOfServiceMetaTitle => _localizer[nameof(TermsOfServiceMetaTitle)]; public string? TermsOfServiceLinkText => _localizer[nameof(TermsOfServiceLinkText)]; public string? TermsOfServiceLinkAltText => _localizer[nameof(TermsOfServiceLinkAltText)]; public string? UpdateFailureModalTitle => _localizer[nameof(UpdateFailureModalTitle)]; public string? UpdateFailureModalDescription => _localizer[nameof(UpdateFailureModalDescription)]; public string? UpdateSuccessModalTitle => _localizer[nameof(UpdateSuccessModalTitle)]; public string? UpdateProgressModalTitle => _localizer[nameof(UpdateProgressModalTitle)]; public string? UpdateProgressModalDescription => _localizer[nameof(UpdateProgressModalDescription)]; public string? LinePreferencesNoneLead => _localizer[nameof(LinePreferencesNoneLead)]; public string? LinePreferencesNoneContent => _localizer[nameof(LinePreferencesNoneContent), BrandName!]; public string? LinePreferencesSingular => _localizer[nameof(LinePreferencesSingular)]; public string? AlexaSignInTitle => _localizer[nameof(AlexaSignInTitle)]; public string? AlexaSignInMetaDescription => _localizer[nameof(AlexaSignInMetaDescription)]; public string? AlexaSignInParagraph1 => _localizer[nameof(AlexaSignInParagraph1)]; public string? AlexaSignInParagraph2 => _localizer[nameof(AlexaSignInParagraph2)]; public string? AlexaSignInParagraph3 => _localizer[nameof(AlexaSignInParagraph3)]; public string? AlexaSignInFormTitle => _localizer[nameof(AlexaSignInFormTitle)]; public string? ErrorTitle400 => _localizer[nameof(ErrorTitle400)]; public string? ErrorSubtitle400 => _localizer[nameof(ErrorSubtitle400)]; public string? ErrorMessage400 => _localizer[nameof(ErrorMessage400)]; public string? ErrorTitle403 => _localizer[nameof(ErrorTitle403)]; public string? ErrorSubtitle403 => _localizer[nameof(ErrorSubtitle403)]; public string? ErrorMessage403 => _localizer[nameof(ErrorMessage403)]; public string? ErrorTitle404 => _localizer[nameof(ErrorTitle404)]; public string? ErrorSubtitle404 => _localizer[nameof(ErrorSubtitle404)]; public string? ErrorMessage404 => _localizer[nameof(ErrorMessage404)]; public string? ErrorTitle405 => _localizer[nameof(ErrorTitle405)]; public string? ErrorSubtitle405 => _localizer[nameof(ErrorSubtitle405)]; public string? ErrorMessage405 => _localizer[nameof(ErrorMessage405)]; public string? ErrorTitle408 => _localizer[nameof(ErrorTitle408)]; public string? ErrorSubtitle408 => _localizer[nameof(ErrorSubtitle408)]; public string? ErrorMessage408 => _localizer[nameof(ErrorMessage408)]; public string? TechnologyTitle => _localizer[nameof(TechnologyTitle)]; public string? TechnologyMetaDescription => _localizer[nameof(TechnologyMetaDescription)]; public string? TechnologyMetaTitle => _localizer[nameof(TechnologyMetaTitle)]; public string? TechnologyLinkText => _localizer[nameof(TechnologyLinkText)]; public string? TechnologyLinkAltText => _localizer[nameof(TechnologyLinkAltText)]; public string? ApiDocumentationMetaTitle => _localizer[nameof(ApiDocumentationMetaTitle)]; public string? ApiDocumentationMetaDescription => _localizer[nameof(ApiDocumentationMetaDescription)]; public string? ErrorSubtitle(int? httpCode) => _localizer[nameof(ErrorSubtitle), httpCode ?? 500]; public LocalizedHtmlString AvailableLinesTitle(string classes, int count) => _htmlLocalizer[nameof(AvailableLinesTitle), classes, count]; public LocalizedHtmlString FavoriteLinesTitle(string classes, int count) => _htmlLocalizer[nameof(FavoriteLinesTitle), classes, count]; public string? LinePreferencesPlural(int count) => _localizer[nameof(LinePreferencesPlural), count]; public LocalizedHtmlString OtherLinesTitle(string classes, int count) => _htmlLocalizer[nameof(OtherLinesTitle), classes, count]; public string? RegisterParagraph4(long count) => _localizer[nameof(RegisterParagraph4), count]; public string? RemoveAccountButtonAltText(string provider) => _localizer[nameof(RemoveAccountButtonAltText), provider]; public string? SignInButtonText(string diplayName) => _localizer[nameof(SignInButtonText), diplayName]; public string? SignInButtonAltText(string diplayName) => _localizer[nameof(SignInButtonAltText), diplayName]; }
/* insert license info here */ using System; using System.Collections; namespace Business.Data.Laboratorio { /// <summary> /// Generated by MyGeneration using the NHibernate Object Mapping template /// </summary> [Serializable] public sealed class SolicitanteExterno: Business.BaseDataAccess { #region Private Members private bool m_isChanged; private int m_idsolicitanteexterno; private Efector m_idefector; private string m_apellido; private string m_nombre; private string m_matricula; private bool m_baja; private Usuario m_idusuarioregistro; private DateTime m_fecharegistro; #endregion #region Default ( Empty ) Class Constuctor /// <summary> /// default constructor /// </summary> public SolicitanteExterno() { m_idsolicitanteexterno = 0; m_idefector = new Efector(); m_apellido = String.Empty; m_nombre = String.Empty; m_matricula = String.Empty; m_baja = false; m_idusuarioregistro = new Usuario(); m_fecharegistro = DateTime.MinValue; } #endregion // End of Default ( Empty ) Class Constuctor #region Required Fields Only Constructor /// <summary> /// required (not null) fields only constructor /// </summary> public SolicitanteExterno( Efector idefector, string apellido, string nombre, string matricula, bool baja, Usuario idusuarioregistro, DateTime fecharegistro) : this() { m_idefector = idefector; m_apellido = apellido; m_nombre = nombre; m_matricula = matricula; m_baja = baja; m_idusuarioregistro = idusuarioregistro; m_fecharegistro = fecharegistro; } #endregion // End Required Fields Only Constructor #region Public Properties /// <summary> /// /// </summary> public int IdSolicitanteExterno { get { return m_idsolicitanteexterno; } set { m_isChanged |= ( m_idsolicitanteexterno != value ); m_idsolicitanteexterno = value; } } /// <summary> /// /// </summary> public Efector IdEfector { get { return m_idefector; } set { m_isChanged |= ( m_idefector != value ); m_idefector = value; } } /// <summary> /// /// </summary> public string Apellido { get { return m_apellido; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Apellido", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Apellido", value, value.ToString()); m_isChanged |= (m_apellido != value); m_apellido = value; } } /// <summary> /// /// </summary> public string Nombre { get { return m_nombre; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Nombre", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Nombre", value, value.ToString()); m_isChanged |= (m_nombre != value); m_nombre = value; } } /// <summary> /// /// </summary> public string Matricula { get { return m_matricula; } set { if( value == null ) throw new ArgumentOutOfRangeException("Null value not allowed for Matricula", value, "null"); if( value.Length > 50) throw new ArgumentOutOfRangeException("Invalid value for Matricula", value, value.ToString()); m_isChanged |= (m_matricula != value); m_matricula = value; } } /// <summary> /// /// </summary> public bool Baja { get { return m_baja; } set { m_isChanged |= ( m_baja != value ); m_baja = value; } } /// <summary> /// /// </summary> public Usuario IdUsuarioRegistro { get { return m_idusuarioregistro; } set { m_isChanged |= ( m_idusuarioregistro != value ); m_idusuarioregistro = value; } } /// <summary> /// /// </summary> public DateTime FechaRegistro { get { return m_fecharegistro; } set { m_isChanged |= ( m_fecharegistro != value ); m_fecharegistro = value; } } /// <summary> /// Returns whether or not the object has changed it's values. /// </summary> public bool IsChanged { get { return m_isChanged; } } #endregion } }
/* * 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 NVelocity.Runtime.Parser { using System; using System.IO; using System.Text; /// <summary> NOTE : This class was originally an ASCII_CharStream autogenerated /// by Javacc. It was then modified via changing class name with appropriate /// fixes for CTORS, and mods to readChar(). /// /// This is safe because we *always* use Reader with this class, and never a /// InputStream. This guarantees that we have a correct stream of 16-bit /// chars - all encoding transformations have been done elsewhere, so we /// believe that there is no risk in doing this. Time will tell :) /// </summary> /// <summary> An implementation of interface CharStream, where the stream is assumed to /// contain only ASCII characters (without unicode processing). /// </summary> public sealed class VelocityCharStream : ICharStream { /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getEndColumn()"> /// </seealso> public int EndColumn { get { return bufcolumn[bufpos]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getEndLine()"> /// </seealso> public int EndLine { get { return bufline[bufpos]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getBeginColumn()"> /// </seealso> public int BeginColumn { get { return bufcolumn[tokenBegin]; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.getBeginLine()"> /// </seealso> public int BeginLine { get { return bufline[tokenBegin]; } } public const bool staticFlag = false; internal int bufsize; private int nextBufExpand; internal int available; internal int tokenBegin; public int bufpos = -1; private int[] bufline; private int[] bufcolumn; private int column = 0; private int line = 1; private bool prevCharIsCR = false; private bool prevCharIsLF = false; private TextReader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private void ExpandBuff(bool wrapAround) { char[] newbuffer = new char[bufsize + nextBufExpand]; int[] newbufline = new int[bufsize + nextBufExpand]; int[] newbufcolumn = new int[bufsize + nextBufExpand]; try { if (wrapAround) { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (System.Exception t) { throw new System.Exception(t.Message); } bufsize += nextBufExpand; nextBufExpand = bufsize; available = bufsize; tokenBegin = 0; } private bool FillBuff() { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > nextBufExpand) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) { bufpos = maxNextCharInd = 0; } else { ExpandBuff(false); } } else if (available > tokenBegin) { available = bufsize; } else if ((tokenBegin - available) < nextBufExpand) { ExpandBuff(true); } else { available = tokenBegin; } } int i; try { if ((i = inputStream.Read(buffer, maxNextCharInd, available - maxNextCharInd)) <= 0) { inputStream.Close(); throw new System.IO.IOException(); } else { maxNextCharInd += i; } return true; } catch { --bufpos; Backup(0); if (tokenBegin == -1) { tokenBegin = bufpos; } return false; } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.BeginToken()"> /// </seealso> public char BeginToken() { tokenBegin = -1; char c = ReadChar(); tokenBegin = bufpos; return c; } private void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else { line += (column = 1); } } switch (c) { case '\r': prevCharIsCR = true; break; case '\n': prevCharIsLF = true; break; case '\t': column--; column += (8 - (column & 7)); break; default: break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.readChar()"> /// </seealso> public char ReadChar() { if (inBuf > 0) { --inBuf; /* * was : return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); */ return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]; } if (++bufpos >= maxNextCharInd) { if (!FillBuff()) { throw new IOException(); } } /* * was : char c = (char)((char)0xff & buffer[bufpos]); */ char c = buffer[bufpos]; UpdateLineColumn(c); return (c); } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.backup(int)"> /// </seealso> public void Backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public VelocityCharStream(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = nextBufExpand = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public VelocityCharStream(TextReader dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public void ReInit(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.Length) { available = bufsize = nextBufExpand = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public void ReInit(TextReader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public VelocityCharStream(Stream dstream, int startline, int startcolumn, int buffersize) : this(new StreamReader(dstream, Encoding.UTF8), startline, startcolumn, buffersize) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public VelocityCharStream(Stream dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> /// <param name="buffersize"> /// </param> public void ReInit(Stream dstream, int startline, int startcolumn, int buffersize) { ReInit(new StreamReader(dstream, Encoding.UTF8), startline, startcolumn, buffersize); } /// <param name="dstream"> /// </param> /// <param name="startline"> /// </param> /// <param name="startcolumn"> /// </param> public void ReInit(Stream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.GetImage()"> /// </seealso> public string GetImage() { if (bufpos >= tokenBegin) { return new string(buffer, tokenBegin, bufpos - tokenBegin + 1); } else { return new string(buffer, tokenBegin, bufsize - tokenBegin) + new string(buffer, 0, bufpos + 1); } } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.GetSuffix(int)"> /// </seealso> public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) { Array.Copy(buffer, bufpos - len + 1, ret, 0, len); } else { Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /// <seealso cref="org.apache.velocity.runtime.parser.CharStream.Done()"> /// </seealso> public void Done() { buffer = null; bufline = null; bufcolumn = null; } /// <summary> Method to adjust line and column numbers for the start of a token.<BR></summary> /// <param name="newLine"> /// </param> /// <param name="newCol"> /// </param> public void AdjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } }
using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; [TestFixture] public class TestCachingCollector : LuceneTestCase { private const double ONE_BYTE = 1.0 / (1024 * 1024); // 1 byte out of MB private class MockScorer : Scorer { internal MockScorer() : base((Weight)null) { } public override float GetScore() { return 0; } public override int Freq => 0; public override int DocID => 0; public override int NextDoc() { return 0; } public override int Advance(int target) { return 0; } public override long GetCost() { return 1; } } private class NoOpCollector : ICollector { private readonly bool acceptDocsOutOfOrder; public NoOpCollector(bool acceptDocsOutOfOrder) { this.acceptDocsOutOfOrder = acceptDocsOutOfOrder; } public virtual void SetScorer(Scorer scorer) { } public virtual void Collect(int doc) { } public virtual void SetNextReader(AtomicReaderContext context) { } public virtual bool AcceptsDocsOutOfOrder => acceptDocsOutOfOrder; } [Test] public virtual void TestBasic() { foreach (bool cacheScores in new bool[] { false, true }) { CachingCollector cc = CachingCollector.Create(new NoOpCollector(false), cacheScores, 1.0); cc.SetScorer(new MockScorer()); // collect 1000 docs for (int i = 0; i < 1000; i++) { cc.Collect(i); } // now replay them cc.Replay(new CollectorAnonymousInnerClassHelper(this)); } } private class CollectorAnonymousInnerClassHelper : ICollector { private readonly TestCachingCollector outerInstance; public CollectorAnonymousInnerClassHelper(TestCachingCollector outerInstance) { this.outerInstance = outerInstance; prevDocID = -1; } internal int prevDocID; public virtual void SetScorer(Scorer scorer) { } public virtual void SetNextReader(AtomicReaderContext context) { } public virtual void Collect(int doc) { Assert.AreEqual(prevDocID + 1, doc); prevDocID = doc; } public virtual bool AcceptsDocsOutOfOrder => false; } [Test] public virtual void TestIllegalStateOnReplay() { CachingCollector cc = CachingCollector.Create(new NoOpCollector(false), true, 50 * ONE_BYTE); cc.SetScorer(new MockScorer()); // collect 130 docs, this should be enough for triggering cache abort. for (int i = 0; i < 130; i++) { cc.Collect(i); } Assert.IsFalse(cc.IsCached, "CachingCollector should not be cached due to low memory limit"); try { cc.Replay(new NoOpCollector(false)); Assert.Fail("replay should fail if CachingCollector is not cached"); } #pragma warning disable 168 catch (InvalidOperationException e) #pragma warning restore 168 { // expected } } [Test] public virtual void TestIllegalCollectorOnReplay() { // tests that the Collector passed to replay() has an out-of-order mode that // is valid with the Collector passed to the ctor // 'src' Collector does not support out-of-order CachingCollector cc = CachingCollector.Create(new NoOpCollector(false), true, 50 * ONE_BYTE); cc.SetScorer(new MockScorer()); for (int i = 0; i < 10; i++) { cc.Collect(i); } cc.Replay(new NoOpCollector(true)); // this call should not fail cc.Replay(new NoOpCollector(false)); // this call should not fail // 'src' Collector supports out-of-order cc = CachingCollector.Create(new NoOpCollector(true), true, 50 * ONE_BYTE); cc.SetScorer(new MockScorer()); for (int i = 0; i < 10; i++) { cc.Collect(i); } cc.Replay(new NoOpCollector(true)); // this call should not fail try { cc.Replay(new NoOpCollector(false)); // this call should fail Assert.Fail("should have failed if an in-order Collector was given to replay(), " + "while CachingCollector was initialized with out-of-order collection"); } #pragma warning disable 168 catch (ArgumentException e) #pragma warning restore 168 { // ok } } [Test] public virtual void TestCachedArraysAllocation() { // tests the cached arrays allocation -- if the 'nextLength' was too high, // caching would terminate even if a smaller length would suffice. // set RAM limit enough for 150 docs + random(10000) int numDocs = Random.Next(10000) + 150; foreach (bool cacheScores in new bool[] { false, true }) { int bytesPerDoc = cacheScores ? 8 : 4; CachingCollector cc = CachingCollector.Create(new NoOpCollector(false), cacheScores, bytesPerDoc * ONE_BYTE * numDocs); cc.SetScorer(new MockScorer()); for (int i = 0; i < numDocs; i++) { cc.Collect(i); } Assert.IsTrue(cc.IsCached); // The 151's document should terminate caching cc.Collect(numDocs); Assert.IsFalse(cc.IsCached); } } [Test] public virtual void TestNoWrappedCollector() { foreach (bool cacheScores in new bool[] { false, true }) { // create w/ null wrapped collector, and test that the methods work CachingCollector cc = CachingCollector.Create(true, cacheScores, 50 * ONE_BYTE); cc.SetNextReader(null); cc.SetScorer(new MockScorer()); cc.Collect(0); Assert.IsTrue(cc.IsCached); cc.Replay(new NoOpCollector(true)); } } } }
using System; using System.Drawing; using System.Diagnostics; using System.IO; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using DirectInput = Microsoft.DirectX.DirectInput; namespace Simbiosis { /// <summary> /// PURE STATIC Class: the one-and-only scene /// </summary> public static class Scene { // WEATHER /// <summary> Colour for fog and also background when wiping render target at start of frame</summary> //public static Color FogColor = Color.FromArgb(110, 180, 160); //public static Color FogColor = Color.FromArgb(64, 100, 140); public static Color FogColor = Color.FromArgb(140, 200, 200); // Farthest visible distance (used to set clipping planes, fog and skybox) public const float Horizon = 200.0f; /// <summary> The time since last frame, for use by objects in the scene </summary> private static float elapsedTime = 0; public static float ElapsedTime { get { return elapsedTime; } } /// <summary> Time since application started (useful for creating rythmic motion etc.) </summary> private static float totalElapsedTime = 0; public static float TotalElapsedTime { get { return totalElapsedTime; } } /// <summary> Time left until game is unfrozen (-1=indefinite freeze, 0=unfrozen, n=pause for n secs) </summary> private static float freezeTime = 0f; public static float FreezeTime { get { return freezeTime; } set { freezeTime = value; } } /// <summary> /// TEMP: Opens a text file that can be used for logging debug info (e.g. in releas version) /// </summary> ////// public static StreamWriter Log = new StreamWriter("Log.txt"); // TEMP: somewhere to store some creatures public static Organism[] Creature = null; #region construction and initialisation /// <summary> /// Constructor. Note: This gets called before the form, device, etc. have been created. /// </summary> static Scene() { Debug.WriteLine("Constructing scene"); } /// <summary> /// Once the first D3D device has been created, set up those things that couldn't be done before /// </summary> public static void OnDeviceCreated() { Debug.WriteLine("Scene.OnDeviceCreated()"); // Pause the time while everything is created, else the first frame will appear to be a long elapsedTime //Engine.Framework.Pause(true, true); // Ripple through to other classes' STATIC event handlers. Instances will hook their own events UserInput.OnDeviceCreated(); Terrain.OnDeviceCreated(); SkyBox.OnDeviceCreated(); Water.OnDeviceCreated(); Marker.OnDeviceCreated(); Scenery.OnDeviceCreated(); Camera.OnDeviceCreated(); CameraShip.OnDeviceCreated(); SkyBox.OnDeviceCreated(); Map.OnDeviceCreated(); // HACK: TEMP TEST FOR BODY & Cell CLASSES CreateSomeCreatures(); //Engine.Framework.Pause(false, false); Microsoft.Samples.DirectX.UtilityToolkit.FrameworkTimer.Reset(); } /// <summary> /// TEMP: Create one or more creatures for testing /// </summary> private static void CreateSomeCreatures() { const int NUMCREATURES = 50; Creature = new Organism[NUMCREATURES]; string[] genotype = { "testTail", "testJawRed", }; // Creature 0 is guaranteed to be in front of the camera - use this alone when testing Creature[0] = new Organism(genotype[0], new Vector3(512.0f, 25.0f, 475.0f), new Orientation(0, 0, 0)); Creature[1] = new Organism(genotype[1], new Vector3(512.0f, 25.0f, 480.0f), new Orientation(0, 0, 0)); for (int c = 2; c < NUMCREATURES; c++) { float x, z; do { x = Rnd.Float(400,600); z = Rnd.Float(400,600); } while (Terrain.AltitudeAt(x, z) > Water.WATERLEVEL - 10); Vector3 loc = new Vector3( x, Rnd.Float(Terrain.AltitudeAt(x, z) + 5, Water.WATERLEVEL - 5), z ); Orientation or = new Orientation(Rnd.Float(3.14f), Rnd.Float(3.14f), Rnd.Float(3.14f)); int genome = Rnd.Int(genotype.Length - 1); Creature[c] = new Organism(genotype[genome], loc, or); } } /// <summary> /// Called immediately after the D3D device has been destroyed, /// which generally happens as a result of application termination or /// windowed/full screen toggles. Resources created in OnSubsequentDevices() /// should be released here, which generally includes all Pool.Managed resources. /// </summary> public static void OnDeviceLost() { Debug.WriteLine("Scene.OnDeviceLost()"); // Ripple through to other classes' STATIC event handlers. Instances will hook their own events SkyBox.OnDeviceLost(); Terrain.OnDeviceLost(); Water.OnDeviceLost(); Marker.OnDeviceLost(); Camera.OnDeviceLost(); UserInput.OnDeviceLost(); Map.OnDeviceLost(); } /// <summary> /// Device has been reset - reinitialise renderstate variables that /// normally don't get modified each frame. Also call the OnReset() /// methods for all scene objects /// </summary> public static void OnReset() { Debug.WriteLine("Scene.OnReset()"); // Ripple through to other classes' STATIC event handlers. Instances will hook their own events Camera.OnReset(); CameraShip.OnReset(); SkyBox.OnReset(); Terrain.OnReset(); Water.OnReset(); Marker.OnReset(); Map.OnReset(); // enable fog Engine.Device.RenderState.FogEnable = true; Engine.Device.RenderState.FogColor = FogColor; // If we can, use h/w alpha testing. This is faster and prevents any depth-buffering issues // TODO: But remember to test it without!!! if (Engine.Device.DeviceCaps.AlphaCompareCaps.SupportsNotEqual==true) { Engine.Device.RenderState.AlphaTestEnable = true; Engine.Device.RenderState.AlphaFunction = Compare.NotEqual; Engine.Device.RenderState.ReferenceAlpha = unchecked((int)0x00000000); } } #endregion /// <summary> /// Render the whole scene /// </summary> public static void Render(float elapsedTime, float appTime) { ///// Scene.Log.WriteLine("e:" + elapsedTime + " t:" + appTime); // If the game is in suspended animation, count down if (FreezeTime > 0) { FreezeTime -= elapsedTime; if (freezeTime < 0) freezeTime = 0; } // Store the elapsed time in a global property Scene.elapsedTime = elapsedTime; ////Debug.WriteLine(elapsedTime.ToString()); Scene.totalElapsedTime = appTime; //////+= elapsedTime; // Handle any pre-render stuff UserInput.Update(); // Poll the input devices (move camera, etc.) SetWaterColour(); // Adjust the fog colour according to depth Camera.Render(); // Set up the camera matrices Map.CullScene(); // Set up the render batches for objects on map // Render the shadow map texture if (Fx.IsShadowed == true) // if we're using shadows, Map.RenderShadow(); // Render the shadow map // Set the viewport for the 3D scene Engine.Device.Viewport = Camera.SceneViewport; // Render the scene from the camera's point of view bool beginSceneCalled = false; Engine.Device.Clear(ClearFlags.ZBuffer | ClearFlags.Target, Scene.FogColor, 1.0f, 0); // Clear the render target and the zbuffer try { Engine.Device.BeginScene(); beginSceneCalled = true; // Render the skybox FIRST SkyBox.Render(); // Render all non-culled objects in the quadtree, including terrain tiles & water Map.Render(); // Draw any debugging 3D markers Marker.Render(); // Set the viewport for the cameraship panel Engine.Device.Viewport = Camera.PanelViewport; // Render the cockpit panel of the current camera ship CameraShip.RenderCockpit(); } catch (Exception e) { throw new SDKException("Unknown error rendering scene: ", e); } finally { if (beginSceneCalled) Engine.Device.EndScene(); } } /// <summary> /// Adjust the fog colour according to depth, so that surface waters are brighter and bluer than deep waters /// </summary> private static void SetWaterColour() { Color deep = Color.FromArgb(35, 80, 50); // deepest water colour Color shallow = Color.FromArgb(190, 223, 223); // shallowest water colour float interp = Camera.Position.Y / Water.WATERLEVEL; FogColor = Color.FromArgb((int)((shallow.R - deep.R) * interp + deep.R), (int)((shallow.G - deep.G) * interp + deep.G), (int)((shallow.B - deep.B) * interp + deep.B)); Engine.Device.RenderState.FogColor = FogColor; } /// <summary> /// Write out a screenshot as a BMP file /// </summary> /// <param name="filespec"></param> public static void SaveScreenshot(string filespec) { Surface backbuffer = Engine.Device.GetBackBuffer(0, 0, BackBufferType.Mono); SurfaceLoader.Save(filespec, ImageFileFormat.Bmp, backbuffer); backbuffer.Dispose(); } /// <summary> /// Put the creatures (but not camera etc.) into suspended animation for n seconds. /// </summary> /// <param name="seconds">0=unfreeze, n=freeze n seconds, -1=freeze indefinitely</param> public static void Freeze(float seconds) { freezeTime = seconds; } } }
// Created by Paul Gonzalez Becerra using System; using System.Runtime.InteropServices; using Saserdote.Mathematics.Collision; namespace Saserdote.Mathematics { [StructLayout(LayoutKind.Sequential)] public struct Vector3 { #region --- Field Variables --- // Variables public float x; public float y; public float z; public readonly static Vector3 ZERO= new Vector3(0f); public readonly static Vector3 UNIT_X= new Vector3(1f, 0f, 0f); public readonly static Vector3 UNIT_Y= new Vector3(0f, 1f, 0f); public readonly static Vector3 UNIT_Z= new Vector3(0f, 0f, 1f); #endregion // Field Variables #region --- Constructors --- public Vector3(float pmX, float pmY, float pmZ) { x= pmX; y= pmY; z= pmZ; } internal Vector3(float all):this(all, all, all) {} #endregion // Constructors #region --- Methods --- // Converts this vector into a 2d vector, Warning! data loss possible public Vector2 toVector2() { return new Vector2(x, y); } // Converts this vector into a 3d point public Point3f toPoint3f() { return new Point3f(x, y, z); } // Converts this vector into a 3d point public Point3i toPoint3i() { return new Point3i((int)x, (int)y, (int)z); } // Converts this vector into a 2d point public Point2f toPoint2f() { return new Point2f(x, y); } // Converts this vector into a 2d point public Point2i toPoint2i() { return new Point2i((int)x, (int)y); } // Adds the point with the vector to get another point public Point3f add(Point3f pt) { return new Point3f(x+pt.x, y+pt.y, z+pt.z); } // Adds the point with the vector to get another point public Point3i add(Point3i pt) { return new Point3i((int)x+pt.x, (int)y+pt.y, (int)z+pt.z); } // Adds the point with the vector to get another point public Point2f add(Point2f pt) { return new Point2f(x+pt.x, y+pt.y); } // Adds the point with the vector to get another point public Point2i add(Point2i pt) { return new Point2i((int)x+pt.x, (int)y+pt.y); } // Adds the two vectors together public Vector3 add(Vector2 vec) { return new Vector3(x+vec.x, y+vec.y, z); } // Adds the two vectors together public Vector3 add(Vector3 vec) { return new Vector3(x+vec.x, y+vec.y, z+vec.z); } // Subtracts the point with the vector to get another point public Point3f subtract(Point3f pt) { return new Point3f(x-pt.x, y-pt.y, z-pt.z); } // Subtracts the point with the vector to get another point public Point3i subtract(Point3i pt) { return new Point3i((int)x-pt.x, (int)y-pt.y, (int)z-pt.z); } // Subtracts the point with the vector to get another point public Point2f subtract(Point2f pt) { return new Point2f(x-pt.x, y-pt.y); } // Subtracts the point with the vector to get another point public Point2i subtract(Point2i pt) { return new Point2i((int)x-pt.x, (int)y-pt.y); } // Subtracts the two vectors together public Vector3 subtract(Vector2 vec) { return new Vector3(x-vec.x, y-vec.y, z); } // Subtracts the two vectors together public Vector3 subtract(Vector3 vec) { return new Vector3(x-vec.x, y-vec.y, z-vec.z); } // Multiplies the 3d vector to get an appropriate scale public Vector3 multiply(float scale) { return new Vector3(x*scale, y*scale, z*scale); } // Divides the 3d vector to get the appropriate scale public Vector3 divide(float scale) { if(scale== 0) throw new Exception("Dividing by Zero!"); return multiply(1f/scale); } // Gets the dot product of the two given vectors public float getDotProduct(Vector3 vec) { return (x*vec.x)+(y*vec.y)+(z*vec.z); } // Gets the vector that is perpendicular to this vector and the given vector public Vector3 getCrossProduct(Vector3 vec) { return new Vector3((y*vec.z-z*vec.y), (z*vec.x-x*vec.z), (x*vec.y-y*vec.x)); } // Gets the opposite of the current vector public Vector3 negate() { return new Vector3(-1f*x, -1f*y, -1f*z); } // Gets the vector's magnitude public float getMagnitude() { return (float)(Math.Sqrt(getMagnitudeSquared())); } // Gets the vector's magnitude before square rooting it public float getMagnitudeSquared() { return (x*x)+(y*y)+(z*z); } // Normalizes the vector, non-destructive public Vector3 normalize() { // Variables float mag= getMagnitude(); if(mag!= 0f) return new Vector3(x/mag, y/mag, z/mag); else return Vector3.ZERO; } // Normalizes the vector, destructive public Vector3 normalizeDest() { // Variables float mag= getMagnitude(); if(mag!= 0f) { x/= mag; y/= mag; z/= mag; } return this; } // Finds if the two vectors are equal public bool equals(Vector3 vec) { return (x== vec.x && y== vec.y && z== vec.z); } //public Vector3 rotateXAxis(float radians); //public Vector3 rotateYAxis(float radians); //public Vector3 rotateZAxis(float radians); #endregion // Methods #region --- Inherited Methods --- // Finds if the object is equal to this vector public override bool Equals(object obj) { if(obj== null) return false; if(obj is Vector3) return equals((Vector3)obj); return false; } // Gets the hash code public override int GetHashCode() { return ((int)x^(int)y^(int)z); } // Prints out what the vector's fields are public override string ToString() { return "X:"+x+",Y:"+y+",Z:"+z; } #endregion // Inherited Methods #region --- Operators --- // Equality operators public static bool operator ==(Vector3 left, Vector3 right) { return left.equals(right); } // Inequality operators public static bool operator !=(Vector3 left, Vector3 right) { return !left.equals(right); } // Less than operators public static bool operator <(Vector3 left, Vector3 right) { return (left.getMagnitudeSquared()< right.getMagnitudeSquared()); } public static bool operator <(Vector3 left, float right) { return (left.getMagnitude()< right); } public static bool operator <(float left, Vector3 right) { return (left< right.getMagnitude()); } // Less than or equal to operators public static bool operator <=(Vector3 left, Vector3 right) { return (left.getMagnitudeSquared()<= right.getMagnitudeSquared()); } public static bool operator <=(Vector3 left, float right) { return (left.getMagnitude()<= right); } public static bool operator <=(float left, Vector3 right) { return (left<= right.getMagnitude()); } // Greater than operators public static bool operator >(Vector3 left, Vector3 right) { return (left.getMagnitudeSquared()> right.getMagnitudeSquared()); } public static bool operator >(Vector3 left, float right) { return (left.getMagnitude()> right); } public static bool operator >(float left, Vector3 right) { return (left> right.getMagnitude()); } // Greater than or equal to operators public static bool operator >=(Vector3 left, Vector3 right) { return (left.getMagnitudeSquared()>= right.getMagnitudeSquared()); } public static bool operator >=(Vector3 left, float right) { return (left.getMagnitude()>= right); } public static bool operator >=(float left, Vector3 right) { return (left>= right.getMagnitude()); } // Addition operators public static Vector3 operator +(Vector3 left, Vector3 right) { return left.add(right); } public static Vector3 operator +(Vector3 left, Vector2 right) { return left.add(right); } public static Point3f operator +(Vector3 left, Point3f right) { return left.add(right); } public static Point3i operator +(Vector3 left, Point3i right) { return left.add(right); } public static Point2f operator +(Vector3 left, Point2f right) { return left.add(right); } public static Point2i operator +(Vector3 left, Point2i right) { return left.add(right); } // Subtraction operators public static Vector3 operator -(Vector3 left, Vector3 right) { return left.subtract(right); } public static Vector3 operator -(Vector3 left, Vector2 right) { return left.subtract(right); } public static Point3f operator -(Vector3 left, Point3f right) { return left.subtract(right); } public static Point3i operator -(Vector3 left, Point3i right) { return left.subtract(right); } public static Point2f operator -(Vector3 left, Point2f right) { return left.subtract(right); } public static Point2i operator -(Vector3 left, Point2i right) { return left.subtract(right); } // Multiplication operators public static float operator *(Vector3 left, Vector3 right) { return left.getDotProduct(right); } public static Vector3 operator *(Vector3 left, float right) { return left.multiply(right); } public static Vector3 operator *(float left, Vector3 right) { return right.multiply(left); } public static Vector3 operator *(Vector3 left, int right) { return left.multiply((float)right); } public static Vector3 operator *(int left, Vector3 right) { return right.multiply((float)left); } public static bool operator *(Vector3 left, BoundingVolume right) { return right.contains(left); } // Division operators public static Vector3 operator /(Vector3 left, float right) { return left.divide(right); } public static Vector3 operator /(Vector3 left, int right) { return left.divide((float)right); } // Unknown named operators public static Vector3 operator ^(Vector3 left, Vector3 right) { return left.getCrossProduct(right); } // Uniary operators public static Vector3 operator -(Vector3 self) { return self.negate(); } public static Vector3 operator ~(Vector3 self) { return self.normalize(); } // Convertsion operator // [Vector3 to Vector2] public static explicit operator Vector2(Vector3 castee) { return castee.toVector2(); } // [Vector3 to Point3f] public static explicit operator Point3f(Vector3 castee) { return castee.toPoint3f(); } // [Vector3 to Point3i] public static explicit operator Point3i(Vector3 castee) { return castee.toPoint3i(); } // [Vector3 to Point2f] public static explicit operator Point2f(Vector3 castee) { return castee.toPoint2f(); } // [Vector3 to Point2i] public static explicit operator Point2i(Vector3 castee) { return castee.toPoint2i(); } #endregion // Operators } } // End of File
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Game.Online.API; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Screens.OnlinePlay.Match.Components; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Users; using osuTK; using Footer = osu.Game.Screens.OnlinePlay.Match.Components.Footer; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsRoomSubScreen : RoomSubScreen { public override string Title { get; } public override string ShortTitle => "playlist"; [Resolved(typeof(Room), nameof(Room.RoomID))] private Bindable<long?> roomId { get; set; } [Resolved(typeof(Room), nameof(Room.Playlist))] private BindableList<PlaylistItem> playlist { get; set; } private MatchSettingsOverlay settingsOverlay; private MatchLeaderboard leaderboard; private OverlinedHeader participantsHeader; private GridContainer mainContent; public PlaylistsRoomSubScreen(Room room) { Title = room.RoomID.Value == null ? "New playlist" : room.Name.Value; Activity.Value = new UserActivity.InLobby(room); } [BackgroundDependencyLoader] private void load() { AddRangeInternal(new Drawable[] { mainContent = new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Horizontal = 105, Vertical = 20 }, Child = new GridContainer { RelativeSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(), }, Content = new[] { new Drawable[] { new Match.Components.Header() }, new Drawable[] { participantsHeader = new OverlinedHeader("Participants") { ShowLine = false } }, new Drawable[] { new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Margin = new MarginPadding { Top = 5 }, Child = new ParticipantsDisplay(Direction.Horizontal) { Details = { BindTarget = participantsHeader.Details } } } }, new Drawable[] { new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Right = 5 }, Child = new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new OverlinedPlaylistHeader(), }, new Drawable[] { new DrawableRoomPlaylistWithResults { RelativeSizeAxes = Axes.Both, Items = { BindTarget = playlist }, SelectedItem = { BindTarget = SelectedItem }, RequestShowResults = item => { Debug.Assert(roomId.Value != null); ParentScreen?.Push(new PlaylistsResultsScreen(null, roomId.Value.Value, item, false)); } } }, }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(), } } }, null, new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new[] { UserModsSection = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Margin = new MarginPadding { Bottom = 10 }, Children = new Drawable[] { new OverlinedHeader("Extra mods"), new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(10, 0), Children = new Drawable[] { new UserModSelectButton { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 90, Text = "Select", Action = ShowUserModSelect, }, new ModDisplay { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Current = UserMods, Scale = new Vector2(0.8f), }, } } } }, }, new Drawable[] { new OverlinedHeader("Leaderboard") }, new Drawable[] { leaderboard = new MatchLeaderboard { RelativeSizeAxes = Axes.Both }, }, new Drawable[] { new OverlinedHeader("Chat"), }, new Drawable[] { new MatchChatDisplay { RelativeSizeAxes = Axes.Both } } }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.Relative, size: 0.4f, minSize: 120), } }, null }, }, ColumnDimensions = new[] { new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 400), new Dimension(), new Dimension(GridSizeMode.Relative, size: 0.5f, maxSize: 600), new Dimension(), } } } }, } } }, new Drawable[] { new Footer { OnStart = StartPlay } } }, RowDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), } }, settingsOverlay = new PlaylistsMatchSettingsOverlay { RelativeSizeAxes = Axes.Both, EditPlaylist = () => { if (this.IsCurrentScreen()) this.Push(new PlaylistsSongSelect()); }, State = { Value = roomId.Value == null ? Visibility.Visible : Visibility.Hidden } } }); if (roomId.Value == null) { // A new room is being created. // The main content should be hidden until the settings overlay is hidden, signaling the room is ready to be displayed. mainContent.Hide(); settingsOverlay.State.BindValueChanged(visibility => { if (visibility.NewValue == Visibility.Hidden) mainContent.Show(); }, true); } } [Resolved] private IAPIProvider api { get; set; } protected override void LoadComplete() { base.LoadComplete(); roomId.BindValueChanged(id => { if (id.NewValue == null) settingsOverlay.Show(); else { settingsOverlay.Hide(); // Set the first playlist item. // This is scheduled since updating the room and playlist may happen in an arbitrary order (via Room.CopyFrom()). Schedule(() => SelectedItem.Value = playlist.FirstOrDefault()); } }, true); } protected override Screen CreateGameplayScreen() => new PlayerLoader(() => new PlaylistsPlayer(SelectedItem.Value) { Exited = () => leaderboard.RefreshScores() }); } }
namespace android.net { [global::MonoJavaBridge.JavaClass()] public partial class ConnectivityManager : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ConnectivityManager() { InitJNI(); } protected ConnectivityManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _isNetworkTypeValid5123; public static bool isNetworkTypeValid(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._isNetworkTypeValid5123, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setNetworkPreference5124; public virtual void setNetworkPreference(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.ConnectivityManager._setNetworkPreference5124, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._setNetworkPreference5124, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getNetworkPreference5125; public virtual int getNetworkPreference() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.ConnectivityManager._getNetworkPreference5125); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._getNetworkPreference5125); } internal static global::MonoJavaBridge.MethodId _getActiveNetworkInfo5126; public virtual global::android.net.NetworkInfo getActiveNetworkInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager._getActiveNetworkInfo5126)) as android.net.NetworkInfo; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._getActiveNetworkInfo5126)) as android.net.NetworkInfo; } internal static global::MonoJavaBridge.MethodId _getNetworkInfo5127; public virtual global::android.net.NetworkInfo getNetworkInfo(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager._getNetworkInfo5127, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.NetworkInfo; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._getNetworkInfo5127, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.NetworkInfo; } internal static global::MonoJavaBridge.MethodId _getAllNetworkInfo5128; public virtual global::android.net.NetworkInfo[] getAllNetworkInfo() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.net.NetworkInfo>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager._getAllNetworkInfo5128)) as android.net.NetworkInfo[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.net.NetworkInfo>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._getAllNetworkInfo5128)) as android.net.NetworkInfo[]; } internal static global::MonoJavaBridge.MethodId _startUsingNetworkFeature5129; public virtual int startUsingNetworkFeature(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.ConnectivityManager._startUsingNetworkFeature5129, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._startUsingNetworkFeature5129, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _stopUsingNetworkFeature5130; public virtual int stopUsingNetworkFeature(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.ConnectivityManager._stopUsingNetworkFeature5130, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._stopUsingNetworkFeature5130, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _requestRouteToHost5131; public virtual bool requestRouteToHost(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.ConnectivityManager._requestRouteToHost5131, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._requestRouteToHost5131, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getBackgroundDataSetting5132; public virtual bool getBackgroundDataSetting() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.ConnectivityManager._getBackgroundDataSetting5132); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.ConnectivityManager.staticClass, global::android.net.ConnectivityManager._getBackgroundDataSetting5132); } public static global::java.lang.String CONNECTIVITY_ACTION { get { return "android.net.conn.CONNECTIVITY_CHANGE"; } } public static global::java.lang.String EXTRA_NETWORK_INFO { get { return "networkInfo"; } } public static global::java.lang.String EXTRA_IS_FAILOVER { get { return "isFailover"; } } public static global::java.lang.String EXTRA_OTHER_NETWORK_INFO { get { return "otherNetwork"; } } public static global::java.lang.String EXTRA_NO_CONNECTIVITY { get { return "noConnectivity"; } } public static global::java.lang.String EXTRA_REASON { get { return "reason"; } } public static global::java.lang.String EXTRA_EXTRA_INFO { get { return "extraInfo"; } } public static global::java.lang.String ACTION_BACKGROUND_DATA_SETTING_CHANGED { get { return "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"; } } public static int TYPE_MOBILE { get { return 0; } } public static int TYPE_WIFI { get { return 1; } } public static int TYPE_MOBILE_MMS { get { return 2; } } public static int TYPE_MOBILE_SUPL { get { return 3; } } public static int TYPE_MOBILE_DUN { get { return 4; } } public static int TYPE_MOBILE_HIPRI { get { return 5; } } public static int TYPE_WIMAX { get { return 6; } } public static int DEFAULT_NETWORK_PREFERENCE { get { return 1; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.ConnectivityManager.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/ConnectivityManager")); global::android.net.ConnectivityManager._isNetworkTypeValid5123 = @__env.GetStaticMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "isNetworkTypeValid", "(I)Z"); global::android.net.ConnectivityManager._setNetworkPreference5124 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "setNetworkPreference", "(I)V"); global::android.net.ConnectivityManager._getNetworkPreference5125 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "getNetworkPreference", "()I"); global::android.net.ConnectivityManager._getActiveNetworkInfo5126 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "getActiveNetworkInfo", "()Landroid/net/NetworkInfo;"); global::android.net.ConnectivityManager._getNetworkInfo5127 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "getNetworkInfo", "(I)Landroid/net/NetworkInfo;"); global::android.net.ConnectivityManager._getAllNetworkInfo5128 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "getAllNetworkInfo", "()[Landroid/net/NetworkInfo;"); global::android.net.ConnectivityManager._startUsingNetworkFeature5129 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "startUsingNetworkFeature", "(ILjava/lang/String;)I"); global::android.net.ConnectivityManager._stopUsingNetworkFeature5130 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "stopUsingNetworkFeature", "(ILjava/lang/String;)I"); global::android.net.ConnectivityManager._requestRouteToHost5131 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "requestRouteToHost", "(II)Z"); global::android.net.ConnectivityManager._getBackgroundDataSetting5132 = @__env.GetMethodIDNoThrow(global::android.net.ConnectivityManager.staticClass, "getBackgroundDataSetting", "()Z"); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Framework.Client; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes.Types; namespace OpenSim.Region.Framework.Scenes { public class SceneViewer : ISceneViewer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected ScenePresence m_presence; protected UpdateQueue m_partsUpdateQueue = new UpdateQueue(); protected Queue<SceneObjectGroup> m_pendingObjects; protected Dictionary<UUID, ScenePartUpdate> m_updateTimes = new Dictionary<UUID, ScenePartUpdate>(); public SceneViewer() { } public SceneViewer(ScenePresence presence) { m_presence = presence; } /// <summary> /// Add the part to the queue of parts for which we need to send an update to the client /// </summary> /// <param name="part"></param> public void QueuePartForUpdate(SceneObjectPart part) { // if (part.IsAttachment) // m_log.DebugFormat("[SCENE VIEWER]: Queueing part {0} {1} for update", part.Name, part.LocalId); lock (m_partsUpdateQueue) { m_partsUpdateQueue.Enqueue(part); } } public void SendPrimUpdates() { if (m_pendingObjects == null) { if (!m_presence.IsChildAgent || (m_presence.Scene.m_seeIntoRegionFromNeighbor)) { m_pendingObjects = new Queue<SceneObjectGroup>(); foreach (EntityBase e in m_presence.Scene.Entities) { if (e is SceneObjectGroup) m_pendingObjects.Enqueue((SceneObjectGroup)e); } } } while (m_pendingObjects != null && m_pendingObjects.Count > 0) { SceneObjectGroup g = m_pendingObjects.Dequeue(); // This is where we should check for draw distance // do culling and stuff. Problem with that is that until // we recheck in movement, that won't work right. // So it's not implemented now. // // Don't even queue if we have sent this one // if (!m_updateTimes.ContainsKey(g.UUID)) g.ScheduleFullUpdateToAvatar(m_presence); } while (m_partsUpdateQueue.Count > 0) { SceneObjectPart part = m_partsUpdateQueue.Dequeue(); if (part.ParentGroup == null || part.ParentGroup.IsDeleted) continue; if (m_updateTimes.ContainsKey(part.UUID)) { ScenePartUpdate update = m_updateTimes[part.UUID]; // We deal with the possibility that two updates occur at // the same unix time at the update point itself. if ((update.LastFullUpdateTime < part.TimeStampFull) || part.IsAttachment) { // m_log.DebugFormat( // "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampFull); part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID)); // We'll update to the part's timestamp rather than // the current time to avoid the race condition // whereby the next tick occurs while we are doing // this update. If this happened, then subsequent // updates which occurred on the same tick or the // next tick of the last update would be ignored. update.LastFullUpdateTime = part.TimeStampFull; } else if (update.LastTerseUpdateTime <= part.TimeStampTerse) { // m_log.DebugFormat(AddFullUpdateToAvatar // "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampTerse); part.SendTerseUpdateToClient(m_presence.ControllingClient); update.LastTerseUpdateTime = part.TimeStampTerse; } } else { //never been sent to client before so do full update ScenePartUpdate update = new ScenePartUpdate(); update.FullID = part.UUID; update.LastFullUpdateTime = part.TimeStampFull; m_updateTimes.Add(part.UUID, update); // Attachment handling // if (part.ParentGroup.RootPart.Shape.PCode == 9 && part.ParentGroup.RootPart.Shape.State != 0) { if (part != part.ParentGroup.RootPart) continue; part.ParentGroup.SendFullUpdateToClient(m_presence.ControllingClient); continue; } part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID)); } } } public void Reset() { if (m_pendingObjects != null) { lock (m_pendingObjects) { m_pendingObjects.Clear(); m_pendingObjects = null; } } } public void Close() { lock (m_updateTimes) { m_updateTimes.Clear(); } lock (m_partsUpdateQueue) { m_partsUpdateQueue.Clear(); } Reset(); } public class ScenePartUpdate { public UUID FullID; public uint LastFullUpdateTime; public uint LastTerseUpdateTime; public ScenePartUpdate() { FullID = UUID.Zero; LastFullUpdateTime = 0; LastTerseUpdateTime = 0; } } } }
#region Using Directives using System; using System.IO; using System.Windows.Forms; using System.Globalization; using Microsoft.Practices.ComponentModel; using Microsoft.Practices.RecipeFramework; using Microsoft.Practices.RecipeFramework.Library; using Microsoft.Practices.RecipeFramework.Services; using Microsoft.Practices.RecipeFramework.VisualStudio; using Microsoft.Practices.RecipeFramework.VisualStudio.Templates; using EnvDTE; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.SharePoint; #endregion namespace SPALM.SPSF.Library.Actions { /// <summary> /// </summary> [ServiceDependency(typeof(DTE))] public class ShowProperties : ConfigurableAction { private ProjectItem projectItem; private Project project; [Input(Required = false)] public ProjectItem SelectedItem { get { return projectItem; } set { projectItem = value; } } [Input(Required = false)] public Project SelectedProject { get { return project; } set { project = value; } } protected string GetBasePath() { return base.GetService<IConfigurationService>(true).BasePath; } public object GetService(object serviceProvider, System.Type type) { return GetService(serviceProvider, type.GUID); } public object GetService(object serviceProviderObject, System.Guid guid) { object service = null; Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider = null; IntPtr serviceIntPtr; int hr = 0; Guid SIDGuid; Guid IIDGuid; SIDGuid = guid; IIDGuid = SIDGuid; serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)serviceProviderObject; hr = serviceProvider.QueryService(ref SIDGuid, ref IIDGuid, out serviceIntPtr); if (hr != 0) { System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(hr); } else if (!serviceIntPtr.Equals(IntPtr.Zero)) { service = System.Runtime.InteropServices.Marshal.GetObjectForIUnknown(serviceIntPtr); System.Runtime.InteropServices.Marshal.Release(serviceIntPtr); } return service; } public override void Execute() { DTE service = (DTE)this.GetService(typeof(DTE)); try { if (projectItem != null) { Helpers.LogMessage(service, this, "*********** SharePointService Properties ********************"); try { ISharePointProjectService projectService = Helpers2.GetSharePointProjectService(service); ISharePointProject sharePointProject = projectService.Convert<EnvDTE.Project, ISharePointProject>(project); try { //is it a feature ISharePointProjectFeature sharePointFeature = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectFeature>(projectItem); } catch { } try { //is it a feature ISharePointProjectItem sharePointItem = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectItem>(projectItem); } catch { } try { //is it a feature ISharePointProjectItemFile sharePointItemFile = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectItemFile>(projectItem); } catch { } try { //is it a mapped folder IMappedFolder sharePointMappedFolder = projectService.Convert<EnvDTE.ProjectItem, IMappedFolder>(projectItem); } catch { } try { //is it a mapped folder ISharePointProjectPackage sharePointProjectPackage = projectService.Convert<EnvDTE.ProjectItem, ISharePointProjectPackage>(projectItem); } catch { } } catch{} //codelements Helpers.LogMessage(service, this, "*********** EnvDTE CodeElements ********************"); foreach (CodeElement codeElement in projectItem.FileCodeModel.CodeElements) { try { Helpers.LogMessage(service, this, "codeElement.FullName: " + codeElement.FullName); Helpers.LogMessage(service, this, "codeElement.Type: " + codeElement.GetType().ToString()); Helpers.LogMessage(service, this, "codeElement.Kind: " + codeElement.Kind.ToString()); } catch {} } Helpers.LogMessage(service, this, "*********** EnvDTE Properties ********************"); for (int i = 0; i < projectItem.Properties.Count; i++) { try { string name = projectItem.Properties.Item(i).Name; string value = ""; try { value = projectItem.Properties.Item(i).Value.ToString(); } catch (Exception) { } Helpers.LogMessage(service, this, name + "=" + value); } catch (Exception) { } } } else if (project != null) { for (int i = 0; i < project.Properties.Count; i++) { try { string name = project.Properties.Item(i).Name; string value = ""; try { value = project.Properties.Item(i).Value.ToString(); } catch (Exception) { } Helpers.LogMessage(service, this, name + "=" + value); if (project.Properties.Item(i).Collection.Count > 0) { } } catch (Exception) { } } } } catch (Exception ex) { Helpers.LogMessage(service, this, ex.ToString()); } } /// <summary> /// Removes the previously added reference, if it was created /// </summary> public override void Undo() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AbovetheTreeline.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) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Data.Tables.Models; using Azure.Data.Tables.Sas; using NUnit.Framework; namespace Azure.Data.Tables.Tests { /// <summary> /// The suite of tests for the <see cref="TableServiceClient"/> class. /// </summary> /// <remarks> /// These tests have a dependency on live Azure services and may incur costs for the associated /// Azure subscription. /// </remarks> public class TableServiceClientLiveTests : TableServiceLiveTestsBase { public TableServiceClientLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */) { } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateTableIfNotExists() { // Call CreateTableIfNotExists when the table already exists. Assert.That(async () => await CosmosThrottleWrapper(async () => await service.CreateTableIfNotExistsAsync(tableName).ConfigureAwait(false)), Throws.Nothing); // Call CreateTableIfNotExists when the table does not already exists. var newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); try { TableItem table = await CosmosThrottleWrapper(async () => await service.CreateTableIfNotExistsAsync(newTableName).ConfigureAwait(false)); Assert.That(table.TableName, Is.EqualTo(newTableName)); } finally { // Delete the table using the TableClient method. await CosmosThrottleWrapper(async () => await service.DeleteTableAsync(newTableName).ConfigureAwait(false)); } } [RecordedTest] public void ValidateAccountSasCredentialsWithPermissions() { // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(TestEnvironment.StorageAccountName, TestEnvironment.PrimaryStorageAccountKey); // Build a shared access signature with only Delete permissions and access to all service resource types. TableAccountSasBuilder sasDelete = service.GetSasBuilder(TableAccountSasPermissions.Delete, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); string tokenDelete = sasDelete.Sign(credential); // Build a shared access signature with the Write and Delete permissions and access to all service resource types. TableAccountSasBuilder sasWriteDelete = service.GetSasBuilder(TableAccountSasPermissions.Write, TableAccountSasResourceTypes.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); string tokenWriteDelete = sasWriteDelete.Sign(credential); // Build SAS URIs. UriBuilder sasUriDelete = new UriBuilder(TestEnvironment.StorageUri) { Query = tokenDelete }; UriBuilder sasUriWriteDelete = new UriBuilder(TestEnvironment.StorageUri) { Query = tokenWriteDelete }; // Create the TableServiceClients using the SAS URIs. var sasAuthedServiceDelete = InstrumentClient(new TableServiceClient(sasUriDelete.Uri, InstrumentClientOptions(new TableClientOptions()))); var sasAuthedServiceWriteDelete = InstrumentClient(new TableServiceClient(sasUriWriteDelete.Uri, InstrumentClientOptions(new TableClientOptions()))); // Validate that we are unable to create a table using the SAS URI with only Delete permissions. var sasTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); Assert.That(async () => await sasAuthedServiceDelete.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.Forbidden)); // Validate that we are able to create a table using the SAS URI with Write and Delete permissions. Assert.That(async () => await sasAuthedServiceWriteDelete.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing); // Validate that we are able to delete a table using the SAS URI with only Delete permissions. Assert.That(async () => await sasAuthedServiceDelete.DeleteTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing); } [RecordedTest] public void ValidateAccountSasCredentialsWithResourceTypes() { // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(TestEnvironment.StorageAccountName, TestEnvironment.PrimaryStorageAccountKey); // Build a shared access signature with all permissions and access to only Service resource types. TableAccountSasBuilder sasService = service.GetSasBuilder(TableAccountSasPermissions.All, TableAccountSasResourceTypes.Service, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); string tokenService = sasService.Sign(credential); // Build a shared access signature with all permissions and access to Service and Container resource types. TableAccountSasBuilder sasServiceContainer = service.GetSasBuilder(TableAccountSasPermissions.All, TableAccountSasResourceTypes.Service | TableAccountSasResourceTypes.Container, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); string tokenServiceContainer = sasServiceContainer.Sign(credential); // Build SAS URIs. UriBuilder sasUriService = new UriBuilder(TestEnvironment.StorageUri) { Query = tokenService }; UriBuilder sasUriServiceContainer = new UriBuilder(TestEnvironment.StorageUri) { Query = tokenServiceContainer }; // Create the TableServiceClients using the SAS URIs. var sasAuthedServiceClientService = InstrumentClient(new TableServiceClient(sasUriService.Uri, InstrumentClientOptions(new TableClientOptions()))); var sasAuthedServiceClientServiceContainer = InstrumentClient(new TableServiceClient(sasUriServiceContainer.Uri, InstrumentClientOptions(new TableClientOptions()))); // Validate that we are unable to create a table using the SAS URI with access to Service resource types. var sasTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); Assert.That(async () => await sasAuthedServiceClientService.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.Forbidden)); // Validate that we are able to create a table using the SAS URI with access to Service and Container resource types. Assert.That(async () => await sasAuthedServiceClientServiceContainer.CreateTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing); // Validate that we are able to get table service properties using the SAS URI with access to Service resource types. Assert.That(async () => await sasAuthedServiceClientService.GetPropertiesAsync().ConfigureAwait(false), Throws.Nothing); // Validate that we are able to get table service properties using the SAS URI with access to Service and Container resource types. Assert.That(async () => await sasAuthedServiceClientService.GetPropertiesAsync().ConfigureAwait(false), Throws.Nothing); // Validate that we are able to delete a table using the SAS URI with access to Service and Container resource types. Assert.That(async () => await sasAuthedServiceClientServiceContainer.DeleteTableAsync(sasTableName).ConfigureAwait(false), Throws.Nothing); } /// <summary> /// Validates the functionality of the TableServiceClient. /// </summary> [RecordedTest] [TestCase(null)] [TestCase(5)] public async Task GetTablesReturnsTablesWithAndWithoutPagination(int? pageCount) { var createdTables = new List<string>() { tableName }; try { // Create some extra tables. for (int i = 0; i < 10; i++) { var table = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); createdTables.Add(table); await CosmosThrottleWrapper(async () => await service.CreateTableAsync(table).ConfigureAwait(false)); } // Get the table list. var remainingItems = createdTables.Count; await foreach (var page in service.GetTablesAsync(/*maxPerPage: pageCount*/).AsPages(pageSizeHint: pageCount)) { Assert.That(page.Values, Is.Not.Empty); if (pageCount.HasValue) { Assert.That(page.Values.Count, Is.EqualTo(Math.Min(pageCount.Value, remainingItems))); remainingItems -= page.Values.Count; } else { Assert.That(page.Values.Count, Is.EqualTo(createdTables.Count)); } Assert.That(page.Values.All(r => createdTables.Contains(r.TableName))); } } finally { foreach (var table in createdTables) { await service.DeleteTableAsync(table); } } } /// <summary> /// Validates the functionality of the TableServiceClient. /// </summary> [RecordedTest] public async Task GetTablesReturnsTablesWithFilter() { var createdTables = new List<string>(); try { // Create some extra tables. for (int i = 0; i < 10; i++) { var table = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); await CosmosThrottleWrapper(async () => await service.CreateTableAsync(table).ConfigureAwait(false)); createdTables.Add(table); } // Query with a filter. var tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{tableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList(); Assert.That(() => tableResponses, Is.Not.Empty); Assert.That(() => tableResponses.Select(r => r.TableName), Contains.Item(tableName)); } finally { foreach (var table in createdTables) { await service.DeleteTableAsync(table); } } } [RecordedTest] public async Task GetPropertiesReturnsProperties() { // Get current properties TableServiceProperties responseToChange = await service.GetPropertiesAsync().ConfigureAwait(false); // Change a property responseToChange.Logging.Read = !responseToChange.Logging.Read; // Set properties to the changed one await service.SetPropertiesAsync(responseToChange).ConfigureAwait(false); // Get configured properties // A delay is required to ensure properties are updated in the service TableServiceProperties changedResponse = await RetryUntilExpectedResponse( async () => await service.GetPropertiesAsync().ConfigureAwait(false), result => result.Value.Logging.Read == responseToChange.Logging.Read, 15000).ConfigureAwait(false); // Test each property CompareServiceProperties(responseToChange, changedResponse); } [RecordedTest] public async Task GetTableServiceStatsReturnsStats() { // Get statistics TableServiceStatistics stats = await service.GetStatisticsAsync().ConfigureAwait(false); // Test that the secondary location is live Assert.AreEqual(new TableGeoReplicationStatus("live"), stats.GeoReplication.Status); } private void CompareServiceProperties(TableServiceProperties expected, TableServiceProperties actual) { Assert.AreEqual(expected.Logging.Read, actual.Logging.Read); Assert.AreEqual(expected.Logging.Version, actual.Logging.Version); Assert.AreEqual(expected.Logging.Write, actual.Logging.Write); Assert.AreEqual(expected.Logging.Delete, actual.Logging.Delete); Assert.AreEqual(expected.Logging.RetentionPolicy.Enabled, actual.Logging.RetentionPolicy.Enabled); Assert.AreEqual(expected.Logging.RetentionPolicy.Days, actual.Logging.RetentionPolicy.Days); Assert.AreEqual(expected.HourMetrics.Enabled, actual.HourMetrics.Enabled); Assert.AreEqual(expected.HourMetrics.Version, actual.HourMetrics.Version); Assert.AreEqual(expected.HourMetrics.IncludeApis, actual.HourMetrics.IncludeApis); Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Enabled, actual.HourMetrics.RetentionPolicy.Enabled); Assert.AreEqual(expected.HourMetrics.RetentionPolicy.Days, actual.HourMetrics.RetentionPolicy.Days); Assert.AreEqual(expected.MinuteMetrics.Enabled, actual.MinuteMetrics.Enabled); Assert.AreEqual(expected.MinuteMetrics.Version, actual.MinuteMetrics.Version); Assert.AreEqual(expected.MinuteMetrics.IncludeApis, actual.MinuteMetrics.IncludeApis); Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Enabled, actual.MinuteMetrics.RetentionPolicy.Enabled); Assert.AreEqual(expected.MinuteMetrics.RetentionPolicy.Days, actual.MinuteMetrics.RetentionPolicy.Days); Assert.AreEqual(expected.Cors.Count, actual.Cors.Count); for (int i = 0; i < expected.Cors.Count; i++) { TableCorsRule expectedRule = expected.Cors[i]; TableCorsRule actualRule = actual.Cors[i]; Assert.AreEqual(expectedRule.AllowedHeaders, actualRule.AllowedHeaders); Assert.AreEqual(expectedRule.AllowedMethods, actualRule.AllowedMethods); Assert.AreEqual(expectedRule.AllowedOrigins, actualRule.AllowedOrigins); Assert.AreEqual(expectedRule.MaxAgeInSeconds, actualRule.MaxAgeInSeconds); Assert.AreEqual(expectedRule.ExposedHeaders, actualRule.ExposedHeaders); } } } }
// 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.Runtime.InteropServices; namespace System.Management { //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Represents different collections of management objects /// retrieved through WMI. The objects in this collection are of <see cref='System.Management.ManagementBaseObject'/>-derived types, including <see cref='System.Management.ManagementObject'/> and <see cref='System.Management.ManagementClass'/> /// .</para> /// <para> The collection can be the result of a WMI /// query executed through a <see cref='System.Management.ManagementObjectSearcher'/> object, or an enumeration of /// management objects of a specified type retrieved through a <see cref='System.Management.ManagementClass'/> representing that type. /// In addition, this can be a collection of management objects related in a specified /// way to a specific management object - in this case the collection would /// be retrieved through a method such as <see cref='System.Management.ManagementObject.GetRelated()'/>.</para> /// <para>The collection can be walked using the <see cref='System.Management.ManagementObjectCollection.ManagementObjectEnumerator'/> and objects in it can be inspected or /// manipulated for various management tasks.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to enumerate instances of a ManagementClass object. /// class Sample_ManagementObjectCollection /// { /// public static int Main(string[] args) { /// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); /// ManagementObjectCollection disks = diskClass.GetInstances(); /// foreach (ManagementObject disk in disks) { /// Console.WriteLine("Disk = " + disk["deviceid"]); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// /// ' This example demonstrates how to enumerate instances of a ManagementClass object. /// Class Sample_ManagementObjectCollection /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// Dim disks As ManagementObjectCollection = diskClass.GetInstances() /// Dim disk As ManagementObject /// For Each disk In disks /// Console.WriteLine("Disk = " &amp; disk("deviceid").ToString()) /// Next disk /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// public class ManagementObjectCollection : ICollection, IEnumerable, IDisposable { private static readonly string name = typeof(ManagementObjectCollection).FullName; //fields internal ManagementScope scope; internal EnumerationOptions options; private readonly IEnumWbemClassObject enumWbem; //holds WMI enumerator for this collection private bool isDisposed = false; //Constructor internal ManagementObjectCollection( ManagementScope scope, EnumerationOptions options, IEnumWbemClassObject enumWbem) { if (null != options) this.options = (EnumerationOptions)options.Clone(); else this.options = new EnumerationOptions(); if (null != scope) this.scope = (ManagementScope)scope.Clone(); else this.scope = ManagementScope._Clone(null); this.enumWbem = enumWbem; } /// <summary> /// <para>Disposes of resources the object is holding. This is the destructor for the object.</para> /// </summary> ~ManagementObjectCollection() { Dispose(false); } /// <summary> /// Releases resources associated with this object. After this /// method has been called, an attempt to use this object will /// result in an ObjectDisposedException being thrown. /// </summary> public void Dispose() { if (!isDisposed) { Dispose(true); } } private void Dispose(bool disposing) { if (disposing) { GC.SuppressFinalize(this); isDisposed = true; } Marshal.ReleaseComObject(enumWbem); } // //ICollection properties & methods // /// <summary> /// <para>Represents the number of objects in the collection.</para> /// </summary> /// <value> /// <para>The number of objects in the collection.</para> /// </value> /// <remarks> /// <para>This property is very expensive - it requires that /// all members of the collection be enumerated.</para> /// </remarks> public int Count { get { if (isDisposed) throw new ObjectDisposedException(name); // // We can not use foreach since it _always_ calls Dispose on the collection // invalidating the IEnumWbemClassObject pointers. // We prevent this by doing a manual walk of the collection. // int count = 0; IEnumerator enumCol = this.GetEnumerator(); while (enumCol.MoveNext() == true) { count++; } return count; } } /// <summary> /// <para>Represents whether the object is synchronized.</para> /// </summary> /// <value> /// <para><see langword='true'/>, if the object is synchronized; /// otherwise, <see langword='false'/>.</para> /// </value> public bool IsSynchronized { get { if (isDisposed) throw new ObjectDisposedException(name); return false; } } /// <summary> /// <para>Represents the object to be used for synchronization.</para> /// </summary> /// <value> /// <para> The object to be used for synchronization.</para> /// </value> public object SyncRoot { get { if (isDisposed) throw new ObjectDisposedException(name); return this; } } /// <overload> /// Copies the collection to an array. /// </overload> /// <summary> /// <para> Copies the collection to an array.</para> /// </summary> /// <param name='array'>An array to copy to. </param> /// <param name='index'>The index to start from. </param> public void CopyTo(Array array, int index) { if (isDisposed) throw new ObjectDisposedException(name); if (null == array) throw new ArgumentNullException(nameof(array)); if ((index < array.GetLowerBound(0)) || (index > array.GetUpperBound(0))) throw new ArgumentOutOfRangeException(nameof(index)); // Since we don't know the size until we've enumerated // we'll have to dump the objects in a list first then // try to copy them in. int capacity = array.Length - index; int numObjects = 0; ArrayList arrList = new ArrayList(); ManagementObjectEnumerator en = this.GetEnumerator(); ManagementBaseObject obj; while (en.MoveNext()) { obj = en.Current; arrList.Add(obj); numObjects++; if (numObjects > capacity) throw new ArgumentException(null, nameof(index)); } // If we get here we are OK. Now copy the list to the array arrList.CopyTo(array, index); return; } /// <summary> /// <para>Copies the items in the collection to a <see cref='System.Management.ManagementBaseObject'/> /// array.</para> /// </summary> /// <param name='objectCollection'>The target array.</param> /// <param name=' index'>The index to start from.</param> public void CopyTo(ManagementBaseObject[] objectCollection, int index) { CopyTo((Array)objectCollection, index); } // //IEnumerable methods // //**************************************** //GetEnumerator //**************************************** /// <summary> /// <para>Returns the enumerator for the collection. If the collection was retrieved from an operation that /// specified the EnumerationOptions.Rewindable = false only one iteration through this enumerator is allowed. /// Note that this applies to using the Count property of the collection as well since an iteration over the collection /// is required. Due to this, code using the Count property should never specify EnumerationOptions.Rewindable = false. /// </para> /// </summary> /// <returns> /// An <see cref='System.Collections.IEnumerator'/>that can be used to iterate through the /// collection. /// </returns> public ManagementObjectEnumerator GetEnumerator() { if (isDisposed) throw new ObjectDisposedException(name); // // We do not clone the enumerator if its the first enumerator. // If it is the first enumerator we pass the reference // to the enumerator implementation rather than a clone. If the enumerator is used // from within a foreach statement in the client code, the foreach statement will // dec the ref count on the reference which also happens to be the reference to the // original enumerator causing subsequent uses of the collection to fail. // To prevent this we always clone the enumerator (assuming its a rewindable enumerator) // to avoid invalidating the collection. // // If its a forward only enumerator we simply pass back the original enumerator (i.e. // not cloned) and if it gets disposed we end up throwing the next time its used. Essentially, // the enumerator becomes the collection. // // Unless this is the first enumerator, we have // to clone. This may throw if we are non-rewindable. if (this.options.Rewindable == true) { IEnumWbemClassObject enumWbemClone = null; int status = (int)ManagementStatus.NoError; try { status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Clone_(ref enumWbemClone); if ((status & 0x80000000) == 0) { //since the original enumerator might not be reset, we need //to reset the new one. status = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbemClone).Reset_(); } } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementObjectEnumerator(this, enumWbemClone); } else { // // Notice that we use the original enumerator and hence enum position is retained. // For example, if the client code manually walked half the collection and then // used a foreach statement, the foreach statement would continue from where the // manual walk ended. // return new ManagementObjectEnumerator(this, enumWbem); } } /// <internalonly/> /// <summary> /// <para>Returns an enumerator that can iterate through a collection.</para> /// </summary> /// <returns> /// An <see cref='System.Collections.IEnumerator'/> that can be used to iterate /// through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // // ManagementObjectCollection methods // //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC /// <summary> /// <para>Represents the enumerator on the collection.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// /// // This example demonstrates how to enumerate all logical disks /// // using the ManagementObjectEnumerator object. /// class Sample_ManagementObjectEnumerator /// { /// public static int Main(string[] args) { /// ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk"); /// ManagementObjectCollection disks = diskClass.GetInstances(); /// ManagementObjectCollection.ManagementObjectEnumerator disksEnumerator = /// disks.GetEnumerator(); /// while(disksEnumerator.MoveNext()) { /// ManagementObject disk = (ManagementObject)disksEnumerator.Current; /// Console.WriteLine("Disk found: " + disk["deviceid"]); /// } /// return 0; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// ' This sample demonstrates how to enumerate all logical disks /// ' using ManagementObjectEnumerator object. /// Class Sample_ManagementObjectEnumerator /// Overloads Public Shared Function Main(args() As String) As Integer /// Dim diskClass As New ManagementClass("Win32_LogicalDisk") /// Dim disks As ManagementObjectCollection = diskClass.GetInstances() /// Dim disksEnumerator As _ /// ManagementObjectCollection.ManagementObjectEnumerator = _ /// disks.GetEnumerator() /// While disksEnumerator.MoveNext() /// Dim disk As ManagementObject = _ /// CType(disksEnumerator.Current, ManagementObject) /// Console.WriteLine("Disk found: " &amp; disk("deviceid")) /// End While /// Return 0 /// End Function /// End Class /// </code> /// </example> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC public class ManagementObjectEnumerator : IEnumerator, IDisposable { private static readonly string name = typeof(ManagementObjectEnumerator).FullName; private IEnumWbemClassObject enumWbem; private ManagementObjectCollection collectionObject; private uint cachedCount; //says how many objects are in the enumeration cache (when using BlockSize option) private int cacheIndex; //used to walk the enumeration cache private IWbemClassObjectFreeThreaded[] cachedObjects; //points to objects currently available in enumeration cache private bool atEndOfCollection; private bool isDisposed = false; //constructor internal ManagementObjectEnumerator( ManagementObjectCollection collectionObject, IEnumWbemClassObject enumWbem) { this.enumWbem = enumWbem; this.collectionObject = collectionObject; cachedObjects = new IWbemClassObjectFreeThreaded[collectionObject.options.BlockSize]; cachedCount = 0; cacheIndex = -1; // Reset position atEndOfCollection = false; } /// <summary> /// <para>Disposes of resources the object is holding. This is the destructor for the object.</para> /// </summary> ~ManagementObjectEnumerator() { Dispose(); } /// <summary> /// Releases resources associated with this object. After this /// method has been called, an attempt to use this object will /// result in an ObjectDisposedException being thrown. /// </summary> public void Dispose() { if (!isDisposed) { if (null != enumWbem) { Marshal.ReleaseComObject(enumWbem); enumWbem = null; } cachedObjects = null; // DO NOT dispose of collectionObject. It is merely a reference - its lifetime // exceeds that of this object. If collectionObject.Dispose was to be done here, // a reference count would be needed. // collectionObject = null; isDisposed = true; GC.SuppressFinalize(this); } } /// <summary> /// <para>Gets the current <see cref='System.Management.ManagementBaseObject'/> that this enumerator points /// to.</para> /// </summary> /// <value> /// <para>The current object in the enumeration.</para> /// </value> public ManagementBaseObject Current { get { if (isDisposed) throw new ObjectDisposedException(name); if (cacheIndex < 0) throw new InvalidOperationException(); return ManagementBaseObject.GetBaseObject(cachedObjects[cacheIndex], collectionObject.scope); } } /// <internalonly/> /// <summary> /// <para>Returns the current object in the enumeration.</para> /// </summary> /// <value> /// <para>The current object in the enumeration.</para> /// </value> object IEnumerator.Current { get { return Current; } } //**************************************** //MoveNext //**************************************** /// <summary> /// Indicates whether the enumerator has moved to /// the next object in the enumeration. /// </summary> /// <returns> /// <para><see langword='true'/>, if the enumerator was /// successfully advanced to the next element; <see langword='false'/> if the enumerator has /// passed the end of the collection.</para> /// </returns> public bool MoveNext() { if (isDisposed) throw new ObjectDisposedException(name); //If there are no more objects in the collection return false if (atEndOfCollection) return false; //Look for the next object cacheIndex++; if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects { //If the timeout is set to infinite, need to use the WMI infinite constant int timeout = (collectionObject.options.Timeout.Ticks == long.MaxValue) ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE : (int)collectionObject.options.Timeout.TotalMilliseconds; //Get the next [BLockSize] objects within the specified timeout SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler(); //Because Interop doesn't support custom marshalling for arrays, we have to use //the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded" //counterparts afterwards. IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[collectionObject.options.BlockSize]; int status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)collectionObject.options.BlockSize, tempArray, ref cachedCount); securityHandler.Reset(); if (status >= 0) { //Convert results and put them in cache. for (int i = 0; i < cachedCount; i++) { cachedObjects[i] = new IWbemClassObjectFreeThreaded ( Marshal.GetIUnknownForObject(tempArray[i]) ); } } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } else { //If there was a timeout and no object can be returned we throw a timeout exception... if ((status == (int)tag_WBEMSTATUS.WBEM_S_TIMEDOUT) && (cachedCount == 0)) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); //If not timeout and no objects were returned - we're at the end of the collection if ((status == (int)tag_WBEMSTATUS.WBEM_S_FALSE) && (cachedCount == 0)) { atEndOfCollection = true; cacheIndex--; //back to last object /* This call to Dispose is being removed as per discussion with URT people and the newly supported * Dispose() call in the foreach implementation itself. * * //Release the COM object (so that the user doesn't have to) Dispose(); */ return false; } } cacheIndex = 0; } return true; } //**************************************** //Reset //**************************************** /// <summary> /// <para>Resets the enumerator to the beginning of the collection.</para> /// </summary> public void Reset() { if (isDisposed) throw new ObjectDisposedException(name); //If the collection is not rewindable you can't do this if (!collectionObject.options.Rewindable) throw new InvalidOperationException(); else { //Reset the WMI enumerator SecurityHandler securityHandler = collectionObject.scope.GetSecurityHandler(); int status = (int)ManagementStatus.NoError; try { status = collectionObject.scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Reset_(); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } finally { securityHandler.Reset(); } if ((status & 0xfffff000) == 0x80041000) { ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); } else if ((status & 0x80000000) != 0) { Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } //Flush the current enumeration cache for (int i = (cacheIndex >= 0 ? cacheIndex : 0); i < cachedCount; i++) Marshal.ReleaseComObject((IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(cachedObjects[i]))); cachedCount = 0; cacheIndex = -1; atEndOfCollection = false; } } } //ManagementObjectEnumerator class } //ManagementObjectCollection class }
// 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.IO; using System.Linq; using System.Globalization; using System.Collections.Generic; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Xml; using System.Security.Cryptography.X509Certificates; using Xunit; using Test.Cryptography; using System.Security.Cryptography.Pkcs.Tests; namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests { public static partial class StateTests { // // Exercises various edge cases when EnvelopedCms methods and properties are called out of the "expected" order. // // The "expected" sequences are one of: // // ctor(ContentInfo)|ctor(ContentInfo,AlgorithmIdentifier) => Encrypt() => Encode() // // or // // ctor() => Decode() => RecipientInfos => Decrypt() => ContentInfo // // Most of these semantics are driven by backward compatibility. A tighter api design wouldn't // have exposed all these state transitions in the first place. // // The four states an EnvelopedCms can be in are as follows: // // State 1: Post constructor // // There are three constructor overloads, but all but one just supply default arguments // so we can consider there to be just one constructor. // // At this stage, there is no CMS underneath, just some properties (ContentInfo, AlgorithmIdentifier, etc.) // that serve as implicit inputs to a future Encrypt() call. // // State 2: Post Encrypt() // // Encrypt() can be called at any time and it effectively resets the state of the EnvelopedCms // (although the prior contents of ContentInfo, ContentEncryptionAlgorithm, UnprotectedAttributes and Certificates // will naturally influence the contents of CMS is constructed.) // // Encrypt() actually both encrypts and encodes, but you have to call Encode() afterward to pick up the encoded bytes. // // State 3: Post Decode() // // Decode() can also be called at any time - it's effectively a constructor that resets the internal // state and all the member properties. // // In this state, you can invoke the RecipientInfos properties to decide which recipient to pass to Decrypt(). // // State 4: Post Decrypt() // // A Decrypt() can only happen after a Decode(). // // Once in this state, you can fetch ContentInfo to get the decrypted content // but otherwise, the CMS is in a pretty useless state. // // // State 1 // // Constructed using any of the constructor overloads. // [Fact] public static void PostCtor_Version() { // Version returns 0 by fiat. EnvelopedCms ecms = new EnvelopedCms(); Assert.Equal(0, ecms.Version); } [Fact] public static void PostCtor_RecipientInfos() { // RecipientInfo returns empty collection by fiat. EnvelopedCms ecms = new EnvelopedCms(); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(0, recipients.Count); } [Fact] public static void PostCtor_Encode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<InvalidOperationException>(() => ecms.Encode()); } [Fact] public static void PostCtor_Decrypt() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<InvalidOperationException>(() => ecms.Decrypt()); } [Fact] public static void PostCtor_ContentInfo() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); ContentInfo actualContentInfo = ecms.ContentInfo; Assert.Equal(expectedContentInfo.ContentType, actualContentInfo.ContentType); Assert.Equal<byte>(expectedContentInfo.Content, actualContentInfo.Content); } // // State 2 // // Called constructor + Encrypt() // [Fact] public static void PostEncrypt_Version() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); int versionBeforeEncrypt = ecms.Version; using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } // Encrypt does not update Version member. Assert.Equal(versionBeforeEncrypt, ecms.Version); } [Fact] public static void PostEncrypt_RecipientInfos() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } object ignore; Assert.ThrowsAny<CryptographicException>(() => ignore = ecms.RecipientInfos); } [Fact] public static void PostEncrypt_Decrypt() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt()); } [Fact] public static void PostEncrypt_ContentInfo() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } // Encrypting does not update ContentInfo. ContentInfo actualContentInfo = ecms.ContentInfo; Assert.Equal(expectedContentInfo.ContentType, actualContentInfo.ContentType); Assert.Equal<byte>(expectedContentInfo.Content, actualContentInfo.Content); } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void PostEncrypt_Certs() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); ecms.Certificates.Add(Certificates.RSAKeyTransfer2.GetCertificate()); ecms.Certificates.Add(Certificates.RSAKeyTransfer3.GetCertificate()); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } Assert.Equal(Certificates.RSAKeyTransfer2.GetCertificate(), ecms.Certificates[0]); Assert.Equal(Certificates.RSAKeyTransfer3.GetCertificate(), ecms.Certificates[1]); } // // State 3: Called Decode() // private static void PostDecode_Encode(bool isRunningOnDesktop) { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // This should really have thrown an InvalidOperationException. Instead, you get... something back. string expectedString = isRunningOnDesktop ? "35edc437e31d0b70000000000000" : "35edc437e31d0b70"; byte[] expectedGarbage = expectedString.HexToByteArray(); byte[] garbage = ecms.Encode(); Assert.Equal(expectedGarbage, garbage); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void PostDecode_Encode_net46() { PostDecode_Encode(isRunningOnDesktop: true); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void PostDecode_Encode_netcore() { PostDecode_Encode(isRunningOnDesktop: false); } private static void PostDecode_ContentInfo(bool isRunningOnDesktop) { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // This gets you the encrypted inner content. ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal(Oids.Pkcs7Data, contentInfo.ContentType.Value); string expectedString = isRunningOnDesktop ? "35edc437e31d0b70000000000000" : "35edc437e31d0b70"; byte[] expectedGarbage = expectedString.HexToByteArray(); Assert.Equal(expectedGarbage, contentInfo.Content); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void PostDecode_ContentInfo_net46() { PostDecode_ContentInfo(isRunningOnDesktop: true); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void PostDecode_ContentInfo_netcore() { PostDecode_ContentInfo(isRunningOnDesktop: false); } // // State 4: Called Decode() + Decrypt() // [Theory] [OuterLoop(/* Leaks key on disk if interrupted */)] [InlineData(false)] #if NETCOREAPP // API not supported on netfx [InlineData(true)] #endif public static void PostDecrypt_Encode(bool useExplicitPrivateKey) { byte[] expectedContent = { 6, 3, 128, 33, 44 }; EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent)); ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate())); byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067" + "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380" + "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac" + "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d" + "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray(); ecms.Decode(encodedMessage); using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cer == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. RecipientInfoCollection r = ecms.RecipientInfos; if (useExplicitPrivateKey) { #if NETCOREAPP ecms.Decrypt(r[0], cer.GetRSAPrivateKey()); #else Assert.True(false, "Should not run on this platform"); #endif } else { X509Certificate2Collection extraStore = new X509Certificate2Collection(cer); ecms.Decrypt(r[0], extraStore); } // Desktop compat: Calling Encode() at this point should have thrown an InvalidOperationException. Instead, it returns // the decrypted inner content (same as ecms.ContentInfo.Content). This is easy for someone to take a reliance on // so for compat sake, we'd better keep it. byte[] encoded = ecms.Encode(); Assert.Equal<byte>(expectedContent, encoded); } } [Fact] [OuterLoop(/* Leaks key on disk if interrupted */)] public static void PostDecrypt_RecipientInfos() { byte[] expectedContent = { 6, 3, 128, 33, 44 }; EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent)); ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate())); byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067" + "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380" + "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac" + "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d" + "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray(); ecms.Decode(encodedMessage); using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cer == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(cer); RecipientInfoCollection col1 = ecms.RecipientInfos; ecms.Decrypt(col1[0], extraStore); // Make sure we can still RecipientInfos after a Decrypt() RecipientInfoCollection col2 = ecms.RecipientInfos; Assert.Equal(col1.Count, col2.Count); RecipientInfo r1 = col1[0]; RecipientInfo r2 = col2[0]; X509IssuerSerial is1 = (X509IssuerSerial)(r1.RecipientIdentifier.Value); X509IssuerSerial is2 = (X509IssuerSerial)(r2.RecipientIdentifier.Value); Assert.Equal(is1.IssuerName, is2.IssuerName); Assert.Equal(is1.SerialNumber, is2.SerialNumber); } } [Theory] [OuterLoop(/* Leaks key on disk if interrupted */)] [InlineData(false)] #if NETCOREAPP // API not supported on netfx [InlineData(true)] #endif public static void PostDecrypt_Decrypt(bool useExplicitPrivateKey) { byte[] expectedContent = { 6, 3, 128, 33, 44 }; byte[] encodedMessage = ("308202b006092a864886f70d010703a08202a13082029d020100318202583081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004" + "81801026d9fb60d1a55686b73cf859c8bd66b58defda5e23e3da5f535f1427e3c5f7a4a2a94373e8e3ba5488a7c6a1059bfb" + "57301156698e7fca62671426d388fb3fb4373c9cb53132fda067598256bbfe8491b14dadaaf04d5fdfb2463f358ad0d6a594" + "bf6a4fbab6b3d725f08032e601492265e6336d5a638096f9975025ccd6393081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e736665723202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d010101050004" + "8180b6497a2b789728f200ca1f974a676c531a4769f03f3929bd7526e7333ea483b4abb530a49c8532db5d4a4df66f173e3e" + "a4ba9e4814b584dc987ac87c46bb131daab535140968aafad8808100a2515e9c6d0c1f382b024992ce36b70b841628e0eb43" + "4db89545d702a8fbd3403188e7de7cb4bc1dcc3bc325467570654aaf2ee83081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e736665723302104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d010101050004" + "81807517e594c353d41abff334c6162988b78e05df7d79457c146fbc886d2d8057f594fa3a96cd8df5842c9758baac1fcdd5" + "d9672a9f8ef9426326cccaaf5954f2ae657f8c7b13aef2f811adb4954323aa8319a1e8f2ad4e5c96c1d3fbe413ae479e471b" + "b701cbdfa145c9b64f5e1f69f472804995d56c31351553f779cf8efec237303c06092a864886f70d010701301d0609608648" + "01650304012a041023a114c149d7d4017ce2f5ec7c5d53f980104e50ab3c15533743dd054ef3ff8b9d83").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert1 = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.TryGetCertificateWithPrivateKey()) using (X509Certificate2 cert3 = Certificates.RSAKeyTransfer3.TryGetCertificateWithPrivateKey()) { if (cert1 == null || cert2 == null || cert3 == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert1); extraStore.Add(cert2); extraStore.Add(cert3); RecipientInfoCollection r = ecms.RecipientInfos; Action decrypt = () => { if (useExplicitPrivateKey) { #if NETCOREAPP ecms.Decrypt(r[0], cert1.GetRSAPrivateKey()); #else Assert.True(false, "Should not run on this platform"); #endif } else { ecms.Decrypt(r[0], extraStore); } }; decrypt(); ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(expectedContent, contentInfo.Content); // Though this doesn't seem like a terribly unreasonable thing to attempt, attempting to call Decrypt() again // after a successful Decrypt() throws a CryptographicException saying "Already decrypted." Assert.ThrowsAny<CryptographicException>(() => decrypt()); } } [Fact] public static void PostEncode_DifferentData() { // This ensures that the decoding and encoding output different values to make sure Encrypt changes the state of the data. byte[] encoded = ("3082010206092A864886F70D010703A081F43081F10201003181C83081C5020100302E301A311830160603550403130F" + "5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A864886F70D0101010500" + "04818009C16B674495C2C3D4763189C3274CF7A9142FBEEC8902ABDC9CE29910D541DF910E029A31443DC9A9F3B05F02" + "DA1C38478C400261C734D6789C4197C20143C4312CEAA99ECB1849718326D4FC3B7FBB2D1D23281E31584A63E99F2C17" + "132BCD8EDDB632967125CD0A4BAA1EFA8CE4C855F7C093339211BDF990CEF5CCE6CD74302106092A864886F70D010701" + "301406082A864886F70D03070408779B3DE045826B18").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encoded); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } byte[] encrypted = ecms.Encode(); Assert.NotEqual<byte>(encoded, encrypted); } private static void AssertEncryptedContentEqual(byte[] expected, byte[] actual) { if (expected.SequenceEqual(actual)) return; if (actual.Length > expected.Length && actual.Take(expected.Length).SequenceEqual(expected)) throw new Exception("Returned content had extra bytes padded. If you're running this test on the desktop framework, this is a known bug."); Assert.Equal<byte>(expected, actual); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Linq.Tests { public class ToDictionaryTests : EnumerableTests { private class CustomComparer<T> : IEqualityComparer<T> { public bool Equals(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); } public int GetHashCode(T obj) { return EqualityComparer<T>.Default.GetHashCode(obj); } } [Fact] public void ToDictionary_AlwaysCreateACopy() { Dictionary<int, int> source = new Dictionary<int, int>() { { 1, 1 }, { 2, 2 }, { 3, 3 } }; Dictionary<int, int> result = source.ToDictionary(key => key.Key, val => val.Value); Assert.NotSame(source, result); Assert.Equal(source, result); } private void RunToDictionaryOnAllCollectionTypes<T>(T[] items, Action<Dictionary<T, T>> validation) { validation(Enumerable.ToDictionary(items, key => key)); validation(Enumerable.ToDictionary(items, key => key, value => value)); validation(Enumerable.ToDictionary(new List<T>(items), key => key)); validation(Enumerable.ToDictionary(new List<T>(items), key => key, value => value)); validation(new TestEnumerable<T>(items).ToDictionary(key => key)); validation(new TestEnumerable<T>(items).ToDictionary(key => key, value => value)); validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key)); validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key, value => value)); validation(new TestCollection<T>(items).ToDictionary(key => key)); validation(new TestCollection<T>(items).ToDictionary(key => key, value => value)); } [Fact] public void ToDictionary_WorkWithEmptyCollection() { RunToDictionaryOnAllCollectionTypes(new int[0], resultDictionary => { Assert.NotNull(resultDictionary); Assert.Equal(0, resultDictionary.Count); }); } [Fact] public void ToDictionary_ProduceCorrectDictionary() { int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 }; RunToDictionaryOnAllCollectionTypes(sourceArray, resultDictionary => { Assert.Equal(sourceArray.Length, resultDictionary.Count); Assert.Equal(sourceArray, resultDictionary.Keys); Assert.Equal(sourceArray, resultDictionary.Values); }); string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" }; RunToDictionaryOnAllCollectionTypes(sourceStringArray, resultDictionary => { Assert.Equal(sourceStringArray.Length, resultDictionary.Count); for (int i = 0; i < sourceStringArray.Length; i++) Assert.Same(sourceStringArray[i], resultDictionary[sourceStringArray[i]]); }); } [Fact] public void ToDictionary_PassCustomComparer() { CustomComparer<int> comparer = new CustomComparer<int>(); TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer); Assert.Same(comparer, result1.Comparer); Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer); Assert.Same(comparer, result2.Comparer); } [Fact] public void ToDictionary_UseDefaultComparerOnNull() { CustomComparer<int> comparer = null; TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer); Assert.Same(EqualityComparer<int>.Default, result1.Comparer); Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer); Assert.Same(EqualityComparer<int>.Default, result2.Comparer); } [Fact] public void ToDictionary_KeyValueSelectorsWork() { TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 }); Dictionary<int, int> result = collection.ToDictionary(key => key + 10, val => val + 100); Assert.Equal(collection.Items.Select(o => o + 10), result.Keys); Assert.Equal(collection.Items.Select(o => o + 100), result.Values); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNull() { int[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNull() { int[] source = new int[0]; Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenValueSelectorIsNull() { int[] source = new int[0]; Func<int, int> keySelector = key => key; Func<int, int> valueSelector = null; Assert.Throws<ArgumentNullException>("elementSelector", () => source.ToDictionary(keySelector, valueSelector)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNullElementSelector() { int[] source = null; Assert.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key, e => e)); } [Fact] public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNullElementSelector() { int[] source = new int[0]; Func<int, int> keySelector = null; Assert.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector, e => e)); } [Fact] public void ToDictionary_KeySelectorThrowException() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => { if (key == 1) throw new InvalidOperationException(); return key; }; Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowWhenKeySelectorReturnNull() { int[] source = new int[] { 1, 2, 3 }; Func<int, string> keySelector = key => null; Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ThrowWhenKeySelectorReturnSameValueTwice() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => 1; Assert.Throws<ArgumentException>(() => source.ToDictionary(keySelector)); } [Fact] public void ToDictionary_ValueSelectorThrowException() { int[] source = new int[] { 1, 2, 3 }; Func<int, int> keySelector = key => key; Func<int, int> valueSelector = value => { if (value == 1) throw new InvalidOperationException(); return value; }; Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector, valueSelector)); } [Fact] public void ThrowsOnNullKey() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name)); } [Fact] public void ThrowsOnNullKeyCustomComparer() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, new AnagramEqualityComparer()); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void ThrowsOnNullKeyValueSelector() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, e => e); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e)); } [Fact] public void ThrowsOnNullKeyCustomComparerValueSelector() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "null", Score = 55 } }; source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer()); // Doesn't throw; source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = default(string), Score = 55 } }; Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer())); } [Fact] public void ThrowsOnDuplicateKeys() { var source = new[] { new { Name = "Chris", Score = 50 }, new { Name = "Bob", Score = 95 }, new { Name = "Bob", Score = 55 } }; Assert.Throws<ArgumentException>(() => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer())); } private static void AssertMatches<K, E>(IEnumerable<K> keys, IEnumerable<E> values, Dictionary<K, E> dict) { Assert.NotNull(dict); Assert.NotNull(keys); Assert.NotNull(values); using (var ke = keys.GetEnumerator()) { foreach(var value in values) { Assert.True(ke.MoveNext()); var key = ke.Current; E dictValue; Assert.True(dict.TryGetValue(key, out dictValue)); Assert.Equal(value, dictValue); dict.Remove(key); } Assert.False(ke.MoveNext()); Assert.Equal(0, dict.Count()); } } [Fact] public void EmtpySource() { int[] elements = new int[] { }; string[] keys = new string[] { }; var source = keys.Zip(elements, (k, e) => new { Name = k, Score = e }); AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void OneElementNullComparer() { int[] elements = new int[] { 5 }; string[] keys = new string[] { "Bob" }; var source = new [] { new { Name = keys[0], Score = elements[0] } }; AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, null)); } [Fact] public void SeveralElementsCustomComparerer() { string[] keys = new string[] { "Bob", "Zen", "Prakash", "Chris", "Sachin" }; var source = new [] { new { Name = "Bbo", Score = 95 }, new { Name = keys[1], Score = 45 }, new { Name = keys[2], Score = 100 }, new { Name = keys[3], Score = 90 }, new { Name = keys[4], Score = 45 } }; AssertMatches(keys, source, source.ToDictionary(e => e.Name, new AnagramEqualityComparer())); } [Fact] public void NullCoalescedKeySelector() { string[] elements = new string[] { null }; string[] keys = new string[] { string.Empty }; string[] source = new string[] { null }; AssertMatches(keys, elements, source.ToDictionary(e => e ?? string.Empty, e => e, EqualityComparer<string>.Default)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using NuGet; using NuGet.VisualStudio; using NuGet.VisualStudio.Resources; namespace NuGetConsole.Host.PowerShell.Implementation { internal abstract class PowerShellHost : IHost, IPathExpansion, IDisposable { private static readonly object _lockObject = new object(); private static readonly object _initScriptsLock = new object(); private readonly string _name; private readonly IRunspaceManager _runspaceManager; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly ISolutionManager _solutionManager; private string _targetDir; private bool _updateWorkingDirectoryPending; private IConsole _activeConsole; private Runspace _runspace; private NuGetPSHost _nugetHost; // indicates whether this host has been initialized. // null = not initilized, true = initialized successfully, false = initialized unsuccessfully private bool? _initialized; // store the current (non-truncated) project names displayed in the project name combobox private string[] _projectSafeNames; // store the current command typed so far private ComplexCommand _complexCommand; protected PowerShellHost(string name, IRunspaceManager runspaceManager) { _runspaceManager = runspaceManager; // TODO: Take these as ctor arguments _packageSourceProvider = ServiceLocator.GetInstance<IVsPackageSourceProvider>(); _solutionManager = ServiceLocator.GetInstance<ISolutionManager>(); _name = name; IsCommandEnabled = true; } protected Pipeline ExecutingPipeline { get; set; } /// <summary> /// The host is associated with a particular console on a per-command basis. /// This gets set every time a command is executed on this host. /// </summary> protected IConsole ActiveConsole { get { return _activeConsole; } set { _activeConsole = value; if (_nugetHost != null) { _nugetHost.ActiveConsole = value; } } } public bool IsCommandEnabled { get; private set; } protected Runspace Runspace { get { return _runspace; } } private ComplexCommand ComplexCommand { get { if (_complexCommand == null) { _complexCommand = new ComplexCommand((allLines, lastLine) => { Collection<PSParseError> errors; PSParser.Tokenize(allLines, out errors); // If there is a parse error token whose END is past input END, consider // it a multi-line command. if (errors.Count > 0) { if (errors.Any(e => (e.Token.Start + e.Token.Length) >= allLines.Length)) { return false; } } return true; }); } return _complexCommand; } } public string Prompt { get { return ComplexCommand.IsComplete ? EvaluatePrompt() : ">> "; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private string EvaluatePrompt() { string prompt = "PM>"; try { PSObject output = this.Runspace.Invoke("prompt", null, outputResults: false).FirstOrDefault(); if (output != null) { string result = output.BaseObject.ToString(); if (!String.IsNullOrEmpty(result)) { prompt = result; } } } catch (Exception ex) { ExceptionHelper.WriteToActivityLog(ex); } return prompt; } /// <summary> /// Doing all necessary initialization works before the console accepts user inputs /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Initialize(IConsole console) { ActiveConsole = console; if (_initialized.HasValue) { if (_initialized.Value && console.ShowDisclaimerHeader) { DisplayDisclaimerAndHelpText(); } } else { try { Tuple<Runspace, NuGetPSHost> tuple = _runspaceManager.GetRunspace(console, _name); _runspace = tuple.Item1; _nugetHost = tuple.Item2; _initialized = true; if (console.ShowDisclaimerHeader) { DisplayDisclaimerAndHelpText(); } UpdateWorkingDirectory(); ExecuteInitScripts(); // Hook up solution events _solutionManager.SolutionOpened += (o, e) => { UpdateWorkingDirectory(); ExecuteInitScripts(); }; _solutionManager.SolutionClosed += (o, e) => UpdateWorkingDirectory(); } catch (Exception ex) { // catch all exception as we don't want it to crash VS _initialized = false; IsCommandEnabled = false; ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } private void UpdateWorkingDirectory() { string targetDir; if (_solutionManager.IsSolutionOpen) { targetDir = _solutionManager.SolutionDirectory; } else { // if there is no solution open, we set the active directory to be user profile folder targetDir = Environment.GetEnvironmentVariable("USERPROFILE"); } if (Runspace.RunspaceAvailability == RunspaceAvailability.Available) { Runspace.ChangePSDirectory(targetDir); } else { // If we are in the middle of executing some other scripts, which triggered the solution to be opened/closed, then we // can't execute Set-Location here because of reentrancy policy. So we save the location and change it later when the // executing command finishes running. _targetDir = targetDir; _updateWorkingDirectoryPending = true; } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want execution of init scripts to crash our console.")] private void ExecuteInitScripts() { // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads. lock (_initScriptsLock) { if (String.IsNullOrEmpty(_solutionManager.SolutionDirectory)) { return; } try { var localRepository = new LocalPackageRepository(_solutionManager.SolutionDirectory); // invoke init.ps1 files in the order of package dependency. // if A -> B, we invoke B's init.ps1 before A's. var sorter = new PackageSorter(); var sortedPackages = sorter.GetPackagesByDependencyOrder(localRepository); foreach (var package in sortedPackages) { string installPath = localRepository.PathResolver.GetInstallPath(package); AddPathToEnvironment(Path.Combine(installPath, "tools")); Runspace.ExecuteScript(installPath, "tools\\init.ps1", package); } } catch (Exception ex) { // if execution of Init scripts fails, do not let it crash our console ReportError(ex); ExceptionHelper.WriteToActivityLog(ex); } } } private static void AddPathToEnvironment(string path) { if (Directory.Exists(path)) { string environmentPath = Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Process); environmentPath = environmentPath + ";" + path; Environment.SetEnvironmentVariable("path", environmentPath, EnvironmentVariableTarget.Process); } } protected abstract bool ExecuteHost(string fullCommand, string command, params object[] inputs); public bool Execute(IConsole console, string command, params object[] inputs) { if (console == null) { throw new ArgumentNullException("console"); } if (command == null) { throw new ArgumentNullException("command"); } _updateWorkingDirectoryPending = false; ActiveConsole = console; string fullCommand; if (ComplexCommand.AddLine(command, out fullCommand) && !string.IsNullOrEmpty(fullCommand)) { return ExecuteHost(fullCommand, command, inputs); } return false; // constructing multi-line command } protected void OnExecuteCommandEnd() { if (_updateWorkingDirectoryPending == true) { Runspace.ChangePSDirectory(_targetDir); _updateWorkingDirectoryPending = false; _targetDir = null; } } public void Abort() { if (ExecutingPipeline != null) { ExecutingPipeline.StopAsync(); } ComplexCommand.Clear(); } protected void SetSyncModeOnHost(bool isSync) { if (_nugetHost != null) { PSPropertyInfo property = _nugetHost.PrivateData.Properties["IsSyncMode"]; if (property == null) { property = new PSNoteProperty("IsSyncMode", isSync); _nugetHost.PrivateData.Properties.Add(property); } else { property.Value = isSync; } } } public void SetDefaultRunspace() { if (Runspace.DefaultRunspace == null) { lock (_lockObject) { if (Runspace.DefaultRunspace == null) { // Set this runspace as DefaultRunspace so I can script DTE events. // // WARNING: MSDN says this is unsafe. The runspace must not be shared across // threads. I need this to be able to use ScriptBlock for DTE events. The // ScriptBlock event handlers execute on DefaultRunspace. Runspace.DefaultRunspace = Runspace; } } } } private void DisplayDisclaimerAndHelpText() { WriteLine(VsResources.Console_DisclaimerText); WriteLine(); WriteLine(String.Format(CultureInfo.CurrentCulture, Resources.PowerShellHostTitle, _nugetHost.Version.ToString())); WriteLine(); WriteLine(VsResources.Console_HelpText); WriteLine(); } protected void ReportError(ErrorRecord record) { WriteErrorLine(Runspace.ExtractErrorFromErrorRecord(record)); } protected void ReportError(Exception exception) { exception = ExceptionUtility.Unwrap(exception); WriteErrorLine(exception.Message); } private void WriteErrorLine(string message) { if (ActiveConsole != null) { ActiveConsole.Write(message + Environment.NewLine, System.Windows.Media.Colors.Red, null); } } private void WriteLine(string message = "") { if (ActiveConsole != null) { ActiveConsole.WriteLine(message); } } public string ActivePackageSource { get { var activePackageSource = _packageSourceProvider.ActivePackageSource; return activePackageSource == null ? null : activePackageSource.Name; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } _packageSourceProvider.ActivePackageSource = _packageSourceProvider.GetEnabledPackageSourcesWithAggregate().FirstOrDefault( ps => ps.Name.Equals(value, StringComparison.OrdinalIgnoreCase)); } } public string[] GetPackageSources() { return _packageSourceProvider.GetEnabledPackageSourcesWithAggregate().Select(ps => ps.Name).ToArray(); } public string DefaultProject { get { Debug.Assert(_solutionManager != null); if (_solutionManager.DefaultProject == null) { return null; } return _solutionManager.DefaultProject.GetDisplayName(_solutionManager); } } public void SetDefaultProjectIndex(int selectedIndex) { Debug.Assert(_solutionManager != null); if (_projectSafeNames != null && selectedIndex >= 0 && selectedIndex < _projectSafeNames.Length) { _solutionManager.DefaultProjectName = _projectSafeNames[selectedIndex]; } else { _solutionManager.DefaultProjectName = null; } } public string[] GetAvailableProjects() { Debug.Assert(_solutionManager != null); var allProjects = _solutionManager.GetProjects(); _projectSafeNames = allProjects.Select(_solutionManager.GetProjectSafeName).ToArray(); var displayNames = allProjects.Select(p => p.GetDisplayName(_solutionManager)).ToArray(); Array.Sort(displayNames, _projectSafeNames, StringComparer.CurrentCultureIgnoreCase); return displayNames; } #region ITabExpansion public string[] GetExpansions(string line, string lastWord) { var query = from s in Runspace.Invoke( "$__pc_args=@(); $input|%{$__pc_args+=$_}; TabExpansion $__pc_args[0] $__pc_args[1]; Remove-Variable __pc_args -Scope 0", new string[] { line, lastWord }, outputResults: false) select (s == null ? null : s.ToString()); return query.ToArray(); } #endregion #region IPathExpansion public SimpleExpansion GetPathExpansions(string line) { PSObject expansion = Runspace.Invoke( "$input|%{$__pc_args=$_}; _TabExpansionPath $__pc_args; Remove-Variable __pc_args -Scope 0", new object[] { line }, outputResults: false).FirstOrDefault(); if (expansion != null) { int replaceStart = (int)expansion.Properties["ReplaceStart"].Value; IList<string> paths = ((IEnumerable<object>)expansion.Properties["Paths"].Value).Select(o => o.ToString()).ToList(); return new SimpleExpansion(replaceStart, line.Length - replaceStart, paths); } return null; } #endregion #region IDisposable public void Dispose() { if (_runspace != null) { _runspace.Dispose(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Debug = System.Diagnostics.Debug; namespace Internal.TypeSystem { public static partial class CastingHelper { /// <summary> /// Returns true if '<paramref name="thisType"/>' can be cast to '<paramref name="otherType"/>'. /// Assumes '<paramref name="thisType"/>' is in it's boxed form if it's a value type (i.e. /// [System.Int32].CanCastTo([System.Object]) will return true). /// </summary> public static bool CanCastTo(this TypeDesc thisType, TypeDesc otherType) { return thisType.CanCastToInternal(otherType, null); } private static bool CanCastToInternal(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { if (thisType == otherType) { return true; } switch (thisType.Category) { case TypeFlags.GenericParameter: return ((GenericParameterDesc)thisType).CanCastGenericParameterTo(otherType, protect); case TypeFlags.Array: case TypeFlags.SzArray: return ((ArrayType)thisType).CanCastArrayTo(otherType, protect); default: Debug.Assert(thisType.IsDefType); return thisType.CanCastToClassOrInterface(otherType, protect); } } private static bool CanCastGenericParameterTo(this GenericParameterDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { // A boxed variable type can be cast to any of its constraints, or object, if none are specified if (otherType.IsObject) { return true; } if (thisType.HasNotNullableValueTypeConstraint && otherType.IsWellKnownType(WellKnownType.ValueType)) { return true; } foreach (var typeConstraint in thisType.TypeConstraints) { if (typeConstraint.CanCastToInternal(otherType, protect)) { return true; } } return false; } private static bool CanCastArrayTo(this ArrayType thisType, TypeDesc otherType, StackOverflowProtect protect) { // Casting the array to one of the base types or interfaces? if (otherType.IsDefType) { return thisType.CanCastToClassOrInterface(otherType, protect); } // Casting array to something else (between SzArray and Array, for example)? if (thisType.Category != otherType.Category) { return false; } ArrayType otherArrayType = (ArrayType)otherType; // Check ranks if we're casting multidim arrays if (!thisType.IsSzArray && thisType.Rank != otherArrayType.Rank) { return false; } return thisType.CanCastParamTo(otherArrayType.ParameterType, protect); } private static bool CanCastParamTo(this ParameterizedType thisType, TypeDesc paramType, StackOverflowProtect protect) { // While boxed value classes inherit from object their // unboxed versions do not. Parameterized types have the // unboxed version, thus, if the from type parameter is value // class then only an exact match/equivalence works. if (thisType.ParameterType == paramType) { return true; } TypeDesc curTypesParm = thisType.ParameterType; // Object parameters don't need an exact match but only inheritance, check for that TypeDesc fromParamUnderlyingType = curTypesParm.UnderlyingType; if (fromParamUnderlyingType.IsGCPointer) { return curTypesParm.CanCastToInternal(paramType, protect); } else if (curTypesParm.IsGenericParameter) { var genericVariableFromParam = (GenericParameterDesc)curTypesParm; if (genericVariableFromParam.HasReferenceTypeConstraint) { return genericVariableFromParam.CanCastToInternal(paramType, protect); } } else if (fromParamUnderlyingType.IsPrimitive) { TypeDesc toParamUnderlyingType = paramType.UnderlyingType; if (toParamUnderlyingType.IsPrimitive) { if (toParamUnderlyingType == fromParamUnderlyingType) { return true; } if (ArePrimitveTypesEquivalentSize(fromParamUnderlyingType, toParamUnderlyingType)) { return true; } } } // Anything else is not a match return false; } // Returns true of the two types are equivalent primitive types. Used by array casts. private static bool ArePrimitveTypesEquivalentSize(TypeDesc type1, TypeDesc type2) { Debug.Assert(type1.IsPrimitive && type2.IsPrimitive); // Primitive types such as E_T_I4 and E_T_U4 are interchangeable // Enums with interchangeable underlying types are interchangable // BOOL is NOT interchangeable with I1/U1, neither CHAR -- with I2/U2 // Float and double are not interchangable here. int sourcePrimitiveTypeEquivalenceSize = type1.GetIntegralTypeMatchSize(); // Quick check to see if the first type can be matched. if (sourcePrimitiveTypeEquivalenceSize == 0) { return false; } int targetPrimitiveTypeEquivalenceSize = type2.GetIntegralTypeMatchSize(); return sourcePrimitiveTypeEquivalenceSize == targetPrimitiveTypeEquivalenceSize; } private static int GetIntegralTypeMatchSize(this TypeDesc type) { Debug.Assert(type.IsPrimitive); switch (type.Category) { case TypeFlags.SByte: case TypeFlags.Byte: return 1; case TypeFlags.UInt16: case TypeFlags.Int16: return 2; case TypeFlags.Int32: case TypeFlags.UInt32: return 4; case TypeFlags.Int64: case TypeFlags.UInt64: return 8; case TypeFlags.IntPtr: case TypeFlags.UIntPtr: return type.Context.Target.PointerSize; default: return 0; } } public static bool IsArrayElementTypeCastableBySize(TypeDesc elementType) { TypeDesc underlyingType = elementType.UnderlyingType; return underlyingType.IsPrimitive && GetIntegralTypeMatchSize(underlyingType) != 0; } private static bool CanCastToClassOrInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { if (otherType.IsInterface) { return thisType.CanCastToInterface(otherType, protect); } else { return thisType.CanCastToClass(otherType, protect); } } private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { if (!otherType.HasVariance) { return thisType.CanCastToNonVariantInterface(otherType,protect); } else { if (thisType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect)) { return true; } foreach (var interfaceType in thisType.RuntimeInterfaces) { if (interfaceType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect)) { return true; } } } return false; } private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { if (otherType == thisType) { return true; } foreach (var interfaceType in thisType.RuntimeInterfaces) { if (interfaceType == otherType) { return true; } } return false; } private static bool CanCastByVarianceToInterfaceOrDelegate(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protectInput) { if (!thisType.HasSameTypeDefinition(otherType)) { return false; } var stackOverflowProtectKey = new CastingPair(thisType, otherType); if (protectInput != null) { if (protectInput.Contains(stackOverflowProtectKey)) return false; } StackOverflowProtect protect = new StackOverflowProtect(stackOverflowProtectKey, protectInput); Instantiation instantiationThis = thisType.Instantiation; Instantiation instantiationTarget = otherType.Instantiation; Instantiation instantiationOpen = thisType.GetTypeDefinition().Instantiation; Debug.Assert(instantiationThis.Length == instantiationTarget.Length && instantiationThis.Length == instantiationOpen.Length); for (int i = 0; i < instantiationThis.Length; i++) { TypeDesc arg = instantiationThis[i]; TypeDesc targetArg = instantiationTarget[i]; if (arg != targetArg) { GenericParameterDesc openArgType = (GenericParameterDesc)instantiationOpen[i]; switch (openArgType.Variance) { case GenericVariance.Covariant: if (!arg.IsBoxedAndCanCastTo(targetArg, protect)) return false; break; case GenericVariance.Contravariant: if (!targetArg.IsBoxedAndCanCastTo(arg, protect)) return false; break; default: // non-variant Debug.Assert(openArgType.Variance == GenericVariance.None); return false; } } } return true; } private static bool CanCastToClass(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { TypeDesc curType = thisType; // If the target type has variant type parameters, we take a slower path if (curType.HasVariance) { // First chase inheritance hierarchy until we hit a class that only differs in its instantiation do { if (curType == otherType) { return true; } if (curType.CanCastByVarianceToInterfaceOrDelegate(otherType, protect)) { return true; } curType = curType.BaseType; } while (curType != null); } else { // If there are no variant type parameters, just chase the hierarchy // Allow curType to be nullable, which means this method // will additionally return true if curType is Nullable<T> && ( // currType == otherType // OR otherType is System.ValueType or System.Object) // Always strip Nullable from the otherType, if present if (otherType.IsNullable && !curType.IsNullable) { return thisType.CanCastTo(otherType.Instantiation[0]); } do { if (curType == otherType) return true; curType = curType.BaseType; } while (curType != null); } return false; } private static bool IsBoxedAndCanCastTo(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) { TypeDesc fromUnderlyingType = thisType.UnderlyingType; if (fromUnderlyingType.IsGCPointer) { return thisType.CanCastToInternal(otherType, protect); } else if (thisType.IsGenericParameter) { var genericVariableFromParam = (GenericParameterDesc)thisType; if (genericVariableFromParam.HasReferenceTypeConstraint) { return genericVariableFromParam.CanCastToInternal(otherType, protect); } } return false; } private class StackOverflowProtect { private CastingPair _value; private StackOverflowProtect _previous; public StackOverflowProtect(CastingPair value, StackOverflowProtect previous) { _value = value; _previous = previous; } public bool Contains(CastingPair value) { for (var current = this; current != null; current = current._previous) if (current._value.Equals(value)) return true; return false; } } private struct CastingPair { public readonly TypeDesc FromType; public readonly TypeDesc ToType; public CastingPair(TypeDesc fromType, TypeDesc toType) { FromType = fromType; ToType = toType; } public bool Equals(CastingPair other) => FromType == other.FromType && ToType == other.ToType; } } }
#region Copyright /* * The original .NET implementation of the SimMetrics library is taken from the Java * source and converted to NET using the Microsoft Java converter. * It is notclear who made the initial convertion to .NET. * * This updated version has started with the 1.0 .NET release of SimMetrics and used * FxCop (http://www.gotdotnet.com/team/fxcop/) to highlight areas where changes needed * to be made to the converted code. * * this version with updates Copyright (c) 2006 Chris Parkinson. * * For any queries on the .NET version please contact me through the * sourceforge web address. * * SimMetrics - SimMetrics is a java library of Similarity or Distance * Metrics, e.g. Levenshtein Distance, that provide float based similarity * measures between string Data. All metrics return consistant measures * rather than unbounded similarity scores. * * Copyright (C) 2005 Sam Chapman - Open Source Release v1.1 * * Please Feel free to contact me about this library, I would appreciate * knowing quickly what you wish to use it for and any criticisms/comments * upon the SimMetric library. * * email: [email protected] * www: http://www.dcs.shef.ac.uk/~sam/ * www: http://www.dcs.shef.ac.uk/~sam/stringmetrics.html * * address: Sam Chapman, * Department of Computer Science, * University of Sheffield, * Sheffield, * S. Yorks, * S1 4DP * United Kingdom, * * 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 */ #endregion namespace npongo.wpf.simMetrics.SimMetricsMetricUtilities { using System; using npongo.wpf.simMetrics.SimMetricsApi; using npongo.wpf.simMetrics.SimMetricsUtilities; /// <summary> /// levenstein implements the levenstein distance function. /// </summary> sealed public class Levenstein : AbstractStringMetric { const double defaultPerfectMatchScore = 1.0; const double defaultMismatchScore = 0.0; /// <summary> /// constructor to load dummy Java converter classes only /// </summary> public Levenstein() { dCostFunction = new SubCostRange0To1(); } /// <summary> /// the private cost function used in the levenstein distance. /// </summary> AbstractSubstitutionCost dCostFunction; /// <summary> /// a constant for calculating the estimated timing cost. /// </summary> double estimatedTimingConstant = 0.00018F; /// <summary> /// gets the similarity of the two strings using levenstein distance. /// </summary> /// <param name="firstWord">first word</param> /// <param name="secondWord">second word</param> /// <returns>a value between 0-1 of the similarity</returns> public override double GetSimilarity(string firstWord, string secondWord) { if ((firstWord != null) && (secondWord != null)) { double levensteinDistance = GetUnnormalisedSimilarity(firstWord, secondWord); double maxLen = firstWord.Length; if (maxLen < secondWord.Length) { maxLen = secondWord.Length; } if (maxLen == defaultMismatchScore) { return defaultPerfectMatchScore; } else { return defaultPerfectMatchScore - levensteinDistance / maxLen; } } return defaultMismatchScore; } /// <summary> gets a div class xhtml similarity explaining the operation of the metric.</summary> /// <param name="firstWord">string 1</param> /// <param name="secondWord">string 2</param> /// <returns> a div class html section detailing the metric operation. /// </returns> public override string GetSimilarityExplained(string firstWord, string secondWord) { throw new NotImplementedException(); } /// <summary> /// gets the estimated time in milliseconds it takes to perform a similarity timing. /// </summary> /// <param name="firstWord"></param> /// <param name="secondWord"></param> /// <returns>the estimated time in milliseconds taken to perform the similarity measure</returns> public override double GetSimilarityTimingEstimated(string firstWord, string secondWord) { if ((firstWord != null) && (secondWord != null)) { double firstLength = firstWord.Length; double secondLength = secondWord.Length; return firstLength * secondLength * estimatedTimingConstant; } return defaultMismatchScore; } /// <summary> /// gets the un-normalised similarity measure of the metric for the given strings.</summary> /// <param name="firstWord"></param> /// <param name="secondWord"></param> /// <returns> returns the score of the similarity measure (un-normalised)</returns> /// <remarks> /// <p/> /// Copy character from string1 over to string2 (cost 0) /// DeleteCommand a character in string1 (cost 1) /// Insert a character in string2 (cost 1) /// Substitute one character for another (cost 1) /// <p/> /// D(i-1,j-1) + d(si,tj) //subst/copy /// D(i,j) = min D(i-1,j)+1 //insert /// D(i,j-1)+1 //delete /// <p/> /// d(i,j) is a function whereby d(c,d)=0 if c=d, 1 else. /// </remarks> public override double GetUnnormalisedSimilarity(string firstWord, string secondWord) { if ((firstWord != null) && (secondWord != null)) { // Step 1 int n = firstWord.Length; int m = secondWord.Length; if (n == 0) { return m; } if (m == 0) { return n; } double[][] d = new double[n + 1][]; for (int i = 0; i < n + 1; i++) { d[i] = new double[m + 1]; } // Step 2 for (int i = 0; i <= n; i++) { d[i][0] = i; } for (int j = 0; j <= m; j++) { d[0][j] = j; } // Step 3 for (int i = 1; i <= n; i++) { // Step 4 for (int j = 1; j <= m; j++) { // Step 5 double cost = dCostFunction.GetCost(firstWord, i - 1, secondWord, j - 1); // Step 6 d[i][j] = MathFunctions.MinOf3(d[i - 1][j] + 1.0, d[i][j - 1] + 1.0, d[i - 1][j - 1] + cost); } } // Step 7 return d[n][m]; } return 0.0; } /// <summary> /// returns the long string identifier for the metric. /// </summary> public override string LongDescriptionString { get { return "Implements the basic Levenstein algorithm providing a similarity measure between two strings"; } } /// <summary> /// returns the string identifier for the metric. /// </summary> public override string ShortDescriptionString { get { return "Levenstein"; } } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Text; using System.Collections.ObjectModel; using System.IO; using System.CodeDom.Compiler; namespace Common { /// <summary> /// A collection of static methods that perform operations /// on TestCases. /// </summary> public class TestCaseUtils { public static Collection<FileInfo> CollectFilesEndingWith(string endString, params string[] fileNames) { List<FileInfo> retval = new List<FileInfo>(); foreach (string fileName in fileNames) { if (Directory.Exists(fileName)) { retval.AddRange(CollectFilesEndingWith(endString, new DirectoryInfo(fileName))); } else if (File.Exists(fileName) && fileName.EndsWith(endString)) { retval.Add(new FileInfo(fileName)); } } return new Collection<FileInfo>(retval); } public static Collection<FileInfo> CollectFilesEndingWith(string endString, DirectoryInfo resultsDir) { Collection<DirectoryInfo> allDirs = new Collection<DirectoryInfo>(); allDirs.Add(resultsDir); foreach (DirectoryInfo di in resultsDir.GetDirectories("*", SearchOption.AllDirectories)) { allDirs.Add(di); } Collection<FileInfo> retval = new Collection<FileInfo>(); foreach (DirectoryInfo di in allDirs) { foreach (FileInfo fi in di.GetFiles()) { if (fi.Name.EndsWith(endString)) retval.Add(fi); } } return retval; } public static void ReproduceBehavior(Collection<FileInfo> tests) { foreach (FileInfo oneTest in tests) { if (!Reproduce(oneTest)) { Console.WriteLine("Test " + oneTest + " NOT reproducible."); } } } private static bool Reproduce(FileInfo oneTest) { TestCase test = new TestCase(oneTest); TestCase.RunResults results = test.RunExternal(); if (results.behaviorReproduced) return true; return false; } public static void Minimize(Collection<FileInfo> testPaths) { foreach (FileInfo oneTest in testPaths) { int linesRemoved = Minimize(oneTest); if (linesRemoved > 0) Console.WriteLine("Test " + oneTest + ": removed " + linesRemoved + " lines."); } } public static int Minimize(FileInfo testPath) { TestCase testFile = new TestCase(testPath); testFile.WriteToFile(testPath + ".nonmin", false); int linesRemoved = 0; // Console.WriteLine(testFile); for (int linePos = testFile.NumTestLines - 1; linePos >= 0; linePos--) { string oldLine = testFile.RemoveLine(linePos); if (!testFile.RunExternal().behaviorReproduced) { testFile.AddLine(linePos, oldLine); } else { linesRemoved++; } } testFile.WriteToFile(testPath, false); return linesRemoved; } public static Collection<FileInfo> RemoveNonReproducibleErrors(Collection<FileInfo> partitionedTests) { Collection<FileInfo> reproducibleTests = new Collection<FileInfo>(); foreach (FileInfo test in partitionedTests) { TestCase testCase = new TestCase(test); // Don't attempt to reproduce non-error-revealing tests (to save time). if (!IsErrorRevealing(testCase)) { reproducibleTests.Add(test); continue; } TestCase.RunResults runResults = testCase.RunExternal(); if (runResults.behaviorReproduced) reproducibleTests.Add(test); else { if (!runResults.compilationSuccessful) { //Console.WriteLine("@@@COMPILATIONFAILED:"); //foreach (CompilerError err in runResults.compilerErrors) // Console.WriteLine("@@@" + err); } test.Delete(); } } return reproducibleTests; } private class EquivClass { public readonly TestCase representative; public EquivClass(TestCase testCase) { if (testCase == null) throw new ArgumentNullException(); this.representative = testCase; } public override bool Equals(object obj) { EquivClass other = obj as EquivClass; if (other == null) return false; if (!this.representative.exception.Equals(other.representative.exception)) // if "throw the same exception" return false; if (!this.representative.lastAction.Equals(other.representative.lastAction)) // if "end with the same method call" return false; return true; } public override int GetHashCode() { return this.representative.lastAction.GetHashCode() + 3 ^ this.representative.exception.GetHashCode(); } public override string ToString() { return "<equivalence class lastAction=\"" + this.representative.lastAction + "\" exception=\"" + this.representative.exception + "\">"; } } public static Collection<FileInfo> Reduce(Collection<FileInfo> tests) { Dictionary<EquivClass, TestCase> representatives = new Dictionary<EquivClass, TestCase>(); Dictionary<EquivClass, FileInfo> representativesFileInfos = new Dictionary<EquivClass, FileInfo>(); foreach (FileInfo file in tests) { TestCase testCase; try { testCase = new TestCase(file); } catch (Exception) { // File does not contain a valid test case, or // test case is malformed. continue; } EquivClass partition = new EquivClass(testCase); // If there are no representatives for this partition, // use testCase as the representative. if (!representatives.ContainsKey(partition)) { representatives[partition] = testCase; representativesFileInfos[partition] = file; } // if testCase is smaller than the current representative, // use testCase as the representative. // Delete the old representative. else if (testCase.NumTestLines < representatives[partition].NumTestLines) { //representativesFileInfos[partition].Delete(); representativesFileInfos[partition].MoveTo(representativesFileInfos[partition].FullName + ".reduced"); representatives[partition] = testCase; representativesFileInfos[partition] = file; } // Representative is redundant and larger than current representative. // Delete representative. else { //file.Delete(); file.MoveTo(file.FullName+ ".reduced"); } } List<FileInfo> retval = new List<FileInfo>(); retval.AddRange(representativesFileInfos.Values); return new Collection<FileInfo>(retval); } #region sequence-based reducer implemented by [email protected] on 11/05/2012 private class EquivClass2 { public readonly TestCase representative; public EquivClass2(TestCase testCase) { if (testCase == null) throw new ArgumentNullException(); this.representative = testCase; } public override bool Equals(object obj) { EquivClass2 other = obj as EquivClass2; if (other == null) return false; string testPlans = getSequence(this.representative.testPlanCollection); string testPlans2 = getSequence(other.representative.testPlanCollection); if (testPlans.Contains(testPlans2)) return true; if (testPlans2.Contains(testPlans)) return true; return false; } public override int GetHashCode() { return this.representative.lastAction.GetHashCode() + 3 ^ this.representative.exception.GetHashCode(); } public string getSequence(Collection<string> testplans) { string testSequence = ""; foreach (string planline in testplans) { string test = planline.Substring(0, planline.IndexOf("transformer")); testSequence += test; } return testSequence; } public override string ToString() { return "<equivalence class lastAction=\"" + this.representative.lastAction + "\" exception=\"" + this.representative.exception + "\">"; } } public static Collection<FileInfo> Reduce2(Collection<FileInfo> tests) { Dictionary<EquivClass2, TestCase> representatives = new Dictionary<EquivClass2, TestCase>(); Dictionary<EquivClass2, FileInfo> representativesFileInfos = new Dictionary<EquivClass2, FileInfo>(); foreach (FileInfo file in tests) { TestCase testCase; try { testCase = new TestCase(file); } catch (Exception) { // File does not contain a valid test case, or // test case is malformed. continue; } EquivClass2 partition = new EquivClass2(testCase); // If there are no representatives for this partition, // use testCase as the representative. if (!representatives.ContainsKey(partition)) { representatives[partition] = testCase; representativesFileInfos[partition] = file; } // if testCase is larger than the current representative (the current test sequence is a subset), // use testCase as the representative. // Delete the old representative. else if (testCase.NumTestLines > representatives[partition].NumTestLines) { //representativesFileInfos[partition].Delete(); representativesFileInfos[partition].MoveTo(representativesFileInfos[partition].FullName + ".reduced"); representatives[partition] = testCase; representativesFileInfos[partition] = file; } // sequence of testCase is a subset of the sequence of current representative. // Delete testCase. else { //file.Delete(); file.MoveTo(file.FullName+".reduced"); } } List<FileInfo> retval = new List<FileInfo>(); retval.AddRange(representativesFileInfos.Values); return new Collection<FileInfo>(retval); } #endregion //sequence-based reducer implemented by [email protected] on 11/05/2012 public static Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>> ClassifyTestsByMessage(Collection<FileInfo> tests) { Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>> testsByMessage = new Dictionary<TestCase.ExceptionDescription, Collection<FileInfo>>(); foreach (FileInfo t in tests) { TestCase tc; try { tc = new TestCase(t); } catch (TestCase.TestCaseParseException e) { Console.WriteLine("Problem parsing test {0}. (Ignoring test.)", t.FullName); Console.WriteLine(Util.SummarizeException(e, "")); continue; } Collection<FileInfo> l; if (!testsByMessage.ContainsKey(tc.exception)) { l = new Collection<FileInfo>(); testsByMessage[tc.exception] = l; } else { l = testsByMessage[tc.exception]; } l.Add(t); } return testsByMessage; } private static bool IsErrorRevealing(TestCase tc) { TestCase.ExceptionDescription d; d = TestCase.ExceptionDescription.GetDescription(typeof(System.AccessViolationException)); if (d.Equals(tc.exception)) return true; d = TestCase.ExceptionDescription.GetDescription(typeof(System.NullReferenceException)); if (d.Equals(tc.exception)) return true; d = TestCase.ExceptionDescription.GetDescription(typeof(System.NullReferenceException)); if (d.Equals(tc.exception)) return true; return false; } public static void WriteTestCasesAsUnitTest( TextWriter writer, string @namespace, string typeName, string testName, IEnumerable<TestCase> tests) { // collect imports var imports = new Dictionary<string, string>(); imports.Add("Microsoft.VisualStudio.TestTools.UnitTesting", null); foreach (var test in tests) foreach (var import in test.Imports) imports[import] = null; // start emitting file var w = new IndentedTextWriter(writer); foreach (var import in imports) w.WriteLine("using {0};", import); w.WriteLine("namespace {0}", @namespace); w.WriteLine("{"); w.Indent++; { w.WriteLine("[TestClass]"); w.WriteLine("public partial class {0}", typeName); w.WriteLine("{"); w.Indent++; { int testCount = 0; foreach (var test in tests) { string testID = testCount.ToString("000"); test.WriteAsUnitTest(w, testName + testID); w.WriteLine(); } } w.Indent--; } w.Indent--; w.WriteLine("}"); } } }