context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ClassEither.cs" company="Sven Erik Matzen"> // (c) Sven Erik Matzen // </copyright> // <summary> // The tests for the class <see cref="Either{TOne,TTwo}" />. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sem.FuncLib.Tests { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// The tests for the class <see cref="Either{TOne,TTwo}"/>. /// </summary> public static class ClassEither { /// <summary> /// The casts from native. /// </summary> [TestClass] public class CastsFromNative { /// <summary> /// Cast succeeds for a class instance with first type parameter matching class type. /// </summary> [TestMethod] public void SucceedsForAClassInstanceWithFirstTypeParameterMatchingClassType() { var target = (Either<Sample, Exception>)new Sample(5); Assert.IsFalse(target.Is<Exception>()); Assert.IsNotNull((Sample)target); Assert.IsTrue(target.Is<Sample>()); } /// <summary> /// Cast succeeds for a class instance with second type parameter matching class type. /// </summary> [TestMethod] public void SucceedsForAClassInstanceWithSecondTypeParameterMatchingClassType() { var target = (Either<Exception, Sample>)new Sample(5); Assert.IsFalse(target.Is<Exception>()); Assert.IsNotNull((Sample)target); Assert.IsTrue(target.Is<Sample>()); } } /// <summary> /// Casting from null. /// </summary> [TestClass] public class CastsFromNull { /// <summary> /// Succeeds without exception. /// </summary> [TestMethod] public void Succeeds() { var sample = (Sample)null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; Assert.IsNull((Sample)value); Assert.IsTrue(value.Is<Sample>()); } } /// <summary> /// The method <see cref="Either{TOne,TTwo}.WhenIs"/>. /// </summary> [TestClass] public class WhenIs { /// <summary> /// Detects correct type for first type parameter. /// </summary> [TestMethod] public void DetectsCorrectTypeForFirstTypeParameter() { var invoked = false; var sample = (Sample)null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; value.WhenIs<Sample>(x => invoked = true); Assert.IsTrue(invoked); } /// <summary> /// Detects correct type for second type parameter. /// </summary> [TestMethod] public void DetectsCorrectTypeForSecondTypeParameter() { var invoked = false; var sample = (Exception)null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; value.WhenIs<Exception>(x => invoked = true); Assert.IsTrue(invoked); } /// <summary> /// Does not invoke action with non matching null value in type 1. /// </summary> [TestMethod] public void WithNonMatchingNullValue1() { var invoked = false; var sample = (Exception)null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; value.WhenIs<Sample>(x => invoked = true); Assert.IsFalse(invoked); } /// <summary> /// Does not invoke action with non matching null value in type 2. /// </summary> [TestMethod] public void WhenIsWithNonMatchingNullValue2() { var invoked = false; var sample = (Sample)null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; value.WhenIs<Exception>(x => invoked = true); Assert.IsFalse(invoked); } } /// <summary> /// The casts between equivalent classes with swapped type arguments. /// </summary> [TestClass] public class CastsBetweenEquivalent { /// <summary> /// Succeeds when value is not null. /// </summary> [TestMethod] public void SucceedsWhenValueIsNotNull() { var sample = new Sample(5); var value = (Either<Sample, Exception>)sample; var target = (Either<Exception, Sample>)value; Assert.AreEqual(5, ((Sample)target).Value); Assert.AreSame(sample, (Sample)target); } /// <summary> /// Succeeds when value is null. /// </summary> [TestMethod] public void SucceedsWhenValueIsNull() { Sample sample = null; // ReSharper disable once ExpressionIsAlwaysNull var value = (Either<Sample, Exception>)sample; var target = (Either<Exception, Sample>)value; Assert.IsNull((Sample)target); } } /// <summary> /// Testing for equivalence. /// </summary> [TestClass] public class TestingEquivalence { /// <summary> /// With same type parameters and same instance returns true. /// </summary> [TestMethod] public void EqualAndSameEqualTypes() { var sample = new Sample(5); var value1 = (Either<Sample, Exception>)sample; var value2 = (Either<Sample, Exception>)sample; Assert.AreEqual(value1, value2); Assert.AreSame((Sample)value2, (Sample)value1); } /// <summary> /// With swapped type parameters and same instance returns true. /// </summary> [TestMethod] public void EqualAndSameSwappedTypes() { var sample = new Sample(5); var value1 = (Either<Sample, Exception>)sample; var value2 = (Either<Exception, Sample>)sample; Assert.AreEqual(value1, value2); Assert.AreSame((Sample)value2, (Sample)value1); } /// <summary> /// With same type parameters and different instances returns false. /// </summary> [TestMethod] public void NotEqualAndSameTypes() { var sample1 = new Sample(5); var sample2 = new Sample(6); var value1 = (Either<Sample, Exception>)sample1; var value2 = (Either<Sample, Exception>)sample2; Assert.AreNotEqual(value1, value2); Assert.AreNotSame((Sample)value2, (Sample)value1); } /// <summary> /// With swapped type parameters and different instances returns false. /// </summary> [TestMethod] public void NotEqualAndSwappedTypes() { var sample1 = new Sample(5); var sample2 = new Sample(6); var value1 = (Either<Exception, Sample>)sample1; var value2 = (Either<Sample, Exception>)sample2; Assert.AreNotEqual(value1, value2); Assert.AreNotSame((Sample)value2, (Sample)value1); } /// <summary> /// With different values using the equals operator returns false. /// </summary> [TestMethod] public void NotEqualWithEqualsOperator() { var sample1 = new Sample(5); var sample2 = new Sample(6); var value1 = (Either<Exception, Sample>)sample1; var value2 = (Either<Exception, Sample>)sample2; Assert.IsFalse(value1 == value2); } /// <summary> /// With same instance using the equals operator returns true. /// </summary> [TestMethod] public void EqualWithEqualsOperator() { var sample1 = new Sample(6); var value1 = (Either<Exception, Sample>)sample1; var value2 = (Either<Exception, Sample>)sample1; Assert.IsTrue(value1 == value2); } /// <summary> /// With different instances using the "not equals" operator returns true. /// </summary> [TestMethod] public void NotEqualWithNotEqualsOperator() { var sample1 = new Sample(5); var sample2 = new Sample(6); var value1 = (Either<Exception, Sample>)sample1; var value2 = (Either<Exception, Sample>)sample2; Assert.IsTrue(value1 != value2); } /// <summary> /// With same instance using the "not equals" operator returns false. /// </summary> [TestMethod] public void EqualWithNotEqualsOperator() { var sample1 = new Sample(6); var value1 = (Either<Exception, Sample>)sample1; var value2 = (Either<Exception, Sample>)sample1; Assert.IsFalse(value1 != value2); } } } }
#region Copyright // ----------------------------------------------------------------------- // // Copyright (c) 2012, Shad Storhaug <shad@shadstorhaug.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------- #endregion namespace ContinuousSeo.W3cValidation.Runner.UnitTests { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using NUnit.Framework; using Moq; using ContinuousSeo.Core.Extensions; using ContinuousSeo.Core.Net; using ContinuousSeo.Core.IO; using ContinuousSeo.W3cValidation.Runner.Parsers; [TestFixture] public class SitemapsParserTests { #region SetUp / TearDown [SetUp] public void Init() { } [TearDown] public void Dispose() { } #endregion #region ProcessSitemapsFile Method private static void WriteSitemapsStream(Stream stream, IEnumerable<SitemapInfo> entries) { XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); writer.WriteStartDocument(true); writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9"); writer.WriteStartElement("url"); foreach (SitemapInfo entry in entries) { writer.WriteStartElement("loc"); writer.WriteRaw(entry.Location); writer.WriteEndElement(); writer.WriteStartElement("lastmod"); writer.WriteRaw(entry.LastModification.ToString("yyyy-MM-dd")); writer.WriteEndElement(); writer.WriteStartElement("changefreq"); writer.WriteRaw(entry.ChangeFrequency.ToString().ToLowerInvariant()); writer.WriteEndElement(); writer.WriteStartElement("priority"); writer.WriteRaw(entry.Priority.GetDescription()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); // Reset to beginning of stream writer.Flush(); stream.Position = 0; // leave writer open so the stream isn't closed } private void WriteValidSitemapsStreamWith4Urls(Stream stream) { List<SitemapInfo> entries = new List<SitemapInfo>(); entries.Add(new SitemapInfo("http://www.google.com/", DateTime.MinValue, SitemapChangeFrequency.monthly, SitemapPriority.Priority5)); entries.Add(new SitemapInfo("http://www.google.com/test.aspx", DateTime.MinValue, SitemapChangeFrequency.monthly, SitemapPriority.Priority5)); entries.Add(new SitemapInfo("http://www.google.com/test1.aspx", DateTime.MinValue, SitemapChangeFrequency.monthly, SitemapPriority.Priority5)); entries.Add(new SitemapInfo("http://www.google.com/test2.aspx", DateTime.MinValue, SitemapChangeFrequency.monthly, SitemapPriority.Priority5)); WriteSitemapsStream(stream, entries); } [Test] public void ParseUrlsFromFile_ValidStreamWith4Urls_ShouldReturn4Urls() { // arrange var httpClient = new Mock<IHttpClient>(); var streamFactory = new Mock<IStreamFactory>(); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); IEnumerable<string> result; using (Stream file = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(file); // act result = target.ParseUrlsFromFile(file); } // assert var actual = result.Count(); var expected = 4; Assert.AreEqual(expected, actual); } [Test] public void ParseUrlsFromFile_ValidStreamWith4Urls_ShouldMatch1stUrl() { // arrange var httpClient = new Mock<IHttpClient>(); var streamFactory = new Mock<IStreamFactory>(); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); IEnumerable<string> result; using (Stream file = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(file); // act result = target.ParseUrlsFromFile(file); } // assert var actual = result.First(); var expected = "http://www.google.com/"; Assert.AreEqual(expected, actual); } [Test] public void ParseUrlsFromFile_ValidStreamWith4Urls_ShouldMatch2ndUrl() { // arrange var httpClient = new Mock<IHttpClient>(); var streamFactory = new Mock<IStreamFactory>(); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); IEnumerable<string> result; using (Stream file = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(file); // act result = target.ParseUrlsFromFile(file); } // assert var actual = result.ElementAt(1); var expected = "http://www.google.com/test.aspx"; Assert.AreEqual(expected, actual); } [Test] public void ParseUrlsFromFile_ValidUrlWith4Urls_ShouldMatch1stUrl() { // arrange IEnumerable<string> result; string sitemapsUrl = "http://www.mydomain.com/sitemaps.xml"; using (var sitemapsFile = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(sitemapsFile); var httpClient = new Mock<IHttpClient>(); httpClient.Setup(x => x.GetResponseStream(sitemapsUrl)).Returns(sitemapsFile); var streamFactory = new Mock<IStreamFactory>(); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); // act result = target.ParseUrlsFromFile(sitemapsUrl); } // assert var actual = result.ElementAt(0); var expected = "http://www.google.com/"; Assert.AreEqual(expected, actual); } public void ParseUrlsFromFile_ValidUrlWith4Urls_ShouldMatch2ndUrl() { // arrange IEnumerable<string> result; string sitemapsUrl = "http://www.mydomain.com/sitemaps.xml"; using (var sitemapsFile = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(sitemapsFile); var httpClient = new Mock<IHttpClient>(); httpClient.Setup(x => x.GetResponseStream(sitemapsUrl)).Returns(sitemapsFile); var streamFactory = new Mock<IStreamFactory>(); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); // act result = target.ParseUrlsFromFile(sitemapsUrl); } // assert var actual = result.ElementAt(1); var expected = "http://www.google.com/test.aspx"; Assert.AreEqual(expected, actual); } [Test] public void ParseUrlsFromFile_ValidFilePathWith4Urls_ShouldMatch1stUrl() { // arrange IEnumerable<string> result; string sitemapsPath = @"C:\sitemaps.xml"; using (var sitemapsFile = new MemoryStream()) { WriteValidSitemapsStreamWith4Urls(sitemapsFile); var httpClient = new Mock<IHttpClient>(); var streamFactory = new Mock<IStreamFactory>(); streamFactory.Setup(x => x.GetFileStream(sitemapsPath, FileMode.Open, FileAccess.Read)).Returns(sitemapsFile); SitemapsParser target = new SitemapsParser(httpClient.Object, streamFactory.Object); // act result = target.ParseUrlsFromFile(sitemapsPath); } // assert var actual = result.ElementAt(1); var expected = "http://www.google.com/test.aspx"; Assert.AreEqual(expected, actual); } #endregion #region Private Classes public enum SitemapChangeFrequency { always, hourly, daily, weekly, monthly, yearly, never } public enum SitemapPriority { [System.ComponentModel.Description("0.0")] Priority0, [System.ComponentModel.Description("0.1")] Priority1, [System.ComponentModel.Description("0.2")] Priority2, [System.ComponentModel.Description("0.3")] Priority3, [System.ComponentModel.Description("0.4")] Priority4, [System.ComponentModel.Description("0.5")] Priority5, [System.ComponentModel.Description("0.6")] Priority6, [System.ComponentModel.Description("0.7")] Priority7, [System.ComponentModel.Description("0.8")] Priority8, [System.ComponentModel.Description("0.9")] Priority9, [System.ComponentModel.Description("1.0")] Priority10, } private class SitemapInfo { public SitemapInfo(string location, DateTime lastModification, SitemapChangeFrequency changeFrequency, SitemapPriority priority) { this.Location = location; this.LastModification = lastModification; this.ChangeFrequency = changeFrequency; this.Priority = priority; } public string Location { get; set; } public DateTime LastModification { get; set; } public SitemapChangeFrequency ChangeFrequency { get; set; } public SitemapPriority Priority { get; set; } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace SIL.Xml { ///<summary> /// Responsible to read a file which has a sequence of similar elements /// and return byte arrays of each element for further processing. /// This version works entirely with byte arrays, except for the GetSecondLevelElementStrings /// methods, which should only be used for testing or small files. /// ///</summary> public class FastXmlElementSplitter : IDisposable { private readonly static Encoding EncUtf8 = Encoding.UTF8; private readonly static byte _openingAngleBracket = EncUtf8.GetBytes("<")[0]; private readonly static byte _closingAngleBracket = EncUtf8.GetBytes(">")[0]; private readonly static byte _slash = EncUtf8.GetBytes("/")[0]; private readonly static byte _hyphen = EncUtf8.GetBytes("-")[0]; private static byte[] cdataStart = EncUtf8.GetBytes("![CDATA["); private static byte[] cdataEnd = EncUtf8.GetBytes("]]>"); private static byte[] startComment = EncUtf8.GetBytes("!--"); private static byte[] endComment = EncUtf8.GetBytes("-->"); private IByteAccessor _input; /// <summary> /// The value of this boolean will only be set after calls are made to get the elements /// </summary> private bool _foundOptionalFirstElement; /// <summary> /// Characters that may follow a marker and indicate the end of it (for a successful match). /// </summary> private static readonly HashSet<byte> Terminators = new HashSet<byte> { EncUtf8.GetBytes(" ")[0], EncUtf8.GetBytes("\t")[0], EncUtf8.GetBytes("\r")[0], EncUtf8.GetBytes("\n")[0], EncUtf8.GetBytes(">")[0], EncUtf8.GetBytes("/")[0] }; private int _endOfHeadingOffset = -1; // saved initial offset so heading can be retrieved. private int _currentOffset; // Position in the file as we work through it. // index of the angle bracket of the final, closing top-level marker. // In the special case where the top-level marker has no children or close tag (<top/>), // it may be the start of the whole top-level tag. private int _endOfRecordsOffset; /// <summary> /// Constructor /// </summary> /// <param name="pathname">Pathname of file to process.</param> public FastXmlElementSplitter(string pathname) { if (string.IsNullOrEmpty(pathname)) throw new ArgumentException("Null or empty string", "pathname"); if (!File.Exists(pathname)) throw new FileNotFoundException("File was not found.", "pathname"); _input = new AsyncFileReader(pathname); } /// <summary> /// Constructor /// </summary> /// <param name="bytes">Content of XML to be split - could be extracted bytes from splitting a file</param> public FastXmlElementSplitter(byte[] bytes) { if (bytes == null || bytes.Length == 0) throw new ArgumentException("Null or empty byte array", "bytes"); _input = new ByteArrayReader(bytes); } /// <summary> /// Gets the bytes from the start of the data to the first subelement /// </summary> public byte[] GetHeader() { if (_endOfHeadingOffset == -1) InitializeOffsets(); return _input.SubArray(0, _endOfHeadingOffset); } /// <summary> /// Gets the bytes from the end of the last subelement to the end of the data /// </summary> public byte[] GetTrailer() { if (_endOfHeadingOffset == -1) InitializeOffsets(); return _input.SubArray(_endOfRecordsOffset, _input.Length - _endOfRecordsOffset); } ///<summary> /// Return the second level elements that are in the input file. ///</summary> ///<param name="recordMarker">The element name of elements that are children of the main root elment.</param> ///<returns>A collection of byte arrays of the records.</returns> /// <remarks> /// <para> /// <paramref name="recordMarker"/> should not contain the angle brackets that start/end an xml element. /// </para> /// <para> /// The input file can contain one child element of the main root element, before the elements /// marked with <paramref name="recordMarker"/>, but if the file has them, you must use another overload /// and specify the marker for that optional element. /// </para> /// </remarks> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="recordMarker"/> is null, an empty string, or there are no such records in the file. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if the input file is not xml. /// </exception> public IEnumerable<byte[]> GetSecondLevelElementBytes(string recordMarker) { return GetSecondLevelElementBytes(null, recordMarker); } /// <summary> /// Gets all second level elements that are in input file /// </summary> /// <returns>Enumeration of SecondaryElements containing element name and bytes for each element</returns> public IEnumerable<SecondaryElement> GetSecondLevelElements() { return GetSecondLevelElementBytesInternal(null, null); } ///<summary> /// Return the second level elements that are in the input file. ///</summary> ///<param name="recordMarker">The element name of elements that are children of the main root elment.</param> ///<returns>A collection of strings of the records.</returns> /// <remarks> /// <para> /// <paramref name="recordMarker"/> should not contain the angle brackets that start/end an xml element. /// </para> /// <para> /// The input file can contain one child elements of the main root element before this, but if so, you must /// call the appropriate overload and specify the first element marker. /// </para> /// </remarks> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="recordMarker"/> is null, an empty string, or there are no such records in the file. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown if the input file is not xml. /// </exception> public IEnumerable<string> GetSecondLevelElementStrings(string recordMarker) { bool foundOptionalFirstElement; return GetSecondLevelElementStrings(null, recordMarker, out foundOptionalFirstElement); } /// <summary> /// Return the second level elements that are in the input file, including an optional first element. /// Provides a boolean to indicate whether the optional first element was found. /// Note that the overload without this out param is an iterator and can return the results /// without creating a collection of all of them. /// </summary> public List<byte[]> GetSecondLevelElementBytes(string firstElementMarker, string recordMarker, out bool foundOptionalFirstElement) { var result = GetSecondLevelElementBytesInternal(firstElementMarker, recordMarker).Select(t => t.Bytes).ToList(); foundOptionalFirstElement = _foundOptionalFirstElement; return result; } /// <summary> /// Return the second level elements that are in the input file, including an optional first element. /// </summary> public IEnumerable<byte[]> GetSecondLevelElementBytes(string firstElementMarker, string recordMarker) { if (string.IsNullOrEmpty(recordMarker)) throw new ArgumentException("Null or empty string", "recordMarker"); return GetSecondLevelElementBytesInternal(firstElementMarker, recordMarker).Select(t => t.Bytes); } /// <summary> /// Gets all second level elements /// </summary> /// <param name="firstElementMarker">if provided, first element will be checked to see if it matches this marker</param> /// <param name="recordMarker">if provided, all second level elements besides the first must match this marker</param> /// <returns>Enumeration of tuples containing marker name and bytes for all second level elements</returns> private IEnumerable<SecondaryElement> GetSecondLevelElementBytesInternal(string firstElementMarker, string recordMarker) { _foundOptionalFirstElement = false; InitializeOffsets(); var recordMarkerAsBytes = recordMarker != null ? FormatRecordMarker(recordMarker) : null; if (firstElementMarker != null && _currentOffset < _endOfRecordsOffset) { var firstElementMarkerAsBytes = FormatRecordMarker(firstElementMarker); if (MatchMarker(firstElementMarkerAsBytes)) { _foundOptionalFirstElement = true; yield return new SecondaryElement(firstElementMarker, MakeElement(firstElementMarkerAsBytes)); AdvanceToOpenAngleBracket(); } } // We've processed the special first element if any and should be at the first record marker (or end of file) while (_currentOffset < _endOfRecordsOffset) { if (recordMarker == null) { recordMarkerAsBytes = GetOpeningMarker(); } else if (!MatchMarker(recordMarkerAsBytes)) { var msg = string.Format("Can't find{0} main record with element name '{1}'", firstElementMarker == null ? "" : string.Format(" optional element name '{0}' or", firstElementMarker), recordMarker); throw new ArgumentException(msg); } yield return new SecondaryElement(recordMarker ?? EncUtf8.GetString(recordMarkerAsBytes), MakeElement(recordMarkerAsBytes)); AdvanceToOpenAngleBracket(); } } /// <summary> /// Given that _currentInput is at the first character of the marker of the opening XML tag /// of an element, return the byte array that is the complete element. /// </summary> /// <param name="marker"></param> /// <returns></returns> private byte[] MakeElement(byte[] marker) { int start = _currentOffset - 1; // including the opening angle bracket int depth = 1; // How many unmatched opening marker elements have we seen? while (true) { bool gotOpenBracket = AdvanceToAngleBracket(); if (_currentOffset > _endOfRecordsOffset) throw new ArgumentException("Unmatched opening tag " + marker); // We have to distinguish these cases: // 1. <x... : depth++ (start of opening marker) // 2: ...> : no change (end of opening or closing marker) // 3: </x... : depth-- (closing marker) // 4: .../> : depth-- (end of open marker that has no close marker) // 5: <![CDATA[ : advance to matching ]]> // 6: <!-- : depth++ // 7: --> : depth-- // If depth is zero we must stop and output. In case 3 we must also check for the correct closing marker. if (gotOpenBracket) { if (_input[_currentOffset] == _slash) depth--; // case 3 else if (Match(cdataStart)) { _currentOffset += cdataStart.Length; while (_currentOffset <= _endOfRecordsOffset - cdataEnd.Length && !Match(cdataEnd)) _currentOffset++; continue; } else { depth++; // case 1 (or 6) } } else { if (_input[_currentOffset - 2] == _slash) depth--; // case 4 else if (_input[_currentOffset - 2] == _hyphen && _input[_currentOffset - 3] == _hyphen) depth--; // case 6 // otherwise case 2, do nothing. } if (depth == 0) { if (gotOpenBracket) { // case 3, advance past opening slash _currentOffset++; if (!MatchMarker(marker)) throw new ArgumentException("Unmatched opening tag " + marker); // wrong close marker AdvanceToClosingAngleBracket(); } // We matched the marker we started with, output the chunk. if (_input[_currentOffset - 1] != _closingAngleBracket) throw new ArgumentException("Unmatched opening tag " + marker); return _input.SubArray(start, _currentOffset - start); } if (_currentOffset == _endOfRecordsOffset) throw new ArgumentException("Unmatched opening tag " + marker); } } /// <summary> /// Get the next opening element name /// </summary> /// <returns>element name as a byte array</returns> byte[] GetOpeningMarker() { int curpos = _currentOffset; while (!Terminators.Contains(_input[curpos])) curpos++; return _input.SubArray(_currentOffset, curpos - _currentOffset); } /// <summary> /// Return true if the bytes starting at _currentPosition match the specified marker. /// The following character must not be part of a marker name. /// /// Enhance JohnT: technically I think there could be white space between the opening angle bracket and the /// marker. We can make that enhancement if we need it. /// </summary> /// <param name="marker"></param> /// <returns></returns> bool MatchMarker(byte[] marker) { if (!Match(marker)) return false; return Terminators.Contains(_input[_currentOffset + marker.Length]); } /// <summary> /// Return true if the bytes starting at _currentPosition match the specified marker. No termination is required. /// </summary> /// <param name="marker"></param> /// <returns></returns> private bool Match(byte[] marker) { if (_currentOffset + marker.Length >= _endOfRecordsOffset) return false; for (int i = 0; i < marker.Length; i++) { if (_input[_currentOffset + i] != marker[i]) return false; } return true; } /// <summary> /// Return the second level elements that are in the input file, including an optional first element. /// </summary> public IEnumerable<string> GetSecondLevelElementStrings(string firstElementMarker, string recordMarker, out bool foundOptionalFirstElement) { // tempting to call the internal method and avoid the list, but need to create the list to make sure the flag is set correctly // before we return. return GetSecondLevelElementBytes(firstElementMarker, recordMarker, out foundOptionalFirstElement) .Select(byteResult => EncUtf8.GetString(byteResult)); } /// <summary> /// This method adjusts _currentPosition to the offset of the first record, /// and adjusts _endOfRecordsOffset to the end of the last record. /// If there are no records they will end up equal, at the index of the last open angle bracket /// in the file. Throws exception if there is no top-level element in the file. /// </summary> private void InitializeOffsets() { // just reset current record if initialize was already done if (_endOfHeadingOffset != -1) { _currentOffset = _endOfHeadingOffset + 1; return; } // Find offset for end of records. _endOfRecordsOffset = -1; for (var i = _input.Length - 1; i >= 0; --i) { if (_input[i] != _openingAngleBracket) continue; _endOfRecordsOffset = i; break; } if (_endOfRecordsOffset < 0) throw new ArgumentException("There was no main ending tag in the file."); // Find first angle bracket _currentOffset = 0; AdvanceToOpenAngleBracket(); if (_currentOffset < _input.Length && (_input[_currentOffset] == EncUtf8.GetBytes("?")[0])) { // got an xml declaration. Find the NEXT open bracket. This will be the root element. AdvanceToOpenAngleBracket(); } if (_currentOffset >= _endOfRecordsOffset) { // There is only one opening angle bracket in the file, except possibly the xml declaration. // This is valid in just one case, when the root element ends /> bool gotClose = false; for (var i = _input.Length - 1; i > _endOfRecordsOffset; --i) { var c = Convert.ToChar(_input[i]); if (Char.IsWhiteSpace(c)) continue; if (gotClose) { if (c == '/') return; // OK, empty file, except for the self-terminating root. } else { if (c == '>') { gotClose = true; continue; // now we need the slash } } break; // got some invalid sequence at end of file } throw new ArgumentException("There was no main starting tag in the file."); } // Find the NEXT open bracket after the root. This should be the first second-level element. AdvanceToOpenAngleBracket(); // It's OK for this to be equal to _endOfRecordsOffset. Just means a basically empty file, with no second-level elements. _endOfHeadingOffset = _currentOffset - 1; } /// <summary> /// Move _currentOffset to the character following the next angle bracket of either type, or to _endOfRecordOffset if that comes first. /// Answer true if what we got was an opening bracket /// </summary> private bool AdvanceToAngleBracket() { for (; _currentOffset < _endOfRecordsOffset; _currentOffset++) { var inputByte = _input[_currentOffset]; if (inputByte == _openingAngleBracket) { _currentOffset++; return true; } if (inputByte == _closingAngleBracket) { _currentOffset++; return false; } } return _input[_currentOffset] == _openingAngleBracket; } /// <summary> /// Move _currentOffset to the character following the next angle bracket, or to _endOfRecordOffset if that comes first. /// Skip comments. /// </summary> private void AdvanceToOpenAngleBracket() { for (; _currentOffset < _endOfRecordsOffset;_currentOffset++) { if (_input[_currentOffset] == _openingAngleBracket) { _currentOffset++; if (Match(startComment)) { _currentOffset += startComment.Length; while (_currentOffset + endComment.Length < _endOfRecordsOffset && !Match(endComment)) _currentOffset++; continue; } return; } } } /// <summary> /// Move _currentOffset to the character following the next closing angle bracket, or to _endOfRecordOffset if that comes first. /// </summary> private void AdvanceToClosingAngleBracket() { for (; _currentOffset < _endOfRecordsOffset; _currentOffset++) { if (_input[_currentOffset] == _closingAngleBracket) { _currentOffset++; return; } } } private static byte[] FormatRecordMarker(string recordMarker) { return EncUtf8.GetBytes(recordMarker.Replace("<", null).Replace(">", null).Trim()); } ~FastXmlElementSplitter() { Debug.WriteLine("**** FastXmlElementSplitter.Finalizer called ****"); Dispose(false); // The base class finalizer is called automatically. } // Enhance JohnT: there appears to be no reason for this class to be Disposable. public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } private bool IsDisposed { get; set; } private void Dispose(bool disposing) { if (IsDisposed) return; // Done already, so nothing left to do. if (disposing) { if (_input != null) _input.Close(); _input = null; } // Dispose unmanaged resources here, whether disposing is true or false. // Main data members. IsDisposed = true; } } /// <summary> /// An abstraction of the methods needed to either access a file or a byte array in similar ways. /// </summary> internal interface IByteAccessor { void Close(); byte this[int index] { get; } int Length { get; } byte[] SubArray(int start, int count); } /// <summary> /// Class responsible to manage access to the content of a file. The interface is mostly a subset of byte array, /// and in general it replaces input = File.ReadAllBytes(pathname) with input = new AsyncFileReader(pathname), /// and input can be used much like the array. One difference is that the AsyncFileReader should be closed. /// The benefit of using this is that it is not necessary to allocate an array as big as the file. /// Also, if the file is mainly accessed sequentially, some of the data reading will be overlapped with /// processing it, at least for a large file. /// </summary> internal class AsyncFileReader : IByteAccessor { private string _pathname; // MS doc says this is the smallest buffer that will produce real async reads. // We want them relatively small so we can start overlapping quickly. // For testing this class, kbufLen is set very small. // Otherwise the unit tests will just load everything into the first 65K buffer, and much of the logic // will never be tried. internal static int kbufLen = 65536; private const int kBufferCount = 3; private int _currentBuffer; // index of a buffer (no longer Loading) where we last found a desired byte. -1 if none. // The typical use of this class is reading through a file, noting a start position, reading to an end position, // and then making a byte array out of what is in between. Thus, it is basically a sequential read, with an occasional, // typically short, jump backwards. // Using three buffers allows us to have // - one we are reading through (_currentBuffer), // - one we are in the process of loading (asynchronously, while processing the previous one...this is typically // the 'next' buffer in the rotation after _currentBuffer) // - the one we read through last, which we keep around so that stepping back to get the chunk we identified // does not require us to re-read anything (unless a chunk is really huge). Buffer[] buffers = new Buffer[kBufferCount]; private FileStream m_reader; public AsyncFileReader(string pathName) { _pathname = pathName; Length = (int)new FileInfo(_pathname).Length; // Setting a high offset ensures that no byte we want will be in any buffer's range. for (int i = 0; i < kBufferCount; i++) buffers[i] = new Buffer() {Data = new byte[kbufLen], Offset = Length}; _currentBuffer = -1; // no buffer is loaded m_reader = new FileStream(_pathname, FileMode.Open, FileAccess.Read, FileShare.None, 4096, true); // Read a block at the end of the file, which we happen to know we will want first. StartReading(Math.Max(Length - kbufLen, 0)); } public void Close() { // MS Doc says EndRead must be called exactly once for each BeginRead. Not sure whether anything // very bad will happen if we don't finish the final reads, but just in case... for (int i = 0; i < kBufferCount; i++) { if (buffers[i].Loading) m_reader.EndRead(buffers[i].Token); } m_reader.Close(); } // Start reading a block at the specified (byte) index. // Return the index of the block we are loading it into. int StartReading(int index) { // Load the new data into the buffer after the current one, leaving the buffer before it holding // hopefully more recent data. int bufIndex = NextBuffer(_currentBuffer); var buffer = buffers[bufIndex]; // Have to finish the current read, even though we will then overwrite the data. // It should be very unusual, if it can happen at all, that the next buffer needs loading. FinishRead(buffer); // Start an asynchronous read. When something actually needs the data from this buffer, // it must call EndRead(buffer.Token) and then set Loading to false. m_reader.Seek(index, SeekOrigin.Begin); buffer.Token = m_reader.BeginRead(buffer.Data, 0, buffer.Data.Length, null, null); buffer.Offset = index; buffer.Loading = true; return bufIndex; } private void FinishRead(Buffer buffer) { if (!buffer.Loading) return; // already loaded. m_reader.EndRead(buffer.Token); buffer.Loading = false; } /// <summary> /// This makes the class function like a byte array, allowing [n] to get the nth byte. /// </summary> /// <param name="n"></param> /// <returns></returns> public byte this[int n] { get { Buffer currentBuffer; // Try to get it from the current buffer. if (_currentBuffer >= 0) { currentBuffer = buffers[_currentBuffer]; if (n >= currentBuffer.Offset && n < currentBuffer.Offset + kbufLen) return currentBuffer.Data[n - currentBuffer.Offset]; } for (int i = 0; i < kBufferCount; i++) { if (i == _currentBuffer) continue; currentBuffer = buffers[i]; if (n >= currentBuffer.Offset && n < currentBuffer.Offset + kbufLen) { // We have a buffer that covers the relevant part of the file. FinishRead(currentBuffer); int prevBuffer = _currentBuffer; _currentBuffer = i; // If we advanced from one block to the following one, go ahead and start loading the next, if any. // For typical sequential access, this should overlap the reading with processing the block // we just finished loading. // If we went back to a previous block, probably in order to get a SubArray that extends into // the current one, we want to leave the current block intact. if (_currentBuffer == NextBuffer(prevBuffer) && currentBuffer.Offset + kbufLen < Length) StartReading(currentBuffer.Offset + kbufLen); return currentBuffer.Data[n - currentBuffer.Offset]; } } // no current buffer has it. This is usually because we are going back to get a SubArray // up to the present location, and had to back up more than one buffer. // We may want a few bytes before the start of the sub-array, but mainly we will want following bytes. _currentBuffer = StartReading(Math.Max(n - 3, 0)); currentBuffer = buffers[_currentBuffer]; FinishRead(currentBuffer); // Start reading the NEXT block; hopefully it will be ready by the time we need it. if (currentBuffer.Offset + kbufLen < Length) StartReading(currentBuffer.Offset + kbufLen); return currentBuffer.Data[n - currentBuffer.Offset]; } } int NextBuffer(int index) { return index + 1 < kBufferCount ? index + 1 : 0; // 0 initially, when _currentBuffer is -1. } /// <summary> /// Initialized to length of file in constructor. /// </summary> public int Length { get; private set; } public byte[] SubArray(int start, int count) { var result = new byte[count]; // Enhance JohnT: this could be optimized to copy chunks of buffers. for (int i = 0; i < count; i++) result[i] = this[i + start]; return result; } } class Buffer { public bool Loading; // true if we're still loading data for it. public byte[] Data; // bytes we read from the file public int Offset; // from start of whole file (or beyond end, if we haven't started loading buffer) public IAsyncResult Token; // from BeginRead; should be passed to EndRead when we need the data. } class ByteArrayReader : IByteAccessor { readonly byte[] _bytes; public ByteArrayReader(byte[] bytes) { _bytes = bytes; } #region ByteAccessor Members public void Close() { // nothing to do } public byte this[int index] { get { return _bytes[index]; } } public int Length { get { return _bytes.Length; } } public byte[] SubArray(int start, int count) { var result = new byte[count]; Array.Copy(_bytes, start, result, 0, count); return result; } #endregion } public class SecondaryElement { public string Name { get; private set; } public byte[] Bytes { get; private set; } public SecondaryElement(string name, byte[] bytes) { Name = name; Bytes = bytes; } public string BytesAsString { get { return Encoding.UTF8.GetString(Bytes); } } } }
/* * 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. * */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <keiron@aftexsw.com> to whom the Ant project is very grateful for his * great code. */ using System; using System.IO; namespace Org.BouncyCastle.Apache.Bzip2 { /** * An input stream that decompresses from the BZip2 format (with the file * header chars) to be read as any other stream. * * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a> * * <b>NB:</b> note this class has been modified to read the leading BZ from the * start of the BZIP2 stream to make it compatible with other PGP programs. */ public class CBZip2InputStream : Stream { private static void Cadvise() { //System.out.Println("CRC Error"); //throw new CCoruptionError(); } // private static void BadBGLengths() { // Cadvise(); // } // // private static void BitStreamEOF() { // Cadvise(); // } private static void CompressedStreamEOF() { Cadvise(); } private void MakeMaps() { int i; nInUse = 0; for (i = 0; i < 256; i++) { if (inUse[i]) { seqToUnseq[nInUse] = (char) i; unseqToSeq[i] = (char) nInUse; nInUse++; } } } /* index of the last char in the block, so the block size == last + 1. */ private int last; /* index in zptr[] of original string after sorting. */ private int origPtr; /* always: in the range 0 .. 9. The current block size is 100000 * this number. */ private int blockSize100k; private bool blockRandomised; private int bsBuff; private int bsLive; private CRC mCrc = new CRC(); private bool[] inUse = new bool[256]; private int nInUse; private char[] seqToUnseq = new char[256]; private char[] unseqToSeq = new char[256]; private char[] selector = new char[BZip2Constants.MAX_SELECTORS]; private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; private int[] tt; private char[] ll8; /* freq table collected to save a pass over the data during decompression. */ private int[] unzftab = new int[256]; private int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[] minLens = new int[BZip2Constants.N_GROUPS]; private Stream bsStream; private bool streamEnd = false; private int currentChar = -1; private const int START_BLOCK_STATE = 1; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; private int currentState = START_BLOCK_STATE; private int storedBlockCRC, storedCombinedCRC; private int computedBlockCRC, computedCombinedCRC; int i2, count, chPrev, ch2; int i, tPos; int rNToGo = 0; int rTPos = 0; int j2; char z; public CBZip2InputStream(Stream zStream) { ll8 = null; tt = null; BsSetStream(zStream); Initialize(); InitBlock(); SetupBlock(); } internal static int[][] InitIntArray(int n1, int n2) { int[][] a = new int[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new int[n2]; } return a; } internal static char[][] InitCharArray(int n1, int n2) { char[][] a = new char[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new char[n2]; } return a; } public override int ReadByte() { if (streamEnd) { return -1; } else { int retChar = currentChar; switch (currentState) { case START_BLOCK_STATE: break; case RAND_PART_A_STATE: break; case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_A_STATE: break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; default: break; } return retChar; } } private void Initialize() { char magic3, magic4; magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'B' && magic4 != 'Z') { throw new IOException("Not a BZIP2 marked stream"); } magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'h' || magic4 < '1' || magic4 > '9') { BsFinishedWithStream(); streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } private void InitBlock() { char magic1, magic2, magic3, magic4; char magic5, magic6; magic1 = BsGetUChar(); magic2 = BsGetUChar(); magic3 = BsGetUChar(); magic4 = BsGetUChar(); magic5 = BsGetUChar(); magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); if (BsR(1) == 1) { blockRandomised = true; } else { blockRandomised = false; } // currBlockNo++; GetAndMoveToFrontDecode(); mCrc.InitialiseCRC(); currentState = START_BLOCK_STATE; } private void EndBlock() { computedBlockCRC = mCrc.GetFinalCRC(); /* A bad CRC is considered a fatal error. */ if (storedBlockCRC != computedBlockCRC) { CrcError(); } computedCombinedCRC = (computedCombinedCRC << 1) | (int)(((uint)computedCombinedCRC) >> 31); computedCombinedCRC ^= computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != computedCombinedCRC) { CrcError(); } BsFinishedWithStream(); streamEnd = true; } private static void BlockOverrun() { Cadvise(); } private static void BadBlockHeader() { Cadvise(); } private static void CrcError() { Cadvise(); } private void BsFinishedWithStream() { try { if (this.bsStream != null) { this.bsStream.Dispose(); this.bsStream = null; } } catch { //ignore } } private void BsSetStream(Stream f) { bsStream = f; bsLive = 0; bsBuff = 0; } private int BsR(int n) { int v; while (bsLive < n) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } private char BsGetUChar() { return (char) BsR(8); } private int BsGetint() { int u = 0; u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); return u; } private int BsGetIntVS(int numBits) { return (int) BsR(numBits); } private int BsGetInt32() { return (int) BsGetint(); } private void HbCreateDecodeTables(int[] limit, int[] basev, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) { for (j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp] = j; pp++; } } } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] = 0; } for (i = 0; i < alphaSize; i++) { basev[length[i] + 1]++; } for (i = 1; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] += basev[i - 1]; } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { limit[i] = 0; } vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (basev[i + 1] - basev[i]); limit[i] = vec - 1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) { basev[i] = ((limit[i - 1] + 1) << 1) - basev[i]; } } private void RecvDecodingTables() { char[][] len = InitCharArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); int i, j, t, nGroups, nSelectors, alphaSize; int minLen, maxLen; bool[] inUse16 = new bool[16]; /* Receive the mapping table */ for (i = 0; i < 16; i++) { if (BsR(1) == 1) { inUse16[i] = true; } else { inUse16[i] = false; } } for (i = 0; i < 256; i++) { inUse[i] = false; } for (i = 0; i < 16; i++) { if (inUse16[i]) { for (j = 0; j < 16; j++) { if (BsR(1) == 1) { inUse[i * 16 + j] = true; } } } } MakeMaps(); alphaSize = nInUse + 2; /* Now the selectors */ nGroups = BsR(3); nSelectors = BsR(15); for (i = 0; i < nSelectors; i++) { j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (char) j; } /* Undo the MTF values for the selectors. */ { char[] pos = new char[BZip2Constants.N_GROUPS]; char tmp, v; for (v = '\0'; v < nGroups; v++) { pos[v] = v; } for (i = 0; i < nSelectors; i++) { v = selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } } /* Now the coding tables */ for (t = 0; t < nGroups; t++) { int curr = BsR(5); for (i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char) curr; } } /* Create the Huffman decoding tables */ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (len[t][i] > maxLen) { maxLen = len[t][i]; } if (len[t][i] < minLen) { minLen = len[t][i]; } } HbCreateDecodeTables(limit[t], basev[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { char[] yy = new char[256]; int i, j, nextSym, limitLast; int EOB, groupNo, groupPos; limitLast = BZip2Constants.baseBlockSize * blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); EOB = nInUse + 1; groupNo = -1; groupPos = 0; /* Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. */ for (i = 0; i <= 255; i++) { unzftab[i] = 0; } for (i = 0; i <= 255; i++) { yy[i] = (char) i; } last = -1; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) { char ch; int s = -1; int N = 1; do { if (nextSym == BZip2Constants.RUNA) { s = s + (0 + 1) * N; } else if (nextSym == BZip2Constants.RUNB) { s = s + (1 + 1) * N; } N = N * 2; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); s++; ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } continue; } else { char tmp; last++; if (last >= limitLast) { BlockOverrun(); } tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; /* This loop is hammered during decompression, hence the unrolling. for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1]; */ j = nextSym - 1; for (; j > 3; j -= 4) { yy[j] = yy[j - 1]; yy[j - 1] = yy[j - 2]; yy[j - 2] = yy[j - 3]; yy[j - 3] = yy[j - 4]; } for (; j > 0; j--) { yy[j] = yy[j - 1]; } yy[0] = tmp; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } continue; } } } private void SetupBlock() { int[] cftab = new int[257]; char ch; cftab[0] = 0; for (i = 1; i <= 256; i++) { cftab[i] = unzftab[i - 1]; } for (i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (i = 0; i <= last; i++) { ch = (char) ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } cftab = null; tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /* not a char and not EOF */ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= (int) ((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (char)((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } private void SetupRandPartC() { if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } private void SetupNoRandPartC() { if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { // throw new IOException("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } int n = BZip2Constants.baseBlockSize * newSize100k; ll8 = new char[n]; tt = new int[n]; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { int c = -1; int k; for (k = 0; k < count; ++k) { c = ReadByte(); if (c == -1) break; buffer[k + offset] = (byte)c; } return k; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using RimDev.Filter.Generic; using RimDev.Filter.Range.Generic; using Xunit; #if !NETCOREAPP2_1 namespace RimDev.Filter.Tests.Generic.Integration { public class EfTests : IClassFixture<DatabaseFixture> { private readonly DatabaseFixture fixture; public EfTests(DatabaseFixture databaseFixture) { fixture = databaseFixture; } private readonly IEnumerable<Person> People = new[] { new Person() { FavoriteDate = DateTime.Parse("2000-01-01"), FavoriteDateTimeOffset = DateTimeOffset.Parse("2010-01-01"), FavoriteLetter = 'a', FavoriteNumber = 5, FirstName = "John", LastName = "Doe" }, new Person() { FavoriteDate = DateTime.Parse("2000-01-02"), FavoriteDateTimeOffset = DateTimeOffset.Parse("2010-01-02"), FavoriteLetter = 'b', FavoriteNumber = 10, FirstName = "Tim", LastName = "Smith", Rating = 4.5m }, }; [Fact] public void Can_filter_nullable_models_via_entity_framework() { Database.SetInitializer(new DropCreateDatabaseAlways<FilterDbContext>()); using (var context = new FilterDbContext(fixture.ConnectionString)) using (var transaction = context.Database.BeginTransaction()) { context.People.AddRange(People); context.SaveChanges(); var @return = context.People.Filter(new { Rating = new decimal?(4.5m) }); Assert.Equal(1, @return.Count()); transaction.Rollback(); } } [Fact] public void Can_filter_datetimeoffset_via_entity_framework() { using (var context = new FilterDbContext(fixture.ConnectionString)) using (var transaction = context.Database.BeginTransaction()) { context.People.AddRange(People); context.SaveChanges(); var @return = context.People.Filter(new { FavoriteDateTimeOffset = (Range<DateTimeOffset>)"[2010-01-01,2010-01-02)" }); Assert.Equal(1, @return.Count()); transaction.Rollback(); } } [Fact] public void Should_be_able_to_handle_nullable_source() { using (var context = new FilterDbContext(fixture.ConnectionString)) using (var transaction = context.Database.BeginTransaction()) { context.People.AddRange(People); context.SaveChanges(); var @return = context.People.Filter(new { Rating = (Range<decimal>)"[4.5,5.0]" }); Assert.Equal(1, @return.Count()); transaction.Rollback(); } } [Fact] public void Should_not_optimize_arrays_containing_multiple_values() { var singleParameter = new { FirstName = "Tim" }; var collectionParameter = new { FirstName = new[] { "Tim", "John" } }; using (var context = new FilterDbContext(fixture.ConnectionString)) { IQueryable<Person> query = context.People.AsNoTracking(); var expectedQuery = query.Filter(singleParameter); var actualQuery = query.Filter(collectionParameter); Assert.NotEqual(expectedQuery.ToString(), actualQuery.ToString(), StringComparer.OrdinalIgnoreCase); } } [Fact] public void Should_optimize_arrays_containing_a_single_value() { var singleParameter = new { FirstName = "Tim" }; var collectionParameter = new { FirstName = new[] { "Tim" } }; using (var context = new FilterDbContext(fixture.ConnectionString)) { IQueryable<Person> query = context.People.AsNoTracking(); var expectedQuery = query.Where(x => x.FirstName == singleParameter.FirstName); var actualQuery = query.Filter(collectionParameter); Assert.Equal(expectedQuery.ToString(), actualQuery.ToString(), StringComparer.OrdinalIgnoreCase); } } [Fact] public void Should_not_optimize_collections_containing_multiple_values() { var singleParameter = new { FirstName = "Tim" }; var collectionParameter = new { FirstName = new List<string> { "Tim", "John" } }; using (var context = new FilterDbContext(fixture.ConnectionString)) { IQueryable<Person> query = context.People.AsNoTracking(); var expectedQuery = query.Filter(singleParameter); var actualQuery = query.Filter(collectionParameter); Assert.NotEqual(expectedQuery.ToString(), actualQuery.ToString(), StringComparer.OrdinalIgnoreCase); } } [Fact] public void Should_optimize_collections_containing_a_single_value() { var singleParameter = new { FirstName = "Tim" }; var collectionParameter = new { FirstName = new List<string> { "Tim" } }; using (var context = new FilterDbContext(fixture.ConnectionString)) { IQueryable<Person> query = context.People.AsNoTracking(); var expectedQuery = query.Filter(singleParameter); var actualQuery = query.Filter(collectionParameter); Assert.Equal(expectedQuery.ToString(), actualQuery.ToString(), StringComparer.OrdinalIgnoreCase); } } public sealed class FilterDbContext : DbContext { public FilterDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } public DbSet<Person> People { get; set; } } public class Person { public int Id { get; set; } public DateTime FavoriteDate { get; set; } public DateTimeOffset FavoriteDateTimeOffset { get; set; } public char FavoriteLetter { get; set; } public int FavoriteNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public decimal? Rating { get; set; } } } } #endif
using System; using Server; namespace Server.Items { public abstract class BaseLight : Item { private Timer m_Timer; private DateTime m_End; private bool m_BurntOut = false; private bool m_Burning = false; private bool m_Protected = false; private TimeSpan m_Duration = TimeSpan.Zero; public abstract int LitItemID{ get; } public virtual int UnlitItemID{ get { return 0; } } public virtual int BurntOutItemID{ get { return 0; } } public virtual int LitSound{ get { return 0x47; } } public virtual int UnlitSound{ get { return 0x3be; } } public virtual int BurntOutSound{ get { return 0x4b8; } } public static readonly bool Burnout = false; [CommandProperty( AccessLevel.GameMaster )] public bool Burning { get { return m_Burning; } set { if ( m_Burning != value ) { m_Burning = true; DoTimer( m_Duration ); } } } [CommandProperty( AccessLevel.GameMaster )] public bool BurntOut { get { return m_BurntOut; } set { m_BurntOut = value; } } [CommandProperty( AccessLevel.GameMaster )] public bool Protected { get { return m_Protected; } set { m_Protected = value; } } [CommandProperty( AccessLevel.GameMaster )] public TimeSpan Duration { get { if ( m_Duration != TimeSpan.Zero && m_Burning ) { return m_End - DateTime.Now; } else return m_Duration; } set { m_Duration = value; } } [Constructable] public BaseLight( int itemID ) : base( itemID ) { } public BaseLight( Serial serial ) : base( serial ) { } public virtual void PlayLitSound() { if ( LitSound != 0 ) { Point3D loc = GetWorldLocation(); Effects.PlaySound( loc, Map, LitSound ); } } public virtual void PlayUnlitSound() { int sound = UnlitSound; if ( m_BurntOut && BurntOutSound != 0 ) sound = BurntOutSound; if ( sound != 0 ) { Point3D loc = GetWorldLocation(); Effects.PlaySound( loc, Map, sound ); } } public virtual void Ignite() { if ( !m_BurntOut ) { PlayLitSound(); m_Burning = true; ItemID = LitItemID; DoTimer( m_Duration ); } } public virtual void Douse() { m_Burning = false; if ( m_BurntOut && BurntOutItemID != 0 ) ItemID = BurntOutItemID; else ItemID = UnlitItemID; if ( m_BurntOut ) m_Duration = TimeSpan.Zero; else if ( m_Duration != TimeSpan.Zero ) m_Duration = m_End - DateTime.Now; if ( m_Timer != null ) m_Timer.Stop(); PlayUnlitSound(); } public virtual void Burn() { m_BurntOut = true; Douse(); } private void DoTimer( TimeSpan delay ) { m_Duration = delay; if ( m_Timer != null ) m_Timer.Stop(); if ( delay == TimeSpan.Zero ) return; m_End = DateTime.Now + delay; m_Timer = new InternalTimer( this, delay ); m_Timer.Start(); } public override void OnDoubleClick( Mobile from ) { if ( m_BurntOut ) return; if ( m_Protected && from.AccessLevel == AccessLevel.Player ) return; if ( !from.InRange( this.GetWorldLocation(), 2 ) ) return; if ( m_Burning ) { if ( UnlitItemID != 0 ) Douse(); } else { Ignite(); } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); writer.Write( m_BurntOut ); writer.Write( m_Burning ); writer.Write( m_Duration ); writer.Write( m_Protected ); if ( m_Burning && m_Duration != TimeSpan.Zero ) writer.WriteDeltaTime( m_End ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); switch ( version ) { case 0: { m_BurntOut = reader.ReadBool(); m_Burning = reader.ReadBool(); m_Duration = reader.ReadTimeSpan(); m_Protected = reader.ReadBool(); if ( m_Burning && m_Duration != TimeSpan.Zero ) DoTimer( reader.ReadDeltaTime() - DateTime.Now ); break; } } } private class InternalTimer : Timer { private BaseLight m_Light; public InternalTimer( BaseLight light, TimeSpan delay ) : base( delay ) { m_Light = light; Priority = TimerPriority.FiveSeconds; } protected override void OnTick() { if ( m_Light != null && !m_Light.Deleted ) m_Light.Burn(); } } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; using System.Text; using System.Threading; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; using TheArtOfDev.HtmlRenderer.Core.Entities; using TheArtOfDev.HtmlRenderer.Core.Utils; namespace TheArtOfDev.HtmlRenderer.Core.Handlers { /// <summary> /// Handler for all loading image logic.<br/> /// <p> /// Loading by <see cref="HtmlImageLoadEventArgs"/>.<br/> /// Loading by file path.<br/> /// Loading by URI.<br/> /// </p> /// </summary> /// <remarks> /// <para> /// Supports sync and async image loading. /// </para> /// <para> /// If the image object is created by the handler on calling dispose of the handler the image will be released, this /// makes release of unused images faster as they can be large.<br/> /// Disposing image load handler will also cancel download of image from the web. /// </para> /// </remarks> internal sealed class ImageLoadHandler : IDisposable { #region Fields and Consts /// <summary> /// the container of the html to handle load image for /// </summary> private readonly HtmlContainerInt _htmlContainer; /// <summary> /// callback raised when image load process is complete with image or without /// </summary> private readonly ActionInt<RImage, RRect, bool> _loadCompleteCallback; /// <summary> /// the web client used to download image from URL (to cancel on dispose) /// </summary> private WebClient _client; /// <summary> /// Must be open as long as the image is in use /// </summary> private FileStream _imageFileStream; /// <summary> /// the image instance of the loaded image /// </summary> private RImage _image; /// <summary> /// the image rectangle restriction as returned from image load event /// </summary> private RRect _imageRectangle; /// <summary> /// to know if image load event callback was sync or async raised /// </summary> private bool _asyncCallback; /// <summary> /// flag to indicate if to release the image object on box dispose (only if image was loaded by the box) /// </summary> private bool _releaseImageObject; /// <summary> /// is the handler has been disposed /// </summary> private bool _disposed; #endregion /// <summary> /// Init. /// </summary> /// <param name="htmlContainer">the container of the html to handle load image for</param> /// <param name="loadCompleteCallback">callback raised when image load process is complete with image or without</param> public ImageLoadHandler(HtmlContainerInt htmlContainer, ActionInt<RImage, RRect, bool> loadCompleteCallback) { ArgChecker.AssertArgNotNull(htmlContainer, "htmlContainer"); ArgChecker.AssertArgNotNull(loadCompleteCallback, "loadCompleteCallback"); _htmlContainer = htmlContainer; _loadCompleteCallback = loadCompleteCallback; } /// <summary> /// the image instance of the loaded image /// </summary> public RImage Image { get { return _image; } } /// <summary> /// the image rectangle restriction as returned from image load event /// </summary> public RRect Rectangle { get { return _imageRectangle; } } /// <summary> /// Set image of this image box by analyzing the src attribute.<br/> /// Load the image from inline base64 encoded string.<br/> /// Or from calling property/method on the bridge object that returns image or URL to image.<br/> /// Or from file path<br/> /// Or from URI. /// </summary> /// <remarks> /// File path and URI image loading is executed async and after finishing calling <see cref="ImageLoadComplete"/> /// on the main thread and not thread-pool. /// </remarks> /// <param name="src">the source of the image to load</param> /// <param name="attributes">the collection of attributes on the element to use in event</param> /// <returns>the image object (null if failed)</returns> public void LoadImage(string src, Dictionary<string, string> attributes) { try { var args = new HtmlImageLoadEventArgs(src, attributes, OnHtmlImageLoadEventCallback); _htmlContainer.RaiseHtmlImageLoadEvent(args); _asyncCallback = !_htmlContainer.AvoidAsyncImagesLoading; if (!args.Handled) { if (!string.IsNullOrEmpty(src)) { if (src.StartsWith("data:image", StringComparison.CurrentCultureIgnoreCase)) { SetFromInlineData(src); } else { SetImageFromPath(src); } } else { ImageLoadComplete(false); } } } catch (Exception ex) { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Exception in handling image source", ex); ImageLoadComplete(false); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _disposed = true; ReleaseObjects(); } #region Private methods /// <summary> /// Set the image using callback from load image event, use the given data. /// </summary> /// <param name="path">the path to the image to load (file path or uri)</param> /// <param name="image">the image to load</param> /// <param name="imageRectangle">optional: limit to specific rectangle of the image and not all of it</param> private void OnHtmlImageLoadEventCallback(string path, object image, RRect imageRectangle) { if (!_disposed) { _imageRectangle = imageRectangle; if (image != null) { _image = _htmlContainer.Adapter.ConvertImage(image); ImageLoadComplete(_asyncCallback); } else if (!string.IsNullOrEmpty(path)) { SetImageFromPath(path); } else { ImageLoadComplete(_asyncCallback); } } } /// <summary> /// Load the image from inline base64 encoded string data. /// </summary> /// <param name="src">the source that has the base64 encoded image</param> private void SetFromInlineData(string src) { _image = GetImageFromData(src); if (_image == null) _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed extract image from inline data"); _releaseImageObject = true; ImageLoadComplete(false); } /// <summary> /// Extract image object from inline base64 encoded data in the src of the html img element. /// </summary> /// <param name="src">the source that has the base64 encoded image</param> /// <returns>image from base64 data string or null if failed</returns> private RImage GetImageFromData(string src) { var s = src.Substring(src.IndexOf(':') + 1).Split(new[] { ',' }, 2); if (s.Length == 2) { int imagePartsCount = 0, base64PartsCount = 0; foreach (var part in s[0].Split(new[] { ';' })) { var pPart = part.Trim(); if (pPart.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) imagePartsCount++; if (pPart.Equals("base64", StringComparison.InvariantCultureIgnoreCase)) base64PartsCount++; } if (imagePartsCount > 0) { byte[] imageData = base64PartsCount > 0 ? Convert.FromBase64String(s[1].Trim()) : new UTF8Encoding().GetBytes(Uri.UnescapeDataString(s[1].Trim())); return _htmlContainer.Adapter.ImageFromStream(new MemoryStream(imageData)); } } return null; } /// <summary> /// Load image from path of image file or URL. /// </summary> /// <param name="path">the file path or uri to load image from</param> private void SetImageFromPath(string path) { var uri = CommonUtils.TryGetUri(path); if (uri != null && uri.Scheme != "file") { SetImageFromUrl(uri); } else { var fileInfo = CommonUtils.TryGetFileInfo(uri != null ? uri.AbsolutePath : path); if (fileInfo != null) { SetImageFromFile(fileInfo); } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed load image, invalid source: " + path); ImageLoadComplete(false); } } } /// <summary> /// Load the image file on thread-pool thread and calling <see cref="ImageLoadComplete"/> after. /// </summary> /// <param name="source">the file path to get the image from</param> private void SetImageFromFile(FileInfo source) { if (source.Exists) { if (_htmlContainer.AvoidAsyncImagesLoading) LoadImageFromFile(source); else ThreadPool.QueueUserWorkItem(state => LoadImageFromFile(source)); } else { ImageLoadComplete(); } } /// <summary> /// Load the image file on thread-pool thread and calling <see cref="ImageLoadComplete"/> after.<br/> /// Calling <see cref="ImageLoadComplete"/> on the main thread and not thread-pool. /// </summary> /// <param name="source">the file path to get the image from</param> private void LoadImageFromFile(FileInfo source) { try { if (source.Exists) { _imageFileStream = File.Open(source.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _image = _htmlContainer.Adapter.ImageFromStream(_imageFileStream); _releaseImageObject = true; } ImageLoadComplete(); } catch (Exception ex) { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image from disk: " + source, ex); ImageLoadComplete(); } } /// <summary> /// Load image from the given URI by downloading it.<br/> /// Create local file name in temp folder from the URI, if the file already exists use it as it has already been downloaded. /// If not download the file using <see cref="DownloadImageFromUrlAsync"/>. /// </summary> private void SetImageFromUrl(Uri source) { var filePath = CommonUtils.GetLocalfileName(source); if (filePath.Exists && filePath.Length > 0) { SetImageFromFile(filePath); } else { if (_htmlContainer.AvoidAsyncImagesLoading) DownloadImageFromUrl(source, filePath); else ThreadPool.QueueUserWorkItem(DownloadImageFromUrlAsync, new KeyValuePair<Uri, FileInfo>(source, filePath)); } } /// <summary> /// Download the requested file in the URI to the given file path.<br/> /// Use async sockets API to download from web, <see cref="OnDownloadImageCompleted(object,System.ComponentModel.AsyncCompletedEventArgs)"/>. /// </summary> private void DownloadImageFromUrl(Uri source, FileInfo filePath) { try { using (var client = _client = new WebClient()) { client.DownloadFile(source, filePath.FullName); OnDownloadImageCompleted(false, null, filePath, client); } } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// Download the requested file in the URI to the given file path.<br/> /// Use async sockets API to download from web, <see cref="OnDownloadImageCompleted(object,System.ComponentModel.AsyncCompletedEventArgs)"/>. /// </summary> /// <param name="data">key value pair of URL and file info to download the file to</param> private void DownloadImageFromUrlAsync(object data) { var uri = ((KeyValuePair<Uri, FileInfo>)data).Key; var filePath = ((KeyValuePair<Uri, FileInfo>)data).Value; try { _client = new WebClient(); _client.DownloadFileCompleted += OnDownloadImageCompleted; _client.DownloadFileAsync(uri, filePath.FullName, filePath); } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// On download image complete to local file use <see cref="LoadImageFromFile"/> to load the image file.<br/> /// If the download canceled do nothing, if failed report error. /// </summary> private void OnDownloadImageCompleted(object sender, AsyncCompletedEventArgs e) { try { using (var client = (WebClient)sender) { client.DownloadFileCompleted -= OnDownloadImageCompleted; OnDownloadImageCompleted(e.Cancelled, e.Error, (FileInfo)e.UserState, client); } } catch (Exception ex) { OnDownloadImageCompleted(false, ex, null, null); } } /// <summary> /// On download image complete to local file use <see cref="LoadImageFromFile"/> to load the image file.<br/> /// If the download canceled do nothing, if failed report error. /// </summary> private void OnDownloadImageCompleted(bool cancelled, Exception error, FileInfo filePath, WebClient client) { if (!cancelled && !_disposed) { if (error == null) { filePath.Refresh(); var contentType = CommonUtils.GetResponseContentType(client); if (contentType != null && contentType.StartsWith("image", StringComparison.OrdinalIgnoreCase)) { LoadImageFromFile(filePath); } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image, not image content type: " + contentType); ImageLoadComplete(); filePath.Delete(); } } else { _htmlContainer.ReportError(HtmlRenderErrorType.Image, "Failed to load image from URL: " + client.BaseAddress, error); ImageLoadComplete(); } } } /// <summary> /// Flag image load complete and request refresh for re-layout and invalidate. /// </summary> private void ImageLoadComplete(bool async = true) { // can happen if some operation return after the handler was disposed if (_disposed) ReleaseObjects(); else _loadCompleteCallback(_image, _imageRectangle, async); } /// <summary> /// Release the image and client objects. /// </summary> private void ReleaseObjects() { if (_releaseImageObject && _image != null) { _image.Dispose(); _image = null; } if (_imageFileStream != null) { _imageFileStream.Dispose(); _imageFileStream = null; } if (_client != null) { _client.CancelAsync(); _client.Dispose(); _client = null; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Xamarin.Forms.Controls.TestCasesPages; using Xamarin.Forms.CustomAttributes; namespace Xamarin.Forms.Controls { public static class TestCases { public class TestCaseScreen : TableView { public static Dictionary<string, Action> PageToAction = new Dictionary<string, Action> (); static TextCell MakeIssueCell (string text, string detail, Action tapped) { PageToAction[text] = tapped; if (detail != null) PageToAction[detail] = tapped; var cell = new TextCell { Text = text, Detail = detail }; cell.Tapped += (s, e) => tapped(); return cell; } Action ActivatePageAndNavigate (IssueAttribute issueAttribute, Type type) { Action navigationAction = null; if (issueAttribute.NavigationBehavior == NavigationBehavior.PushAsync) { return async () => { var page = ActivatePage (type); TrackOnInsights (page); await Navigation.PushAsync (page); }; } if (issueAttribute.NavigationBehavior == NavigationBehavior.PushModalAsync) { return async () => { var page = ActivatePage (type); TrackOnInsights (page); await Navigation.PushModalAsync (page); }; } if (issueAttribute.NavigationBehavior == NavigationBehavior.Default) { return async () => { var page = ActivatePage (type); TrackOnInsights (page); if (page is ContentPage || page is CarouselPage) { await Navigation.PushAsync (page); } else { await Navigation.PushModalAsync (page); } }; } if (issueAttribute.NavigationBehavior == NavigationBehavior.SetApplicationRoot) { return () => { var page = ActivatePage (type); TrackOnInsights (page); Application.Current.MainPage = page; }; } return navigationAction; } static void TrackOnInsights (Page page) { if (Insights.IsInitialized) { Insights.Track ("Navigation", new Dictionary<string, string> { { "Pushing", page.GetType ().Name } }); } } Page ActivatePage (Type type) { var page = Activator.CreateInstance (type) as Page; if (page == null) { throw new InvalidCastException ("Issue must be of type Page"); } return page; } public TestCaseScreen () { AutomationId = "TestCasesIssueList"; Intent = TableIntent.Settings; var assembly = typeof (TestCases).GetTypeInfo ().Assembly; var issueModels = from typeInfo in assembly.DefinedTypes.Select (o => o.AsType ().GetTypeInfo ()) where typeInfo.GetCustomAttribute<IssueAttribute> () != null let attribute = (IssueAttribute)typeInfo.GetCustomAttribute<IssueAttribute> () select new { IssueTracker = attribute.IssueTracker, IssueNumber = attribute.IssueNumber, Name = attribute.IssueTracker.ToString ().Substring(0, 1) + attribute.IssueNumber.ToString (), Description = attribute.Description, Action = ActivatePageAndNavigate (attribute, typeInfo.AsType ()) }; var root = new TableRoot (); var section = new TableSection ("Bug Repro"); root.Add (section); var duplicates = new HashSet<string> (); issueModels.ForEach (im => { if (duplicates.Contains (im.Name) && !IsExempt (im.Name)) { throw new NotSupportedException ("Please provide unique tracker + issue number combo: " + im.IssueTracker.ToString () + im.IssueNumber.ToString ()); } else { duplicates.Add (im.Name); } }); var githubIssueCells = from issueModel in issueModels where issueModel.IssueTracker == IssueTracker.Github orderby issueModel.IssueNumber descending select MakeIssueCell (issueModel.Name, issueModel.Description, issueModel.Action); var bugzillaIssueCells = from issueModel in issueModels where issueModel.IssueTracker == IssueTracker.Bugzilla orderby issueModel.IssueNumber descending select MakeIssueCell (issueModel.Name, issueModel.Description, issueModel.Action); var untrackedIssueCells = from issueModel in issueModels where issueModel.IssueTracker == IssueTracker.None orderby issueModel.Description select MakeIssueCell (issueModel.Name, issueModel.Description, issueModel.Action); var issueCells = bugzillaIssueCells.Concat (githubIssueCells).Concat (untrackedIssueCells); foreach (var issueCell in issueCells) { section.Add (issueCell); } Root = root; } // Legacy reasons, do not add to this list // Going forward, make sure only one Issue attribute exist for a Tracker + Issue number pair bool IsExempt (string name) { if (name == "G1461" || name == "G342" || name == "G1305" || name == "G1653" || name == "N0") return true; else return false; } } public static NavigationPage GetTestCases () { var rootLayout = new StackLayout (); var testCasesRoot = new ContentPage { Title = "Bug Repro's", Content = rootLayout }; var searchBar = new SearchBar() { AutomationId = "SearchBarGo" }; var searchButton = new Button () { Text = "Search And Go To Issue", AutomationId = "SearchButton", Command = new Command (() => { try { TestCaseScreen.PageToAction[searchBar.Text] (); } catch (Exception e) { System.Diagnostics.Debug.WriteLine (e.Message); } }) }; var leaveTestCasesButton = new Button { AutomationId = "GoBackToGalleriesButton", Text = "Go Back to Galleries", Command = new Command (() => testCasesRoot.Navigation.PopModalAsync ()) }; rootLayout.Children.Add (leaveTestCasesButton); rootLayout.Children.Add (searchBar); rootLayout.Children.Add (searchButton); rootLayout.Children.Add (new TestCaseScreen ()); return new NavigationPage (testCasesRoot) { Title = Device.OnPlatform ("Test Cases", "Test Cases", "Tests") }; } } }
using System; using Foundation; using CoreGraphics; using UIKit; using CoreAnimation; namespace JVMenuPopover { /// <summary> /// JVMenuHelper /// </summary> public class JVMenuHelper : NSObject { public static CGSize GetScreenSize() { CGSize screenSize = UIScreen.MainScreen.Bounds.Size; // if ((NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1) && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) // return CGSizeMake(screenSize.height, screenSize.width); return screenSize; } /// <summary> /// Images the with image. /// </summary> /// <returns>The with image.</returns> /// <param name="sourceImage">Source image.</param> /// <param name="i_width">I width.</param> public static UIImage ImageWithImage(UIImage sourceImage, Double i_width) { var oldWidth = sourceImage.Size.Width; var scaleFactor = i_width / oldWidth; var newHeight = sourceImage.Size.Height * scaleFactor; var newWidth = oldWidth * scaleFactor; UIGraphics.BeginImageContext(new CGSize(newWidth, newHeight)); sourceImage.Draw(new CGRect(0, 0, newWidth, newHeight)); var newImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return newImage; } /// <summary> /// Colors the with hex string. /// </summary> /// <returns>The with hex string.</returns> /// <param name="hexValue">Hex value.</param> /// <param name="alpha">Alpha.</param> public static UIColor ColorWithHexString (string hexValue, float alpha = 1.0f) { var colorString = hexValue.Replace ("#", ""); if (alpha > 1.0f) { alpha = 1.0f; } else if (alpha < 0.0f) { alpha = 0.0f; } float red, green, blue; switch (colorString.Length) { case 3 : // #RGB { red = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(0, 1)), 16) / 255f; green = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(1, 1)), 16) / 255f; blue = Convert.ToInt32(string.Format("{0}{0}", colorString.Substring(2, 1)), 16) / 255f; return UIColor.FromRGBA(red, green, blue, alpha); } case 6 : // #RRGGBB { red = Convert.ToInt32(colorString.Substring(0, 2), 16) / 255f; green = Convert.ToInt32(colorString.Substring(2, 2), 16) / 255f; blue = Convert.ToInt32(colorString.Substring(4, 2), 16) / 255f; return UIColor.FromRGBA(red, green, blue, alpha); } default : throw new ArgumentOutOfRangeException(string.Format("Invalid color value {0} is invalid. It should be a hex value of the form #RBG, #RRGGBB", hexValue)); } } /// <summary> /// Colors the with RGB hex. /// </summary> /// <returns>The with RGB hex.</returns> /// <param name="hex">Hex.</param> public static UIColor ColorWithRGBHex(UInt32 hex) { //converts a hex number into a colour var r = (hex >> 16) & 0xFF; var g = (hex >> 8) & 0xFF; var b = (hex) & 0xFF; return UIColor.FromRGBA(r / 255.0f, g / 255.0f, b / 255.0f, 1.0f); } /// <summary> /// Removes the layer from view. /// </summary> /// <param name="view">View.</param> public static void RemoveLayerFromView(UIView view) { CAGradientLayer layerToRemove = null; foreach (CALayer aLayer in view.Layer.Sublayers) { if (aLayer is CAGradientLayer) { layerToRemove = (CAGradientLayer)aLayer; } } if (layerToRemove != null) layerToRemove.RemoveFromSuperLayer(); } /// <summary> /// Tops the view controller. /// </summary> /// <returns>The view controller.</returns> public static UIViewController TopViewController() { return TopViewController(UIApplication.SharedApplication.KeyWindow.RootViewController); } /// <summary> /// Tops the view controller. /// </summary> /// <returns>The view controller.</returns> /// <param name="rootViewController">Root view controller.</param> public static UIViewController TopViewController(UIViewController rootViewController) { if (rootViewController.PresentedViewController == null) return rootViewController; if (rootViewController.PresentedViewController is UINavigationController) { var navigationController = (UINavigationController)rootViewController.PresentedViewController; var lastViewController = navigationController.ViewControllers[navigationController.ViewControllers.Length-1]; return TopViewController(lastViewController); } var presentedViewController = (UIViewController)rootViewController.PresentedViewController; return TopViewController(presentedViewController); } /// <summary> /// Takes the screen shot of view. /// </summary> /// <returns>The screen shot of view.</returns> /// <param name="view">View.</param> /// <param name="updated">If set to <c>true</c> updated.</param> public static UIImage TakeScreenShotOfView(UIView view, Boolean updated) { UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, UIScreen.MainScreen.Scale); view.DrawViewHierarchy(view.Bounds,updated); UIImage image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return image; } /// <summary> /// Changes the color of the image. /// </summary> /// <returns>The image color.</returns> /// <param name="img">Image.</param> /// <param name="color">Color.</param> public static UIImage ChangeImageColor(UIImage img, UIColor color) { if (color != null) { UIGraphics.BeginImageContextWithOptions(img.Size, false, (nfloat)img.CurrentScale); var context = UIGraphics.GetCurrentContext(); context.TranslateCTM(0, img.Size.Height); context.ScaleCTM(1.0f, -1.0f); context.SetBlendMode(CGBlendMode.Normal); CGRect rect = new CGRect(0, 0, img.Size.Width, img.Size.Height); context.ClipToMask(rect,img.CGImage); color.SetFill(); context.FillRect(rect); UIImage newImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return newImage; } return img; } /// <summary> /// Images the with image. /// </summary> /// <returns>The with image.</returns> /// <param name="image">Image.</param> /// <param name="size">Size.</param> public static UIImage ImageWithImage(UIImage image, CGSize size) { UIGraphics.BeginImageContext(size); image.Draw(new CGRect(0, 0, size.Width, size.Height)); var destImage = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return destImage; } /// <summary> /// Applies the blurr with efftect style. /// </summary> /// <returns>The blurr with efftect style.</returns> /// <param name="style">Style.</param> /// <param name="frame">Frame.</param> public static UIVisualEffectView ApplyBlurrWithEfftectStyle(UIBlurEffectStyle style, CGRect frame) { //only apply the blur if the user hasn't disabled transparency effects if(!UIAccessibility.IsReduceTransparencyEnabled) { var blurEffect = UIBlurEffect.FromStyle(style); var blurEffectView = new UIVisualEffectView(blurEffect); blurEffectView.Alpha = 0.6f; blurEffectView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; blurEffectView.Frame = frame; return blurEffectView; } else { // ios 7 implementation } return null; } } }
// 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.SafeHandles; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedFile.CreateNew. /// </summary> public class MemoryMappedFileTests_CreateNew : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateNew mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { // Empty string is an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateNew(string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew capacity parameter. /// </summary> [Theory] [InlineData(0)] // default size is invalid with CreateNew as there's nothing to expand to match [InlineData(-100)] // negative values don't make sense public void InvalidArguments_Capacity(int capacity) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew access parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileAccess)42)] [InlineData((MemoryMappedFileAccess)(-2))] public void InvalidArguments_Access(MemoryMappedFileAccess access) { // Out of range values Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access)); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateNew(null, 4096, access, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew access parameter, specifically MemoryMappedFileAccess.Write. /// </summary> [Fact] public void InvalidArguments_WriteAccess() { // Write-only access isn't allowed, as it'd be useless Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Write)); } /// <summary> /// Tests invalid arguments to the CreateNew options parameter. /// </summary> [Theory] [InlineData((MemoryMappedFileOptions)42)] [InlineData((MemoryMappedFileOptions)(-2))] public void InvalidArguments_Options(MemoryMappedFileOptions options) { Assert.Throws<ArgumentOutOfRangeException>("options", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, options, HandleInheritability.None)); } /// <summary> /// Tests invalid arguments to the CreateNew inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)42)] [InlineData((HandleInheritability)(-2))] public void InvalidArguments_Inheritability(HandleInheritability inheritability) { Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateNew(null, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, inheritability)); } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // On Windows, too large capacity fails during CreateNew call [Fact] public void TooLargeCapacity_Windows() { if (IntPtr.Size == 4) { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateNew(null, 1 + (long)uint.MaxValue)); } else { Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(null, long.MaxValue)); } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately) [Fact] public void TooLargeCapacity_Unix() { // On Windows we fail with too large a capacity as part of the CreateNew call. // On Unix that exception may happen a bit later, as part of creating the view, // due to differences in OS behaviors and Unix not actually having a notion of // a view separate from a map. It could also come from CreateNew, depending // on what backing store is being used. Assert.Throws<IOException>(() => { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, (IntPtr.Size == 4) ? uint.MaxValue : long.MaxValue)) { mmf.CreateViewAccessor().Dispose(); } }); } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateNew(mapName, 4096, MemoryMappedFileAccess.Read, MemoryMappedFileOptions.None, HandleInheritability.None)); } /// <summary> /// Test to verify a variety of map names work correctly on Windows. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names are unsupported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] [InlineData(null)] public void ValidMapNames_Windows(string name) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.Read)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.Read); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.DelayAllocatePages, HandleInheritability.Inheritable)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable); } } /// <summary> /// Test to verify map names are handled appropriately, causing a conflict when they're active but /// reusable in a sequential manner. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows [Theory] [MemberData(nameof(CreateValidMapNames))] public void ReusingNames_Windows(string name) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096); Assert.Throws<IOException>(() => MemoryMappedFile.CreateNew(name, 4096)); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) { ValidateMemoryMappedFile(mmf, 4096, MemoryMappedFileAccess.ReadWrite); } } /// <summary> /// Test various combinations of arguments to CreateNew, validating the created maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinations), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite }, new MemoryMappedFileOptions[] { MemoryMappedFileOptions.None, MemoryMappedFileOptions.DelayAllocatePages }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable })] public void ValidArgumentCombinations( string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, HandleInheritability inheritability) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(mapName, capacity, access, options, inheritability)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } } /// <summary> /// Provides input data to the ValidArgumentCombinations tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses">The accesses to yield</param> /// <param name="options">The options to yield.</param> /// <param name="inheritabilities">The inheritabilities to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinations( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, MemoryMappedFileOptions[] options, HandleInheritability[] inheritabilities) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (MemoryMappedFileOptions option in options) { foreach (HandleInheritability inheritability in inheritabilities) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, option, inheritability }; } } } } } } /// <summary> /// Test to verify that two unrelated maps don't share data. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Map names are unsupported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] [InlineData(null)] public void DataNotPersistedBetweenMaps_Windows(string name) { // Write some data to a map newly created with the specified name using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Write(0, 42); } // After it's closed, open a map with the same name again and verify the data's gone using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(name, 4096)) using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { // Data written to previous map should not be here Assert.Equal(0, accessor.ReadByte(0)); } } /// <summary> /// Test to verify that two unrelated maps don't share data. /// </summary> [Fact] public void DataNotPersistedBetweenMaps_Unix() { // same as the Windows test, but for Unix we only validate null, as other names aren't allowed DataNotPersistedBetweenMaps_Windows(null); } /// <summary> /// Test to verify that we can have many maps open at the same time. /// </summary> [Fact] public void ManyConcurrentMaps() { const int NumMaps = 100, Capacity = 4096; var mmfs = new List<MemoryMappedFile>(Enumerable.Range(0, NumMaps).Select(_ => MemoryMappedFile.CreateNew(null, Capacity))); try { mmfs.ForEach(mmf => ValidateMemoryMappedFile(mmf, Capacity)); } finally { mmfs.ForEach(mmf => mmf.Dispose()); } } /// <summary> /// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Usable capacity limits with MMF APIs different on Windows and Unix [Fact] public void RoundedUpCapacity_Windows() { // On both Windows and Unix, capacity is rounded up to the nearest page size. However, // the amount of capacity actually usable by the developer is supposed to be limited // to that specified. That's not currently the case with the MMF APIs on Windows; // it is the case on Unix. const int CapacityLessThanPageSize = 1; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor()) { Assert.Equal(s_pageSize.Value, acc.Capacity); } } /// <summary> /// Test to verify expected capacity with regards to page size and automatically rounding up to the nearest. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // Usable capacity limits with MMF APIs different on Windows and Unix [Fact] public void RoundedUpCapacity_Unix() { // The capacity of the view should match the capacity specified when creating the map, // even though under the covers the map's capacity is rounded up to the nearest page size. const int CapacityLessThanPageSize = 1; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, CapacityLessThanPageSize)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor()) { Assert.Equal(CapacityLessThanPageSize, acc.Capacity); } } /// <summary> /// Test to verify we can dispose of a map multiple times. /// </summary> [Fact] public void DoubleDispose() { MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); mmf.Dispose(); mmf.Dispose(); } /// <summary> /// Test to verify we can't create new views after the map has been disposed. /// </summary> [Fact] public void UnusableAfterDispose() { MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); SafeMemoryMappedFileHandle handle = mmf.SafeMemoryMappedFileHandle; Assert.False(handle.IsClosed); mmf.Dispose(); Assert.True(handle.IsClosed); Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewAccessor()); Assert.Throws<ObjectDisposedException>(() => mmf.CreateViewStream()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; //using xVal.ServerSide; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace iServe.Models.dotNailsCommon { [DataContract(IsReference=true)] public class LinqEntityBase<EntityType, DataContextType> : IEntity where EntityType : LinqEntityBase<EntityType, DataContextType>, new() where DataContextType : System.Data.Linq.DataContext { private EntityStateEnum _entityState = EntityStateEnum.DefaultLinqToSql; public EntityStateEnum EntityState { get { return _entityState; } set { _entityState = value; } } public int? CurrentUserID { get; set; } internal bool IsSaveInProgress { get; set; } internal bool IsMappingForeignKeys { get; set; } //protected int? UserID { // get { // int? userID = null; // System.Security.Principal.IPrincipal principal = System.Threading.Thread.CurrentPrincipal; // if (principal != null) { // IdotNailsIdentity identity = principal.Identity as IdotNailsIdentity; // if (identity != null) { // userID = identity.ID; // } // } // return userID; // } //} protected DataContextType _db; #region Extensibility Method Definitions protected virtual void ValidateBusinessRules() { } #endregion public virtual void SetDataContext(System.Data.Linq.DataContext dataContext) { DataContextType db = dataContext as DataContextType; if (dataContext != null) { _db = db; } else { throw new Exception("SetDataContext(dataContext) for " + typeof(EntityType) + " did not receive parameter of type " + typeof(DataContextType)); } } public virtual IEntity Save() { return Save(null, null); } public virtual IEntity Save(System.Data.Linq.DataContext dataContext) { return Save(null, dataContext); } public virtual IEntity Save(IEntity parent, System.Data.Linq.DataContext dataContext) { //var errors = DataAnnotationsValidationRunner.GetErrors(this); //if (errors.Any()) // throw new RulesException(errors); // Extensibility hook for derived classes //ValidateBusinessRules(); IEntity topMostParent = parent ?? this; if (dataContext != null) { _db = dataContext as DataContextType; } if (EntityState == EntityStateEnum.DefaultLinqToSql && topMostParent == this) { // Nothing fancy, just let Linq to Sql do its thing _db.SubmitChanges(); return null; } else { // Do our dotNails thing EntityType clone = null; IsSaveInProgress = true; DetermineEntityState(); IAuditable auditableEntity = this as IAuditable; // Handle this current entity switch (EntityState) { case EntityStateEnum.Added: case EntityStateEnum.DefaultLinqToSql: // this can occur for ManyToMany tables (always treat them as Added) if (auditableEntity != null) { auditableEntity.AuditForCreate(CurrentUserID); } clone = InsertEntity(topMostParent) as EntityType; break; case EntityStateEnum.Modified: if (auditableEntity != null) { auditableEntity.AuditForUpdate(CurrentUserID); } clone = UpdateEntity(topMostParent) as EntityType; break; case EntityStateEnum.Deleted: clone = DeleteEntity(topMostParent) as EntityType; break; case EntityStateEnum.Destroyed: clone = DestroyEntity(topMostParent) as EntityType; break; case EntityStateEnum.UnModified: // While we don't have anything to perform on this entity, we may need to mess with his children clone = UnModifiedEntity(topMostParent) as EntityType; break; } if (parent == null) { // We're the entity with the originating request to save, so submit all the changes on the datacontext try { _db.SubmitChanges(); MapChildForeignKeys(); } catch (Exception ex) { throw (ex); } } IsSaveInProgress = false; return clone; } } public virtual EntityType GetSerializableObject() { return Clone(EntityStateEnum.NotSet); } // HACK: This exists because of a troubling mystery with LinqToSql. When a hierarchy of objects gets inserted, the children's foreign key propertyID that points // to their parent EntityRef somehow magically gets set by LinqToSql without calling the property setter for that property!!!! Honest to God, I have no idea how // this is even possible in C#. The underlying variables are private and there's no constructor that I know of that can set them. The result is that our facing // objects never get notified that their clones have new IDs on those properties. The clones have the foreign key set, but the facing objects never hear about it. // This method is a hack for all children to make sure they have the newly inserted IDs of their parents. public virtual void MapChildForeignKeys() { } protected virtual IEntity InsertEntity(IEntity parent) { throw new NotImplementedException(); } protected virtual IEntity UpdateEntity(IEntity parent) { throw new NotImplementedException(); } protected virtual IEntity DeleteEntity(IEntity parent) { throw new NotImplementedException(); } protected virtual IEntity DestroyEntity(IEntity parent) { throw new NotImplementedException(); } protected virtual IEntity UnModifiedEntity(IEntity parent) { throw new NotImplementedException(); } public EntityType Clone() { return Clone(EntityStateEnum.Added); } public virtual EntityType Clone(EntityStateEnum entityState) { throw new NotImplementedException(); } public EntityType ClonePrimaryKeyOnly() { return ClonePrimaryKeyOnly(EntityStateEnum.Modified); } public virtual EntityType ClonePrimaryKeyOnly(EntityStateEnum entityState) { throw new NotImplementedException(); } protected virtual void DetermineEntityState() { throw new NotImplementedException(); } } //internal static class DataAnnotationsValidationRunner { // public static IEnumerable<ErrorInfo> GetErrors(object instance) { // List<ErrorInfo> errors = new List<ErrorInfo>(); // IEnumerable<PropertyDescriptor> properties = TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>(); // foreach (PropertyDescriptor prop in properties) { // IEnumerable<ValidationAttribute> attributes = prop.Attributes.OfType<ValidationAttribute>(); // foreach (ValidationAttribute attribute in attributes) { // if (!attribute.IsValid(prop.GetValue(instance))) { // errors.Add(new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance)); // } // } // } // return errors; // //return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>() // // from attribute in prop.Attributes.OfType<ValidationAttribute>() // // where !attribute.IsValid(prop.GetValue(instance)) // // select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance); // } //} }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Remotion.Linq.Clauses.ExpressionTreeVisitors; using Remotion.Linq.Parsing.ExpressionTreeVisitors; using Remotion.Linq.Parsing.ExpressionTreeVisitors.Transformation; using Remotion.Linq.Parsing.Structure.ExpressionTreeProcessors; using Remotion.Linq.Parsing.Structure.IntermediateModel; using Remotion.Linq.Parsing.Structure.NodeTypeProviders; namespace Remotion.Linq.Parsing.Structure { /// <summary> /// Parses an expression tree into a chain of <see cref="IExpressionNode"/> objects after executing a sequence of /// <see cref="IExpressionTreeProcessor"/> objects. /// </summary> public sealed class ExpressionTreeParser { private static readonly MethodInfo s_getArrayLengthMethod = typeof(Array).GetProperty("Length").GetGetMethod(); /// <summary> /// Creates a default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly /// registered. Users can add inner providers to register their own expression node parsers. /// </summary> /// <returns>A default <see cref="CompoundNodeTypeProvider"/> that already has all expression node parser defined by the re-linq assembly /// registered.</returns> public static CompoundNodeTypeProvider CreateDefaultNodeTypeProvider() { var searchedTypes = typeof(MethodInfoBasedNodeTypeRegistry).Assembly.GetTypes(); var innerProviders = new INodeTypeProvider[] { MethodInfoBasedNodeTypeRegistry.CreateFromTypes (searchedTypes), MethodNameBasedNodeTypeRegistry.CreateFromTypes(searchedTypes) }; return new CompoundNodeTypeProvider(innerProviders); } /// <summary> /// Creates a default <see cref="CompoundExpressionTreeProcessor"/> that already has the expression tree processing steps defined by the re-linq assembly /// registered. Users can insert additional processing steps. /// </summary> /// <param name="tranformationProvider">The tranformation provider to be used by the <see cref="TransformingExpressionTreeProcessor"/> included /// in the result set. Use <see cref="ExpressionTransformerRegistry.CreateDefault"/> to create a default provider.</param> /// <returns> /// A default <see cref="CompoundExpressionTreeProcessor"/> that already has all expression tree processing steps defined by the re-linq assembly /// registered. /// </returns> /// <remarks> /// The following steps are included: /// <list type="bullet"> /// <item><see cref="PartialEvaluatingExpressionTreeProcessor"/></item> /// <item><see cref="TransformingExpressionTreeProcessor"/> (parameterized with <paramref name="tranformationProvider"/>)</item> /// </list> /// </remarks> public static CompoundExpressionTreeProcessor CreateDefaultProcessor(IExpressionTranformationProvider tranformationProvider) { return new CompoundExpressionTreeProcessor(new IExpressionTreeProcessor[] { new PartialEvaluatingExpressionTreeProcessor(), new TransformingExpressionTreeProcessor (tranformationProvider) }); } private readonly UniqueIdentifierGenerator _identifierGenerator = new UniqueIdentifierGenerator(); private readonly INodeTypeProvider _nodeTypeProvider; private readonly IExpressionTreeProcessor _processor; private readonly MethodCallExpressionParser _methodCallExpressionParser; /// <summary> /// Initializes a new instance of the <see cref="ExpressionTreeParser"/> class with a custom <see cref="INodeTypeProvider"/> and /// <see cref="IExpressionTreeProcessor"/> implementation. /// </summary> /// <param name="nodeTypeProvider">The <see cref="INodeTypeProvider"/> to use when parsing <see cref="Expression"/> trees. Use /// <see cref="CreateDefaultNodeTypeProvider"/> to create an instance of <see cref="CompoundNodeTypeProvider"/> that already includes all /// default node types. (The <see cref="CompoundNodeTypeProvider"/> can be customized as needed by adding or removing /// <see cref="CompoundNodeTypeProvider.InnerProviders"/>).</param> /// <param name="processor">The <see cref="IExpressionTreeProcessor"/> to apply to <see cref="Expression"/> trees before parsing their nodes. Use /// <see cref="CreateDefaultProcessor"/> to create an instance of <see cref="CompoundExpressionTreeProcessor"/> that already includes /// the default steps. (The <see cref="CompoundExpressionTreeProcessor"/> can be customized as needed by adding or removing /// <see cref="CompoundExpressionTreeProcessor.InnerProcessors"/>).</param> public ExpressionTreeParser(INodeTypeProvider nodeTypeProvider, IExpressionTreeProcessor processor) { _nodeTypeProvider = nodeTypeProvider; _processor = processor; _methodCallExpressionParser = new MethodCallExpressionParser(_nodeTypeProvider); } /// <summary> /// Gets the node type provider used to parse <see cref="MethodCallExpression"/> instances in <see cref="ParseTree"/>. /// </summary> /// <value>The node type provider.</value> public INodeTypeProvider NodeTypeProvider { get { return _nodeTypeProvider; } } /// <summary> /// Gets the processing steps used by <see cref="ParseTree"/> to process the <see cref="Expression"/> tree before analyzing its structure. /// </summary> /// <value>The processing steps.</value> public IExpressionTreeProcessor Processor { get { return _processor; } } /// <summary> /// Parses the given <paramref name="expressionTree"/> into a chain of <see cref="IExpressionNode"/> instances, using /// <see cref="MethodInfoBasedNodeTypeRegistry"/> to convert expressions to nodes. /// </summary> /// <param name="expressionTree">The expression tree to parse.</param> /// <returns>A chain of <see cref="IExpressionNode"/> instances representing the <paramref name="expressionTree"/>.</returns> public IExpressionNode ParseTree(Expression expressionTree) { if (expressionTree.Type == typeof(void)) { throw new NotSupportedException( string.Format("Expressions of type void ('{0}') are not supported.", FormattingExpressionTreeVisitor.Format(expressionTree))); } var processedExpressionTree = _processor.Process(expressionTree); return ParseNode(processedExpressionTree, null); } /// <summary> /// Gets the query operator <see cref="MethodCallExpression"/> represented by <paramref name="expression"/>. If <paramref name="expression"/> /// is already a <see cref="MethodCallExpression"/>, that is the assumed query operator. If <paramref name="expression"/> is a /// <see cref="MemberExpression"/> and the member's getter is registered with <see cref="NodeTypeProvider"/>, a corresponding /// <see cref="MethodCallExpression"/> is constructed and returned. Otherwise, <see langword="null" /> is returned. /// </summary> /// <param name="expression">The expression to get a query operator expression for.</param> /// <returns>A <see cref="MethodCallExpression"/> to be parsed as a query operator, or <see langword="null"/> if the expression does not represent /// a query operator.</returns> public MethodCallExpression GetQueryOperatorExpression(Expression expression) { var methodCallExpression = expression as MethodCallExpression; if (methodCallExpression != null) return methodCallExpression; var memberExpression = expression as MemberExpression; if (memberExpression != null) { var propertyInfo = memberExpression.Member as PropertyInfo; if (propertyInfo == null) return null; var getterMethod = propertyInfo.GetGetMethod(); if (getterMethod == null || !_nodeTypeProvider.IsRegistered(getterMethod)) return null; return Expression.Call(memberExpression.Expression, getterMethod); } var unaryExpression = expression as UnaryExpression; if (unaryExpression != null) { if (unaryExpression.NodeType == ExpressionType.ArrayLength && _nodeTypeProvider.IsRegistered(s_getArrayLengthMethod)) return Expression.Call(unaryExpression.Operand, s_getArrayLengthMethod); } return null; } private IExpressionNode ParseNode(Expression expression, string associatedIdentifier) { if (string.IsNullOrEmpty(associatedIdentifier)) associatedIdentifier = _identifierGenerator.GetUniqueIdentifier("<generated>_"); var methodCallExpression = GetQueryOperatorExpression(expression); if (methodCallExpression != null) return ParseMethodCallExpression(methodCallExpression, associatedIdentifier); else return ParseNonQueryOperatorExpression(expression, associatedIdentifier); } private IExpressionNode ParseMethodCallExpression(MethodCallExpression methodCallExpression, string associatedIdentifier) { string associatedIdentifierForSource = InferAssociatedIdentifierForSource(methodCallExpression); Expression sourceExpression; IEnumerable<Expression> arguments; if (methodCallExpression.Object != null) { sourceExpression = methodCallExpression.Object; arguments = methodCallExpression.Arguments; } else { sourceExpression = methodCallExpression.Arguments[0]; arguments = methodCallExpression.Arguments.Skip(1); } var source = ParseNode(sourceExpression, associatedIdentifierForSource); return _methodCallExpressionParser.Parse(associatedIdentifier, source, arguments, methodCallExpression); } private IExpressionNode ParseNonQueryOperatorExpression(Expression expression, string associatedIdentifier) { var preprocessedExpression = SubQueryFindingExpressionTreeVisitor.Process(expression, _nodeTypeProvider); try { return new MainSourceExpressionNode(associatedIdentifier, preprocessedExpression); } catch (ArgumentException ex) { var message = string.Format( "Cannot parse expression '{0}' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) " + "and query operators can be parsed.", FormattingExpressionTreeVisitor.Format(preprocessedExpression)); throw new NotSupportedException(message, ex); } } /// <summary> /// Infers the associated identifier for the source expression node contained in methodCallExpression.Arguments[0]. For example, for the /// call chain "<c>source.Where (i => i > 5)</c>" (which actually reads "<c>Where (source, i => i > 5</c>"), the identifier "i" is associated /// with the node generated for "source". If no identifier can be inferred, <see langword="null"/> is returned. /// </summary> private string InferAssociatedIdentifierForSource(MethodCallExpression methodCallExpression) { var lambdaExpression = GetLambdaArgument(methodCallExpression); if (lambdaExpression != null && lambdaExpression.Parameters.Count == 1) return lambdaExpression.Parameters[0].Name; else return null; } private LambdaExpression GetLambdaArgument(MethodCallExpression methodCallExpression) { return methodCallExpression.Arguments .Select(argument => GetLambdaExpression(argument)) .FirstOrDefault(lambdaExpression => lambdaExpression != null); } private LambdaExpression GetLambdaExpression(Expression expression) { var lambdaExpression = expression as LambdaExpression; if (lambdaExpression != null) return lambdaExpression; else { var unaryExpression = expression as UnaryExpression; if (unaryExpression != null) return unaryExpression.Operand as LambdaExpression; else return null; } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // .NET Compact Framework has no support for WindowsIdentity #if !NETCF using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using log4net.Core; namespace log4net.Util { /// <summary> /// Impersonate a Windows Account /// </summary> /// <remarks> /// <para> /// This <see cref="SecurityContext"/> impersonates a Windows account. /// </para> /// <para> /// How the impersonation is done depends on the value of <see cref="Impersonate"/>. /// This allows the context to either impersonate a set of user credentials specified /// using username, domain name and password or to revert to the process credentials. /// </para> /// </remarks> public class WindowsSecurityContext : SecurityContext, IOptionHandler { /// <summary> /// The impersonation modes for the <see cref="WindowsSecurityContext"/> /// </summary> /// <remarks> /// <para> /// See the <see cref="WindowsSecurityContext.Credentials"/> property for /// details. /// </para> /// </remarks> public enum ImpersonationMode { /// <summary> /// Impersonate a user using the credentials supplied /// </summary> User, /// <summary> /// Revert this the thread to the credentials of the process /// </summary> Process } #region Member Variables private ImpersonationMode m_impersonationMode = ImpersonationMode.User; private string m_userName; private string m_domainName = Environment.MachineName; private string m_password; private WindowsIdentity m_identity; #endregion #region Constructor /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public WindowsSecurityContext() { } #endregion #region Public Properties /// <summary> /// Gets or sets the impersonation mode for this security context /// </summary> /// <value> /// The impersonation mode for this security context /// </value> /// <remarks> /// <para> /// Impersonate either a user with user credentials or /// revert this thread to the credentials of the process. /// The value is one of the <see cref="ImpersonationMode"/> /// enum. /// </para> /// <para> /// The default value is <see cref="ImpersonationMode.User"/> /// </para> /// <para> /// When the mode is set to <see cref="ImpersonationMode.User"/> /// the user's credentials are established using the /// <see cref="UserName"/>, <see cref="DomainName"/> and <see cref="Password"/> /// values. /// </para> /// <para> /// When the mode is set to <see cref="ImpersonationMode.Process"/> /// no other properties need to be set. If the calling thread is /// impersonating then it will be reverted back to the process credentials. /// </para> /// </remarks> public ImpersonationMode Credentials { get { return m_impersonationMode; } set { m_impersonationMode = value; } } /// <summary> /// Gets or sets the Windows username for this security context /// </summary> /// <value> /// The Windows username for this security context /// </value> /// <remarks> /// <para> /// This property must be set if <see cref="Credentials"/> /// is set to <see cref="ImpersonationMode.User"/> (the default setting). /// </para> /// </remarks> public string UserName { get { return m_userName; } set { m_userName = value; } } /// <summary> /// Gets or sets the Windows domain name for this security context /// </summary> /// <value> /// The Windows domain name for this security context /// </value> /// <remarks> /// <para> /// The default value for <see cref="DomainName"/> is the local machine name /// taken from the <see cref="Environment.MachineName"/> property. /// </para> /// <para> /// This property must be set if <see cref="Credentials"/> /// is set to <see cref="ImpersonationMode.User"/> (the default setting). /// </para> /// </remarks> public string DomainName { get { return m_domainName; } set { m_domainName = value; } } /// <summary> /// Sets the password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties. /// </summary> /// <value> /// The password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties. /// </value> /// <remarks> /// <para> /// This property must be set if <see cref="Credentials"/> /// is set to <see cref="ImpersonationMode.User"/> (the default setting). /// </para> /// </remarks> public string Password { set { m_password = value; } } #endregion #region IOptionHandler Members /// <summary> /// Initialize the SecurityContext based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// The security context will try to Logon the specified user account and /// capture a primary token for impersonation. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The required <see cref="UserName" />, /// <see cref="DomainName" /> or <see cref="Password" /> properties were not specified.</exception> public void ActivateOptions() { if (m_impersonationMode == ImpersonationMode.User) { if (m_userName == null) throw new ArgumentNullException("m_userName"); if (m_domainName == null) throw new ArgumentNullException("m_domainName"); if (m_password == null) throw new ArgumentNullException("m_password"); m_identity = LogonUser(m_userName, m_domainName, m_password); } } #endregion /// <summary> /// Impersonate the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties. /// </summary> /// <param name="state">caller provided state</param> /// <returns> /// An <see cref="IDisposable"/> instance that will revoke the impersonation of this SecurityContext /// </returns> /// <remarks> /// <para> /// Depending on the <see cref="Credentials"/> property either /// impersonate a user using credentials supplied or revert /// to the process credentials. /// </para> /// </remarks> public override IDisposable Impersonate(object state) { if (m_impersonationMode == ImpersonationMode.User) { if (m_identity != null) { return new DisposableImpersonationContext(m_identity.Impersonate()); } } else if (m_impersonationMode == ImpersonationMode.Process) { // Impersonate(0) will revert to the process credentials return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero)); } return null; } /// <summary> /// Create a <see cref="WindowsIdentity"/> given the userName, domainName and password. /// </summary> /// <param name="userName">the user name</param> /// <param name="domainName">the domain name</param> /// <param name="password">the password</param> /// <returns>the <see cref="WindowsIdentity"/> for the account specified</returns> /// <remarks> /// <para> /// Uses the Windows API call LogonUser to get a principal token for the account. This /// token is used to initialize the WindowsIdentity. /// </para> /// </remarks> #if FRAMEWORK_4_0_OR_ABOVE [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] private static WindowsIdentity LogonUser(string userName, string domainName, string password) { const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; // Call LogonUser to obtain a handle to an access token. IntPtr tokenHandle = IntPtr.Zero; if(!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle)) { NativeError error = NativeError.GetLastError(); throw new Exception("Failed to LogonUser ["+userName+"] in Domain ["+domainName+"]. Error: "+ error.ToString()); } const int SecurityImpersonation = 2; IntPtr dupeTokenHandle = IntPtr.Zero; if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle)) { NativeError error = NativeError.GetLastError(); if (tokenHandle != IntPtr.Zero) { CloseHandle(tokenHandle); } throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString()); } WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle); // Free the tokens. if (dupeTokenHandle != IntPtr.Zero) { CloseHandle(dupeTokenHandle); } if (tokenHandle != IntPtr.Zero) { CloseHandle(tokenHandle); } return identity; } #region Native Method Stubs [DllImport("advapi32.dll", SetLastError=true)] private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] private extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); #endregion #region DisposableImpersonationContext class /// <summary> /// Adds <see cref="IDisposable"/> to <see cref="WindowsImpersonationContext"/> /// </summary> /// <remarks> /// <para> /// Helper class to expose the <see cref="WindowsImpersonationContext"/> /// through the <see cref="IDisposable"/> interface. /// </para> /// </remarks> private sealed class DisposableImpersonationContext : IDisposable { private readonly WindowsImpersonationContext m_impersonationContext; /// <summary> /// Constructor /// </summary> /// <param name="impersonationContext">the impersonation context being wrapped</param> /// <remarks> /// <para> /// Constructor /// </para> /// </remarks> public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext) { m_impersonationContext = impersonationContext; } /// <summary> /// Revert the impersonation /// </summary> /// <remarks> /// <para> /// Revert the impersonation /// </para> /// </remarks> public void Dispose() { m_impersonationContext.Undo(); } } #endregion } } #endif // !NETCF
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ApiManagement { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiManagementServiceOperations operations. /// </summary> public partial interface IApiManagementServiceOperations { /// <summary> /// Restores a backup of an API Management service created using the /// ApiManagementService_Backup operation on the current service. This /// is a long running operation and could take several minutes to /// complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Restore API Management service from /// backup operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> RestoreWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceBackupRestoreParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a backup of the API Management service to the given Azure /// Storage Account. This is long running operation and could take /// several minutes to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the ApiManagementService_Backup operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BackupWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceBackupRestoreParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an API Management service. This is long running /// operation and could take several minutes to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate API Management service /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates an existing API Management service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate API Management service /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an API Management service resource description. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing API Management service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all API Management services within a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiManagementServiceResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all API Management services within an Azure subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiManagementServiceResource>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the Single-Sign-On token for the API Management Service which /// is valid for 5 Minutes. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceGetSsoTokenResult>> GetSsoTokenWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Checks availability and correctness of a name for an API Management /// service. /// </summary> /// <param name='parameters'> /// Parameters supplied to the CheckNameAvailability operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceNameAvailabilityResult>> CheckNameAvailabilityWithHttpMessagesAsync(ApiManagementServiceCheckNameAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the Microsoft.ApiManagement resource running in the Virtual /// network to pick the updated network settings. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Apply Network Configuration operation. /// If the parameters are empty, all the regions in which the Api /// Management service is deployed will be updated sequentially without /// incurring downtime in the region. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> ApplyNetworkConfigurationUpdatesWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceApplyNetworkConfigurationParameters parameters = default(ApiManagementServiceApplyNetworkConfigurationParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Restores a backup of an API Management service created using the /// ApiManagementService_Backup operation on the current service. This /// is a long running operation and could take several minutes to /// complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Restore API Management service from /// backup operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BeginRestoreWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceBackupRestoreParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a backup of the API Management service to the given Azure /// Storage Account. This is long running operation and could take /// several minutes to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the ApiManagementService_Backup operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BeginBackupWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceBackupRestoreParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an API Management service. This is long running /// operation and could take several minutes to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate API Management service /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates an existing API Management service. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate API Management service /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the Microsoft.ApiManagement resource running in the Virtual /// network to pick the updated network settings. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='serviceName'> /// The name of the API Management service. /// </param> /// <param name='parameters'> /// Parameters supplied to the Apply Network Configuration operation. /// If the parameters are empty, all the regions in which the Api /// Management service is deployed will be updated sequentially without /// incurring downtime in the region. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ApiManagementServiceResource>> BeginApplyNetworkConfigurationUpdatesWithHttpMessagesAsync(string resourceGroupName, string serviceName, ApiManagementServiceApplyNetworkConfigurationParameters parameters = default(ApiManagementServiceApplyNetworkConfigurationParameters), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// List all API Management services within a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiManagementServiceResource>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all API Management services within an Azure subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ApiManagementServiceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Numerics; using System.Reflection; using System.Threading; using Hazelcast.Core; using Hazelcast.Logging; using Hazelcast.Net.Ext; namespace Hazelcast.IO.Serialization { internal class SerializationService : ISerializationService { public const byte SerializerVersion = 1; private const int ConstantSerializersSize = SerializationConstants.ConstantSerializersLength; private static readonly IPartitioningStrategy TheEmptyPartitioningStrategy = new EmptyPartitioningStrategy(); private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof (SerializationService)); private readonly ISerializerAdapter[] _constantTypeIds = new ISerializerAdapter[ConstantSerializersSize]; private readonly Dictionary<Type, ISerializerAdapter> _constantTypesMap = new Dictionary<Type, ISerializerAdapter>(ConstantSerializersSize); private readonly BufferPoolThreadLocal _bufferPoolThreadLocal; private readonly ISerializerAdapter _dataSerializerAdapter; private readonly AtomicReference<ISerializerAdapter> _global = new AtomicReference<ISerializerAdapter>(); private readonly ConcurrentDictionary<int, ISerializerAdapter> _idMap = new ConcurrentDictionary<int, ISerializerAdapter>(); private readonly IInputOutputFactory _inputOutputFactory; private readonly IManagedContext _managedContext; private readonly ISerializerAdapter _nullSerializerAdapter; private readonly int _outputBufferSize; private readonly PortableContext _portableContext; private readonly PortableSerializer _portableSerializer; private readonly ISerializerAdapter _portableSerializerAdapter; private readonly ISerializerAdapter _serializableSerializerAdapter; private readonly ConcurrentDictionary<Type, ISerializerAdapter> _typeMap = new ConcurrentDictionary<Type, ISerializerAdapter>(); protected internal readonly IPartitioningStrategy GlobalPartitioningStrategy; private volatile bool _isActive = true; private bool _overrideClrSerialization; internal SerializationService(IInputOutputFactory inputOutputFactory, int version, IDictionary<int, IDataSerializableFactory> dataSerializableFactories, IDictionary<int, IPortableFactory> portableFactories, ICollection<IClassDefinition> classDefinitions, bool checkClassDefErrors, IManagedContext managedContext, IPartitioningStrategy partitionStrategy, int initialOutputBufferSize, bool enableCompression, bool enableSharedObject) { _inputOutputFactory = inputOutputFactory; _managedContext = managedContext; GlobalPartitioningStrategy = partitionStrategy; _outputBufferSize = initialOutputBufferSize; _bufferPoolThreadLocal = new BufferPoolThreadLocal(this); _portableContext = new PortableContext(this, version); _dataSerializerAdapter = CreateSerializerAdapterByGeneric<IIdentifiedDataSerializable>( new DataSerializer(dataSerializableFactories)); _portableSerializer = new PortableSerializer(_portableContext, portableFactories); _portableSerializerAdapter = CreateSerializerAdapterByGeneric<IPortable>(_portableSerializer); _nullSerializerAdapter = CreateSerializerAdapterByGeneric<object>(new ConstantSerializers.NullSerializer()); _serializableSerializerAdapter = CreateSerializerAdapterByGeneric<object>(new DefaultSerializers.SerializableSerializer()); RegisterConstantSerializers(); RegisterDefaultSerializers(); RegisterClassDefinitions(classDefinitions, checkClassDefErrors); } public IData ToData(object obj) { return ToData(obj, GlobalPartitioningStrategy); } public IData ToData(object obj, IPartitioningStrategy strategy) { if (obj == null) { return null; } if (obj is IData) { return (IData) obj; } var pool = _bufferPoolThreadLocal.Get(); var @out = pool.TakeOutputBuffer(); try { var serializer = SerializerFor(obj); var partitionHash = CalculatePartitionHash(obj, strategy); @out.WriteInt(partitionHash, ByteOrder.BigEndian); @out.WriteInt(serializer.GetTypeId(), ByteOrder.BigEndian); serializer.Write(@out, obj); return new HeapData(@out.ToByteArray()); } catch (Exception e) { throw HandleException(e); } finally { pool.ReturnOutputBuffer(@out); } } public T ToObject<T>(object @object) { if (!(@object is IData)) { return @object == null ? default(T) : (T)@object; } var data = (IData) @object; if (IsNullData(data)) { return default(T); } var pool = _bufferPoolThreadLocal.Get(); var @in = pool.TakeInputBuffer(data); try { var typeId = data.GetTypeId(); var serializer = SerializerFor(typeId); if (serializer == null) { if (_isActive) { throw new HazelcastSerializationException("There is no suitable de-serializer for type " + typeId); } throw new HazelcastInstanceNotActiveException(); } var obj = serializer.Read(@in); if (_managedContext != null) { obj = _managedContext.Initialize(obj); } return (T) obj; } catch (Exception e) { throw HandleException(e); } finally { pool.ReturnInputBuffer(@in); } } public void WriteObject(IObjectDataOutput output, object obj) { if (obj is IData) { throw new HazelcastSerializationException( "Cannot write a Data instance! Use #writeData(ObjectDataOutput out, Data data) instead."); } try { var serializer = SerializerFor(obj); output.WriteInt(serializer.GetTypeId()); serializer.Write(output, obj); } catch (Exception e) { throw HandleException(e); } } public byte GetVersion() { return SerializerVersion; } public T ReadObject<T>(IObjectDataInput input) { try { var typeId = input.ReadInt(); var serializer = SerializerFor(typeId); if (serializer == null) { if (_isActive) { throw new HazelcastSerializationException("There is no suitable de-serializer for type " + typeId); } throw new HazelcastInstanceNotActiveException(); } var obj = serializer.Read(input); if (_managedContext != null) { obj = _managedContext.Initialize(obj); } try { return (T) obj; } catch (NullReferenceException) { throw new HazelcastSerializationException("Trying to cast null value to value type " + typeof (T)); } } catch (Exception e) { throw HandleException(e); } } public virtual void DisposeData(IData data) { } public IBufferObjectDataInput CreateObjectDataInput(byte[] data) { return _inputOutputFactory.CreateInput(data, this); } public IBufferObjectDataInput CreateObjectDataInput(IData data) { return _inputOutputFactory.CreateInput(data, this); } public IBufferObjectDataOutput CreateObjectDataOutput(int size) { return _inputOutputFactory.CreateOutput(size, this); } public IBufferObjectDataOutput CreateObjectDataOutput() { return _inputOutputFactory.CreateOutput(_outputBufferSize, this); } public virtual IPortableContext GetPortableContext() { return _portableContext; } /// <exception cref="System.IO.IOException"></exception> public IPortableReader CreatePortableReader(IData data) { if (!data.IsPortable()) { throw new ArgumentException("Given data is not Portable! -> " + data.GetTypeId()); } var input = CreateObjectDataInput(data); return _portableSerializer.CreateReader(input); } public virtual void Destroy() { _isActive = false; foreach (var serializer in _typeMap.Values) { serializer.Destroy(); } _typeMap.Clear(); _idMap.Clear(); _global.Set(null); _constantTypesMap.Clear(); _bufferPoolThreadLocal.Dispose(); } public IManagedContext GetManagedContext() { return _managedContext; } public virtual ByteOrder GetByteOrder() { return _inputOutputFactory.GetByteOrder(); } public virtual bool IsActive() { return _isActive; } public void Register(Type type, ISerializer serializer) { if (type == null) { throw new ArgumentException("Class type information is required!"); } if (serializer.GetTypeId() <= 0) { throw new ArgumentException("Type id must be positive! Current: " + serializer.GetTypeId() + ", Serializer: " + serializer); } SafeRegister(type, CreateSerializerAdapter(type, serializer)); } public void RegisterGlobal(ISerializer serializer, bool overrideClrSerialization) { var adapter = CreateSerializerAdapterByGeneric<object>(serializer); if (!_global.CompareAndSet(null, adapter)) { throw new InvalidOperationException("Global serializer is already registered!"); } _overrideClrSerialization = overrideClrSerialization; var current = _idMap.GetOrAdd(serializer.GetTypeId(), adapter); if (current != null && current.GetImpl().GetType() != adapter.GetImpl().GetType()) { _global.CompareAndSet(adapter, null); _overrideClrSerialization = false; throw new InvalidOperationException("Serializer [" + current.GetImpl() + "] has been already registered for type-id: " + serializer.GetTypeId()); } } protected internal int CalculatePartitionHash(object obj, IPartitioningStrategy strategy) { var partitionHash = 0; var partitioningStrategy = strategy ?? GlobalPartitioningStrategy; if (partitioningStrategy != null) { var pk = partitioningStrategy.GetPartitionKey(obj); if (pk != null && pk != obj) { var partitionKey = ToData(pk, TheEmptyPartitioningStrategy); partitionHash = partitionKey == null ? 0 : partitionKey.GetPartitionHash(); } } return partitionHash; } protected internal ISerializerAdapter SerializerFor(int typeId) { if (typeId <= 0) { var index = IndexForDefaultType(typeId); if (index < ConstantSerializersSize) { return _constantTypeIds[index]; } } ISerializerAdapter result; _idMap.TryGetValue(typeId, out result); return _idMap.TryGetValue(typeId, out result) ? result : default(ISerializerAdapter); } internal PortableSerializer GetPortableSerializer() { return _portableSerializer; } internal static bool IsNullData(IData data) { return data.DataSize() == 0 && data.GetTypeId() == SerializationConstants.ConstantTypeNull; } internal virtual void SafeRegister(Type type, ISerializer serializer) { SafeRegister(type, CreateSerializerAdapter(type, serializer)); } private ISerializerAdapter CreateSerializerAdapter(Type type, ISerializer serializer) { var methodInfo = GetType() .GetMethod("CreateSerializerAdapterByGeneric", BindingFlags.NonPublic | BindingFlags.Instance); var makeGenericMethod = methodInfo.MakeGenericMethod(type); var result = makeGenericMethod.Invoke(this, new object[] {serializer}); return (ISerializerAdapter) result; } private ISerializerAdapter CreateSerializerAdapterByGeneric<T>(ISerializer serializer) { var streamSerializer = serializer as IStreamSerializer<T>; if (streamSerializer != null) { return new StreamSerializerAdapter<T>(streamSerializer); } var arraySerializer = serializer as IByteArraySerializer<T>; if (arraySerializer != null) { return new ByteArraySerializerAdapter<T>(arraySerializer); } throw new ArgumentException("Serializer must be instance of either " + "StreamSerializer or ByteArraySerializer!"); } private static void GetInterfaces(Type type, ICollection<Type> interfaces) { var types = type.GetInterfaces(); if (types.Length > 0) { foreach (var t in types) { interfaces.Add(t); } foreach (var cl in types) { GetInterfaces(cl, interfaces); } } } private Exception HandleException(Exception e) { if (e is OutOfMemoryException) { return e; } if (e is HazelcastSerializationException) { return e; } return new HazelcastSerializationException(e); } private int IndexForDefaultType(int typeId) { return -typeId; } private ISerializerAdapter LookupCustomSerializer(Type type) { ISerializerAdapter serializer; _typeMap.TryGetValue(type, out serializer); if (serializer == null) { // look for super classes var typeSuperclass = type.BaseType; ICollection<Type> interfaces = new HashSet<Type>(); //new Type[5]); GetInterfaces(type, interfaces); while (typeSuperclass != null) { serializer = RegisterFromSuperType(type, typeSuperclass); if (serializer != null) { break; } GetInterfaces(typeSuperclass, interfaces); typeSuperclass = typeSuperclass.BaseType; } if (serializer == null) { // look for interfaces foreach (var typeInterface in interfaces) { serializer = RegisterFromSuperType(type, typeInterface); if (serializer != null) { break; } } } } return serializer; } private ISerializerAdapter LookupDefaultSerializer(Type type) { if (typeof (IIdentifiedDataSerializable).IsAssignableFrom(type)) { return _dataSerializerAdapter; } if (typeof (IPortable).IsAssignableFrom(type)) { return _portableSerializerAdapter; } ISerializerAdapter serializer; if (_constantTypesMap.TryGetValue(type, out serializer) && serializer != null) { return serializer; } return null; } private ISerializerAdapter LookupGlobalSerializer(Type type) { var serializer = _global.Get(); if (serializer != null) { SafeRegister(type, serializer); } return serializer; } private ISerializerAdapter LookupSerializableSerializer(Type type) { if (type.IsSerializable) { if (SafeRegister(type, _serializableSerializerAdapter)) { Logger.Warning("Performance Hint: Serialization service will use CLR Serialization for : " + type + ". Please consider using a faster serialization option such as IIdentifiedDataSerializable."); } return _serializableSerializerAdapter; } return null; } private void RegisterClassDefinition(IClassDefinition cd, IDictionary<int, IClassDefinition> classDefMap, bool checkClassDefErrors) { for (var i = 0; i < cd.GetFieldCount(); i++) { var fd = cd.GetField(i); if (fd.GetFieldType() == FieldType.Portable || fd.GetFieldType() == FieldType.PortableArray) { var classId = fd.GetClassId(); IClassDefinition nestedCd; classDefMap.TryGetValue(classId, out nestedCd); if (nestedCd != null) { RegisterClassDefinition(nestedCd, classDefMap, checkClassDefErrors); _portableContext.RegisterClassDefinition(nestedCd); } else { if (checkClassDefErrors) { throw new HazelcastSerializationException( "Could not find registered ClassDefinition for class-id: " + classId); } } } } _portableContext.RegisterClassDefinition(cd); } private void RegisterClassDefinitions(ICollection<IClassDefinition> classDefinitions, bool checkClassDefErrors) { IDictionary<int, IClassDefinition> classDefMap = new Dictionary<int, IClassDefinition>(classDefinitions.Count); foreach (var cd in classDefinitions) { if (classDefMap.ContainsKey(cd.GetClassId())) { throw new HazelcastSerializationException("Duplicate registration found for class-id[" + cd.GetClassId() + "]!"); } classDefMap.Add(cd.GetClassId(), cd); } foreach (var classDefinition in classDefinitions) { RegisterClassDefinition(classDefinition, classDefMap, checkClassDefErrors); } } private void RegisterConstant(Type type, ISerializer serializer) { RegisterConstant(type, CreateSerializerAdapter(type, serializer)); } private void RegisterConstant(Type type, ISerializerAdapter serializer) { if (type != null) { _constantTypesMap.Add(type, serializer); } _constantTypeIds[IndexForDefaultType(serializer.GetTypeId())] = serializer; } private void RegisterConstantSerializers() { RegisterConstant(null, _nullSerializerAdapter); RegisterConstant(typeof (IIdentifiedDataSerializable), _dataSerializerAdapter); RegisterConstant(typeof (IPortable), _portableSerializerAdapter); RegisterConstant(typeof (byte), new ConstantSerializers.ByteSerializer()); RegisterConstant(typeof (bool), new ConstantSerializers.BooleanSerializer()); RegisterConstant(typeof (char), new ConstantSerializers.CharSerializer()); RegisterConstant(typeof (short), new ConstantSerializers.ShortSerializer()); RegisterConstant(typeof (int), new ConstantSerializers.IntegerSerializer()); RegisterConstant(typeof (long), new ConstantSerializers.LongSerializer()); RegisterConstant(typeof (float), new ConstantSerializers.FloatSerializer()); RegisterConstant(typeof (double), new ConstantSerializers.DoubleSerializer()); RegisterConstant(typeof (bool[]), new ConstantSerializers.BooleanArraySerializer()); RegisterConstant(typeof (byte[]), new ConstantSerializers.ByteArraySerializer()); RegisterConstant(typeof (char[]), new ConstantSerializers.CharArraySerializer()); RegisterConstant(typeof (short[]), new ConstantSerializers.ShortArraySerializer()); RegisterConstant(typeof (int[]), new ConstantSerializers.IntegerArraySerializer()); RegisterConstant(typeof (long[]), new ConstantSerializers.LongArraySerializer()); RegisterConstant(typeof (float[]), new ConstantSerializers.FloatArraySerializer()); RegisterConstant(typeof (double[]), new ConstantSerializers.DoubleArraySerializer()); RegisterConstant(typeof (string[]), new ConstantSerializers.StringArraySerializer()); RegisterConstant(typeof (string), new ConstantSerializers.StringSerializer()); } private void RegisterDefaultSerializers() { RegisterConstant(typeof (DateTime), new DefaultSerializers.DateSerializer()); //TODO: proper support for generic types RegisterConstant(typeof (JavaClass), new DefaultSerializers.JavaClassSerializer()); RegisterConstant(typeof (BigInteger), new DefaultSerializers.BigIntegerSerializer()); RegisterConstant(typeof (JavaEnum), new DefaultSerializers.JavaEnumSerializer()); RegisterConstant(typeof (List<object>), new DefaultSerializers.ListSerializer<object>()); RegisterConstant(typeof (LinkedList<object>), new DefaultSerializers.LinkedListSerializer<object>()); _idMap.TryAdd(_serializableSerializerAdapter.GetTypeId(), _serializableSerializerAdapter); } private ISerializerAdapter RegisterFromSuperType(Type type, Type superType) { ISerializerAdapter serializer; _typeMap.TryGetValue(superType, out serializer); if (serializer != null) { SafeRegister(type, serializer); } return serializer; } private bool SafeRegister(Type type, ISerializerAdapter serializer) { if (_constantTypesMap.ContainsKey(type)) { throw new ArgumentException("[" + type + "] serializer cannot be overridden!"); } var current = _typeMap.GetOrAdd(type, serializer); if (current != null && current.GetImpl().GetType() != serializer.GetImpl().GetType()) { throw new InvalidOperationException("Serializer[" + current.GetImpl() + "] has been already registered for type: " + type); } current = _idMap.GetOrAdd(serializer.GetTypeId(), serializer); if (current != null && current.GetImpl().GetType() != serializer.GetImpl().GetType()) { throw new InvalidOperationException("Serializer [" + current.GetImpl() + "] has been already registered for type-id: " + serializer.GetTypeId()); } return current == null; } /// <summary> /// Searches for a serializer for the provided object /// Serializers will be searched in this order; /// 1-NULL serializer /// 2-Default serializers, like primitives, arrays, String and some C# types /// 3-Custom registered types by user /// 4-CLR serialization if type is Serializable /// 5-Global serializer if registered by user /// /// </summary> /// <param name="obj"></param> /// <returns></returns> private ISerializerAdapter SerializerFor(object obj) { if (obj == null) { return _nullSerializerAdapter; } var type = obj.GetType(); var serializer = LookupDefaultSerializer(type); if (serializer == null) { serializer = LookupCustomSerializer(type); } if (serializer == null && !_overrideClrSerialization) { serializer = LookupSerializableSerializer(type); } if (serializer == null) { serializer = LookupGlobalSerializer(type); } if (serializer == null) { if (_isActive) { throw new HazelcastSerializationException("There is no suitable serializer for " + type); } throw new HazelcastInstanceNotActiveException(); } return serializer; } private sealed class EmptyPartitioningStrategy : IPartitioningStrategy { public object GetPartitionKey(object key) { return null; } } } }
// Copyright 2010 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using JetBrains.Annotations; using NodaTime.Annotations; using NodaTime.Fields; using NodaTime.Text; using NodaTime.Utility; using System; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using static NodaTime.NodaConstants; namespace NodaTime { // Note: documentation that refers to the LocalDateTime type within this class must use the fully-qualified // reference to avoid being resolved to the LocalDateTime property instead. /// <summary> /// LocalTime is an immutable struct representing a time of day, with no reference /// to a particular calendar, time zone or date. /// </summary> /// <remarks> /// Ordering and equality are defined in the natural way, simply comparing the number of "nanoseconds since midnight". /// </remarks> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> [TypeConverter(typeof(LocalTimeTypeConverter))] [XmlSchemaProvider(nameof(AddSchema))] public readonly struct LocalTime : IEquatable<LocalTime>, IComparable<LocalTime>, IFormattable, IComparable, IXmlSerializable { /// <summary> /// Local time at midnight, i.e. 0 hours, 0 minutes, 0 seconds. /// </summary> public static LocalTime Midnight { get; } = new LocalTime(0, 0, 0); /// <summary> /// The minimum value of this type; equivalent to <see cref="Midnight"/>. /// </summary> public static LocalTime MinValue => Midnight; /// <summary> /// Local time at noon, i.e. 12 hours, 0 minutes, 0 seconds. /// </summary> public static LocalTime Noon { get; } = new LocalTime(12, 0, 0); /// <summary> /// The maximum value of this type, one nanosecond before midnight. /// </summary> /// <remarks>This is useful if you have to use an inclusive upper bound for some reason. /// In general, it's better to use an exclusive upper bound, in which case use midnight of /// the following day.</remarks> public static LocalTime MaxValue { get; } = new LocalTime(NanosecondsPerDay - 1); /// <summary> /// Nanoseconds since midnight, in the range [0, 86,400,000,000,000). /// </summary> private readonly long nanoseconds; /// <summary> /// Creates a local time at the given hour and minute, with second, millisecond-of-second /// and tick-of-millisecond values of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); } nanoseconds = unchecked(hour * NanosecondsPerHour + minute * NanosecondsPerMinute); } /// <summary> /// Creates a local time at the given hour, minute and second, /// with millisecond-of-second and tick-of-millisecond values of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute, int second) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerMinute - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); } nanoseconds = unchecked(hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond); } /// <summary> /// Creates a local time at the given hour, minute, second and millisecond, /// with a tick-of-millisecond value of zero. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <param name="millisecond">The millisecond of the second.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public LocalTime(int hour, int minute, int second, int millisecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerMinute - 1 || millisecond < 0 || millisecond > MillisecondsPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1); } nanoseconds = unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + millisecond * NanosecondsPerMillisecond); } /// <summary> /// Factory method to create a local time at the given hour, minute, second, millisecond and tick within millisecond. /// </summary> /// <param name="hour">The hour of day.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second of the minute.</param> /// <param name="millisecond">The millisecond of the second.</param> /// <param name="tickWithinMillisecond">The tick within the millisecond.</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public static LocalTime FromHourMinuteSecondMillisecondTick(int hour, int minute, int second, int millisecond, int tickWithinMillisecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerMinute - 1 || millisecond < 0 || millisecond > MillisecondsPerSecond - 1 || tickWithinMillisecond < 0 || tickWithinMillisecond > TicksPerMillisecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(millisecond), millisecond, 0, MillisecondsPerSecond - 1); Preconditions.CheckArgumentRange(nameof(tickWithinMillisecond), tickWithinMillisecond, 0, TicksPerMillisecond - 1); } long nanoseconds = unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + millisecond * NanosecondsPerMillisecond + tickWithinMillisecond * NanosecondsPerTick); return new LocalTime(nanoseconds); } /// <summary> /// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and tick of second. /// </summary> /// <remarks> /// This is not a constructor overload as it would have the same signature as the one taking millisecond of second. /// </remarks> /// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param> /// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param> /// <param name="second">The second of minute in the desired time, in the range [0, 59].</param> /// <param name="tickWithinSecond">The tick within the second in the desired time, in the range [0, 9999999].</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public static LocalTime FromHourMinuteSecondTick(int hour, int minute, int second, int tickWithinSecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerMinute - 1 || tickWithinSecond < 0 || tickWithinSecond > TicksPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(tickWithinSecond), tickWithinSecond, 0, TicksPerSecond - 1); } return new LocalTime(unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + tickWithinSecond * NanosecondsPerTick)); } /// <summary> /// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and nanosecond of second. /// </summary> /// <remarks> /// This is not a constructor overload as it would have the same signature as the one taking millisecond of second. /// </remarks> /// <param name="hour">The hour of day in the desired time, in the range [0, 23].</param> /// <param name="minute">The minute of hour in the desired time, in the range [0, 59].</param> /// <param name="second">The second of minute in the desired time, in the range [0, 59].</param> /// <param name="nanosecondWithinSecond">The nanosecond within the second in the desired time, in the range [0, 999999999].</param> /// <exception cref="ArgumentOutOfRangeException">The parameters do not form a valid time.</exception> /// <returns>The resulting time.</returns> public static LocalTime FromHourMinuteSecondNanosecond(int hour, int minute, int second, long nanosecondWithinSecond) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hour < 0 || hour > HoursPerDay - 1 || minute < 0 || minute > MinutesPerHour - 1 || second < 0 || second > SecondsPerMinute - 1 || nanosecondWithinSecond < 0 || nanosecondWithinSecond > NanosecondsPerSecond - 1) { Preconditions.CheckArgumentRange(nameof(hour), hour, 0, HoursPerDay - 1); Preconditions.CheckArgumentRange(nameof(minute), minute, 0, MinutesPerHour - 1); Preconditions.CheckArgumentRange(nameof(second), second, 0, SecondsPerMinute - 1); Preconditions.CheckArgumentRange(nameof(nanosecondWithinSecond), nanosecondWithinSecond, 0, NanosecondsPerSecond - 1); } return FromHourMinuteSecondNanosecondTrusted(hour, minute, second, nanosecondWithinSecond); } /// <summary> /// Factory method for creating a local time from the hour of day, minute of hour, second of minute, and nanosecond of second /// where the values have already been validated. /// </summary> internal static LocalTime FromHourMinuteSecondNanosecondTrusted( [Trusted] int hour, [Trusted] int minute, [Trusted] int second, [Trusted] long nanosecondWithinSecond) => new LocalTime(unchecked( hour * NanosecondsPerHour + minute * NanosecondsPerMinute + second * NanosecondsPerSecond + nanosecondWithinSecond)); /// <summary> /// Constructor only called from other parts of Noda Time - trusted to be the range [0, NanosecondsPerDay). /// </summary> internal LocalTime([Trusted] long nanoseconds) { Preconditions.DebugCheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1); this.nanoseconds = nanoseconds; } /// <summary> /// Factory method for creating a local time from the number of nanoseconds which have elapsed since midnight. /// </summary> /// <param name="nanoseconds">The number of nanoseconds, in the range [0, 86,399,999,999,999]</param> /// <returns>The resulting time.</returns> public static LocalTime FromNanosecondsSinceMidnight(long nanoseconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (nanoseconds < 0 || nanoseconds > NanosecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(nanoseconds), nanoseconds, 0, NanosecondsPerDay - 1); } return new LocalTime(nanoseconds); } /// <summary> /// Factory method for creating a local time from the number of ticks which have elapsed since midnight. /// </summary> /// <param name="ticks">The number of ticks, in the range [0, 863,999,999,999]</param> /// <returns>The resulting time.</returns> public static LocalTime FromTicksSinceMidnight(long ticks) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (ticks < 0 || ticks > TicksPerDay - 1) { Preconditions.CheckArgumentRange(nameof(ticks), ticks, 0, TicksPerDay - 1); } return new LocalTime(unchecked(ticks * NanosecondsPerTick)); } /// <summary> /// Factory method for creating a local time from the number of milliseconds which have elapsed since midnight. /// </summary> /// <param name="milliseconds">The number of milliseconds, in the range [0, 86,399,999]</param> /// <returns>The resulting time.</returns> public static LocalTime FromMillisecondsSinceMidnight(int milliseconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (milliseconds < 0 || milliseconds > MillisecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, 0, MillisecondsPerDay - 1); } return new LocalTime(unchecked(milliseconds * NanosecondsPerMillisecond)); } /// <summary> /// Factory method for creating a local time from the number of seconds which have elapsed since midnight. /// </summary> /// <param name="seconds">The number of seconds, in the range [0, 86,399]</param> /// <returns>The resulting time.</returns> public static LocalTime FromSecondsSinceMidnight(int seconds) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (seconds < 0 || seconds > SecondsPerDay - 1) { Preconditions.CheckArgumentRange(nameof(seconds), seconds, 0, SecondsPerDay - 1); } return new LocalTime(unchecked(seconds * NanosecondsPerSecond)); } /// <summary> /// Factory method for creating a local time from the number of minutes which have elapsed since midnight. /// </summary> /// <param name="minutes">The number of minutes, in the range [0, 1439]</param> /// <returns>The resulting time.</returns> public static LocalTime FromMinutesSinceMidnight(int minutes) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (minutes < 0 || minutes > MinutesPerDay - 1) { Preconditions.CheckArgumentRange(nameof(minutes), minutes, 0, MinutesPerDay - 1); } return new LocalTime(unchecked(minutes * NanosecondsPerMinute)); } /// <summary> /// Factory method for creating a local time from the number of hours which have elapsed since midnight. /// </summary> /// <param name="hours">The number of hours, in the range [0, 23]</param> /// <returns>The resulting time.</returns> public static LocalTime FromHoursSinceMidnight(int hours) { // Avoid the method calls which give a decent exception unless we're actually going to fail. if (hours < 0 || hours > HoursPerDay - 1) { Preconditions.CheckArgumentRange(nameof(hours), hours, 0, HoursPerDay - 1); } return new LocalTime(unchecked(hours * NanosecondsPerHour)); } /// <summary> /// Gets the hour of day of this local time, in the range 0 to 23 inclusive. /// </summary> /// <value>The hour of day of this local time, in the range 0 to 23 inclusive.</value> public int Hour => // Effectively nanoseconds / NanosecondsPerHour, but apparently rather more efficient. (int) ((nanoseconds >> 13) / 439453125); /// <summary> /// Gets the hour of the half-day of this local time, in the range 1 to 12 inclusive. /// </summary> /// <value>The hour of the half-day of this local time, in the range 1 to 12 inclusive.</value> public int ClockHourOfHalfDay { get { unchecked { int hourOfHalfDay = unchecked(Hour % 12); return hourOfHalfDay == 0 ? 12 : hourOfHalfDay; } } } /// <summary> /// Gets the minute of this local time, in the range 0 to 59 inclusive. /// </summary> /// <value>The minute of this local time, in the range 0 to 59 inclusive.</value> public int Minute { get { unchecked { // Effectively nanoseconds / NanosecondsPerMinute, but apparently rather more efficient. int minuteOfDay = (int) ((nanoseconds >> 11) / 29296875); return minuteOfDay % MinutesPerHour; } } } /// <summary> /// Gets the second of this local time within the minute, in the range 0 to 59 inclusive. /// </summary> /// <value>The second of this local time within the minute, in the range 0 to 59 inclusive.</value> public int Second { get { unchecked { int secondOfDay = (int) (nanoseconds / (int) NanosecondsPerSecond); return secondOfDay % SecondsPerMinute; } } } /// <summary> /// Gets the millisecond of this local time within the second, in the range 0 to 999 inclusive. /// </summary> /// <value>The millisecond of this local time within the second, in the range 0 to 999 inclusive.</value> public int Millisecond { get { unchecked { long milliSecondOfDay = (nanoseconds / (int) NanosecondsPerMillisecond); return (int) (milliSecondOfDay % MillisecondsPerSecond); } } } // TODO(optimization): Rewrite for performance? /// <summary> /// Gets the tick of this local time within the second, in the range 0 to 9,999,999 inclusive. /// </summary> /// <value>The tick of this local time within the second, in the range 0 to 9,999,999 inclusive.</value> public int TickOfSecond => unchecked((int) (TickOfDay % (int) TicksPerSecond)); /// <summary> /// Gets the tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive. /// </summary> /// <remarks> /// If the value does not fall on a tick boundary, it will be truncated towards zero. /// </remarks> /// <value>The tick of this local time within the day, in the range 0 to 863,999,999,999 inclusive.</value> public long TickOfDay => nanoseconds / NanosecondsPerTick; /// <summary> /// Gets the nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this local time within the second, in the range 0 to 999,999,999 inclusive.</value> public int NanosecondOfSecond => unchecked((int) (nanoseconds % NanosecondsPerSecond)); /// <summary> /// Gets the nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive. /// </summary> /// <value>The nanosecond of this local time within the day, in the range 0 to 86,399,999,999,999 inclusive.</value> public long NanosecondOfDay => nanoseconds; /// <summary> /// Creates a new local time by adding a period to an existing time. The period must not contain /// any date-related units (days etc) with non-zero values. /// </summary> /// <param name="time">The time to add the period to</param> /// <param name="period">The period to add</param> /// <returns>The result of adding the period to the time, wrapping via midnight if necessary</returns> public static LocalTime operator +(LocalTime time, Period period) { Preconditions.CheckNotNull(period, nameof(period)); Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot add a period with a date component to a time"); return time.PlusHours(period.Hours) .PlusMinutes(period.Minutes) .PlusSeconds(period.Seconds) .PlusMilliseconds(period.Milliseconds) .PlusTicks(period.Ticks) .PlusNanoseconds(period.Nanoseconds); } /// <summary> /// Adds the specified period to the time. Friendly alternative to <c>operator+()</c>. /// </summary> /// <param name="time">The time to add the period to</param> /// <param name="period">The period to add. Must not contain any (non-zero) date units.</param> /// <returns>The sum of the given time and period</returns> public static LocalTime Add(LocalTime time, Period period) => time + period; /// <summary> /// Adds the specified period to this time. Fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="period">The period to add. Must not contain any (non-zero) date units.</param> /// <returns>The sum of this time and the given period</returns> [Pure] public LocalTime Plus(Period period) => this + period; /// <summary> /// Creates a new local time by subtracting a period from an existing time. The period must not contain /// any date-related units (days etc) with non-zero values. /// This is a convenience operator over the <see cref="Minus(Period)"/> method. /// </summary> /// <param name="time">The time to subtract the period from</param> /// <param name="period">The period to subtract</param> /// <returns>The result of subtract the period from the time, wrapping via midnight if necessary</returns> public static LocalTime operator -(LocalTime time, Period period) { Preconditions.CheckNotNull(period, nameof(period)); Preconditions.CheckArgument(!period.HasDateComponent, nameof(period), "Cannot subtract a period with a date component from a time"); return time.PlusHours(-period.Hours) .PlusMinutes(-period.Minutes) .PlusSeconds(-period.Seconds) .PlusMilliseconds(-period.Milliseconds) .PlusTicks(-period.Ticks) .PlusNanoseconds(-period.Nanoseconds); } /// <summary> /// Subtracts the specified period from the time. Friendly alternative to <c>operator-()</c>. /// </summary> /// <param name="time">The time to subtract the period from</param> /// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param> /// <returns>The result of subtracting the given period from the time.</returns> public static LocalTime Subtract(LocalTime time, Period period) => time - period; /// <summary> /// Subtracts the specified period from this time. Fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="period">The period to subtract. Must not contain any (non-zero) date units.</param> /// <returns>The result of subtracting the given period from this time.</returns> [Pure] public LocalTime Minus(Period period) => this - period; /// <summary> /// Subtracts one time from another, returning the result as a <see cref="Period"/>. /// </summary> /// <remarks> /// This is simply a convenience operator for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>. /// </remarks> /// <param name="lhs">The time to subtract from</param> /// <param name="rhs">The time to subtract</param> /// <returns>The result of subtracting one time from another.</returns> public static Period operator -(LocalTime lhs, LocalTime rhs) => Period.Between(rhs, lhs); /// <summary> /// Subtracts one time from another, returning the result as a <see cref="Period"/> with units of years, months and days. /// </summary> /// <remarks> /// This is simply a convenience method for calling <see cref="Period.Between(NodaTime.LocalTime,NodaTime.LocalTime)"/>. /// </remarks> /// <param name="lhs">The time to subtract from</param> /// <param name="rhs">The time to subtract</param> /// <returns>The result of subtracting one time from another.</returns> public static Period Subtract(LocalTime lhs, LocalTime rhs) => lhs - rhs; /// <summary> /// Subtracts the specified time from this time, returning the result as a <see cref="Period"/>. /// Fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="time">The time to subtract from this</param> /// <returns>The difference between the specified time and this one</returns> [Pure] public Period Minus(LocalTime time) => this - time; /// <summary> /// Compares two local times for equality. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="lhs">The first value to compare</param> /// <param name="rhs">The second value to compare</param> /// <returns>True if the two times are the same; false otherwise</returns> public static bool operator ==(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds == rhs.nanoseconds; /// <summary> /// Compares two local times for inequality. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="lhs">The first value to compare</param> /// <param name="rhs">The second value to compare</param> /// <returns>False if the two times are the same; true otherwise</returns> public static bool operator !=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds != rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is strictly earlier than the right one. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is strictly earlier than <paramref name="rhs"/>, false otherwise.</returns> public static bool operator <(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds < rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is earlier than or equal to the right one. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is earlier than or equal to <paramref name="rhs"/>, false otherwise.</returns> public static bool operator <=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds <= rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is strictly later than the right one. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is strictly later than <paramref name="rhs"/>, false otherwise.</returns> public static bool operator >(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds > rhs.nanoseconds; /// <summary> /// Compares two LocalTime values to see if the left one is later than or equal to the right one. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="lhs">First operand of the comparison</param> /// <param name="rhs">Second operand of the comparison</param> /// <returns>true if the <paramref name="lhs"/> is later than or equal to <paramref name="rhs"/>, false otherwise.</returns> public static bool operator >=(LocalTime lhs, LocalTime rhs) => lhs.nanoseconds >= rhs.nanoseconds; /// <summary> /// Indicates whether this time is earlier, later or the same as another one. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="other">The other date/time to compare this one with</param> /// <returns>A value less than zero if this time is earlier than <paramref name="other"/>; /// zero if this time is the same as <paramref name="other"/>; a value greater than zero if this time is /// later than <paramref name="other"/>.</returns> public int CompareTo(LocalTime other) => nanoseconds.CompareTo(other.nanoseconds); /// <summary> /// Implementation of <see cref="IComparable.CompareTo"/> to compare two LocalTimes. /// See the type documentation for a description of ordering semantics. /// </summary> /// <remarks> /// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred. /// </remarks> /// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="LocalTime"/>.</exception> /// <param name="obj">The object to compare this value with.</param> /// <returns>The result of comparing this LocalTime with another one; see <see cref="CompareTo(NodaTime.LocalTime)"/> for general details. /// If <paramref name="obj"/> is null, this method returns a value greater than 0. /// </returns> int IComparable.CompareTo(object obj) { if (obj is null) { return 1; } Preconditions.CheckArgument(obj is LocalTime, nameof(obj), "Object must be of type NodaTime.LocalTime."); return CompareTo((LocalTime) obj); } /// <summary> /// Returns a hash code for this local time. /// See the type documentation for a description of equality semantics. /// </summary> /// <returns>A hash code for this local time.</returns> public override int GetHashCode() => nanoseconds.GetHashCode(); /// <summary> /// Compares this local time with the specified one for equality. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="other">The other local time to compare this one with</param> /// <returns>True if the specified time is equal to this one; false otherwise</returns> public bool Equals(LocalTime other) => this == other; /// <summary> /// Compares this local time with the specified reference. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="obj">The object to compare this one with</param> /// <returns>True if the specified value is a local time which is equal to this one; false otherwise</returns> public override bool Equals(object? obj) => obj is LocalTime other && this == other; /// <summary> /// Returns a new LocalTime representing the current value with the given number of hours added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11pm plus two hours is 1am, for example. /// </remarks> /// <param name="hours">The number of hours to add</param> /// <returns>The current value plus the given number of hours.</returns> [Pure] public LocalTime PlusHours(long hours) => TimePeriodField.Hours.Add(this, hours); /// <summary> /// Returns a new LocalTime representing the current value with the given number of minutes added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11pm plus 120 minutes is 1am, for example. /// </remarks> /// <param name="minutes">The number of minutes to add</param> /// <returns>The current value plus the given number of minutes.</returns> [Pure] public LocalTime PlusMinutes(long minutes) => TimePeriodField.Minutes.Add(this, minutes); /// <summary> /// Returns a new LocalTime representing the current value with the given number of seconds added. /// </summary> /// <remarks> /// If the value goes past the start or end of the day, it wraps - so 11:59pm plus 120 seconds is 12:01am, for example. /// </remarks> /// <param name="seconds">The number of seconds to add</param> /// <returns>The current value plus the given number of seconds.</returns> [Pure] public LocalTime PlusSeconds(long seconds) => TimePeriodField.Seconds.Add(this, seconds); /// <summary> /// Returns a new LocalTime representing the current value with the given number of milliseconds added. /// </summary> /// <param name="milliseconds">The number of milliseconds to add</param> /// <returns>The current value plus the given number of milliseconds.</returns> [Pure] public LocalTime PlusMilliseconds(long milliseconds) => TimePeriodField.Milliseconds.Add(this, milliseconds); /// <summary> /// Returns a new LocalTime representing the current value with the given number of ticks added. /// </summary> /// <param name="ticks">The number of ticks to add</param> /// <returns>The current value plus the given number of ticks.</returns> [Pure] public LocalTime PlusTicks(long ticks) => TimePeriodField.Ticks.Add(this, ticks); /// <summary> /// Returns a new LocalTime representing the current value with the given number of nanoseconds added. /// </summary> /// <param name="nanoseconds">The number of nanoseconds to add</param> /// <returns>The current value plus the given number of ticks.</returns> [Pure] public LocalTime PlusNanoseconds(long nanoseconds) => TimePeriodField.Nanoseconds.Add(this, nanoseconds); /// <summary> /// Returns this time, with the given adjuster applied to it. /// </summary> /// <remarks> /// If the adjuster attempts to construct an invalid time, any exception thrown by /// that construction attempt will be propagated through this method. /// </remarks> /// <param name="adjuster">The adjuster to apply.</param> /// <returns>The adjusted time.</returns> [Pure] public LocalTime With(Func<LocalTime, LocalTime> adjuster) => Preconditions.CheckNotNull(adjuster, nameof(adjuster)).Invoke(this); /// <summary> /// Returns an <see cref="OffsetTime"/> for this time-of-day with the given offset. /// </summary> /// <remarks>This method is purely a convenient alternative to calling the <see cref="OffsetTime"/> constructor directly.</remarks> /// <param name="offset">The offset to apply.</param> /// <returns>The result of this time-of-day offset by the given amount.</returns> [Pure] public OffsetTime WithOffset(Offset offset) => new OffsetTime(this, offset); /// <summary> /// Combines this <see cref="LocalTime"/> with the given <see cref="LocalDate"/> /// into a single <see cref="LocalDateTime"/>. /// Fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="date">The date to combine with this time</param> /// <returns>The <see cref="LocalDateTime"/> representation of the given time on this date</returns> [Pure] public LocalDateTime On(LocalDate date) => date + this; /// <summary> /// Deconstruct this time into its components. /// </summary> /// <param name="hour">The hour of the time.</param> /// <param name="minute">The minute of the hour.</param> /// <param name="second">The second within the minute.</param> [Pure] public void Deconstruct(out int hour, out int minute, out int second) { hour = Hour; minute = Minute; second = Second; } /// <summary> /// Returns the later time of the given two. /// </summary> /// <param name="x">The first time to compare.</param> /// <param name="y">The second time to compare.</param> /// <returns>The later instant of <paramref name="x"/> or <paramref name="y"/>.</returns> public static LocalTime Max(LocalTime x, LocalTime y) { return x > y ? x : y; } /// <summary> /// Returns the earlier time of the given two. /// </summary> /// <param name="x">The first time to compare.</param> /// <param name="y">The second time to compare.</param> /// <returns>The earlier time of <paramref name="x"/> or <paramref name="y"/>.</returns> public static LocalTime Min(LocalTime x, LocalTime y) => x < y ? x : y; #region Formatting /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// The value of the current instance in the default format pattern ("T"), using the current thread's /// culture to obtain a format provider. /// </returns> public override string ToString() => LocalTimePattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture); /// <summary> /// Formats the value of the current instance using the specified pattern. /// </summary> /// <returns> /// A <see cref="System.String" /> containing the value of the current instance in the specified format. /// </returns> /// <param name="patternText">The <see cref="System.String" /> specifying the pattern to use, /// or null to use the default format pattern ("T"). /// </param> /// <param name="formatProvider">The <see cref="System.IFormatProvider" /> to use when formatting the value, /// or null to use the current thread's culture to obtain a format provider. /// </param> /// <filterpriority>2</filterpriority> public string ToString(string? patternText, IFormatProvider? formatProvider) => LocalTimePattern.BclSupport.Format(this, patternText, formatProvider); #endregion Formatting #region XML serialization /// <summary> /// Adds the XML schema type describing the structure of the <see cref="LocalTime"/> XML serialization to the given <paramref name="xmlSchemaSet"/>. /// the <paramref name="xmlSchemaSet"/>. /// </summary> /// <param name="xmlSchemaSet">The XML schema set provided by <see cref="XmlSchemaExporter"/>.</param> /// <returns>The qualified name of the schema type that was added to the <paramref name="xmlSchemaSet"/>.</returns> public static XmlQualifiedName AddSchema(XmlSchemaSet xmlSchemaSet) => Xml.XmlSchemaDefinition.AddLocalTimeSchemaType(xmlSchemaSet); /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that /// <inheritdoc /> void IXmlSerializable.ReadXml(XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = LocalTimePattern.ExtendedIso; string text = reader.ReadElementContentAsString(); Unsafe.AsRef(this) = pattern.Parse(text).Value; } /// <inheritdoc /> void IXmlSerializable.WriteXml(XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); writer.WriteString(LocalTimePattern.ExtendedIso.Format(this)); } #endregion } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.Text.RegularExpressions; using Vevo; using Vevo.DataAccessLib.Cart; using Vevo.Domain; using Vevo.Domain.Products; using Vevo.Shared.DataAccess; using Vevo.WebUI; using Vevo.Domain.Stores; public partial class AdminAdvanced_MainControls_ProductSorting : AdminAdvancedBaseUserControl { protected void Page_Load( object sender, EventArgs e ) { uxLanguageControl.BubbleEvent += new EventHandler( Details_RefreshHandler ); if (!MainContext.IsPostBack) PopulateControl(); RegisterJavaScript(); if (!IsAdminModifiable()) { uxSortByNameButton.Visible = false; uxSortByIDButton.Visible = false; uxSaveButton.Visible = false; } } protected void Page_PreRender( object sender, EventArgs e ) { } protected void uxSortByNameButton_Click( object sender, EventArgs e ) { PopulateListControls( "Name" ); } protected void uxSortByIDButton_Click( object sender, EventArgs e ) { PopulateListControls( "ProductID" ); } protected void uxSaveButton_Click( object sender, EventArgs e ) { try { string[] result; if (!String.IsNullOrEmpty( uxStatusHidden.Value )) { string checkValue = uxStatusHidden.Value.Replace( "product[]=", "" ); result = checkValue.Split( '&' ); } else { MatchCollection mc; Regex r = new Regex( @"product_(\d+)" ); mc = r.Matches( uxListLabel.Text ); result = new string[mc.Count]; for (int i = 0; i < mc.Count; i++) { result[i] = mc[i].Value.Replace( "product_", "" ); } } DataAccessContext.ProductRepository.UpdateSortOrder( uxCategoryDrop.SelectedValue, result ); PopulateListControls( "SortOrder" ); uxMessage.DisplayMessage( "Update sort order successfully." ); } catch (Exception ex) { uxMessage.DisplayError( ex.Message ); } } protected void uxCancelButton_Click( object sender, EventArgs e ) { MainContext.RedirectMainControl( "ProductList.ascx" ); } private void PopulateControl() { uxRootCategoryDrop.Items.Clear(); IList<Category> rootCategoryList = DataAccessContext.CategoryRepository.GetRootCategory( uxLanguageControl.CurrentCulture, "CategoryID", BoolFilter.ShowAll ); foreach (Category rootCategory in rootCategoryList) { uxRootCategoryDrop.Items.Add( new ListItem( rootCategory.Name, rootCategory.CategoryID ) ); } uxCategoryDrop.Items.Clear(); IList<Category> categoryList = DataAccessContext.CategoryRepository.GetByRootIDLeafOnly( uxLanguageControl.CurrentCulture, uxRootCategoryDrop.SelectedValue, "SortOrder", BoolFilter.ShowAll ); for (int i = 0; i < categoryList.Count; i++) { ListItem listItem = new ListItem( categoryList[i].CreateFullCategoryPath() + " (" + categoryList[i].CategoryID + ")", categoryList[i].CategoryID ); uxCategoryDrop.Items.Add( listItem ); } if (!KeyUtilities.IsMultistoreLicense()) uxRootCategoryFilterPanel.Visible = false; PopulateListControls( "SortOrder" ); } private void PopulateListControls( string sortBy ) { uxListLabel.Text = ""; uxStatusHidden.Value = ""; IList<Product> productList = DataAccessContext.ProductRepository.GetByCategoryID( uxLanguageControl.CurrentCulture, uxCategoryDrop.SelectedValue, sortBy, BoolFilter.ShowTrue, new StoreRetriever().GetCurrentStoreID() ); string productListString = String.Empty; ArrayList productControlID = new ArrayList(); if (productList.Count > 0) { foreach (Product product in productList) { productListString += String.Format( "<li id='product_{0}'>{1} {2}</li>", product.ProductID, product.ProductID, product.Name ); } } uxListLabel.Text = String.Format( "<ul id='sortList'>{0}</ul>", productListString ); if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Test) uxMessage.DisplayMessage( "Test Sort Success" ); } private void Details_RefreshHandler( object sender, EventArgs e ) { PopulateControl(); } private void RegisterJavaScript() { RegisterCustomScript(); } private void RegisterCustomScript() { StringBuilder sb = new StringBuilder(); sb.AppendLine( "$(document).ready(function(){" ); sb.AppendLine( "$(\"#sortList\").sortable({" ); sb.AppendLine( "stop: function() { Sortable_Changed(); }" ); sb.AppendLine( "});" ); sb.AppendLine( "});" ); sb.AppendLine( "function Sortable_Changed()" ); sb.AppendLine( "{" ); sb.AppendLine( "var hiddenfield = document.getElementById( '" + uxStatusHidden.ClientID + "' );" ); sb.AppendLine( "var state = $(\"#sortList\").sortable( 'serialize' )" ); sb.AppendLine( "hiddenfield.value = state;" ); sb.AppendLine( "}" ); // Inside UpdatePanel, Use ScriptManager to register Javascript // Don't use Page.ClientScript.RegisterStartupScript(typeof(Page), "script", sb.ToString(), true); ScriptManager.RegisterStartupScript( this, typeof( Page ), "sortingListScript", sb.ToString(), true ); } protected void uxCategoryDrop_SelectedIndexChanged( object sender, EventArgs e ) { PopulateListControls( "SortOrder" ); } protected void uxRootCategoryDrop_SelectedIndexChanged( object sender, EventArgs e ) { uxCategoryDrop.Items.Clear(); IList<Category> categoryList = DataAccessContext.CategoryRepository.GetByRootIDLeafOnly( uxLanguageControl.CurrentCulture, uxRootCategoryDrop.SelectedValue, "SortOrder", BoolFilter.ShowAll ); for (int i = 0; i < categoryList.Count; i++) { ListItem listItem = new ListItem( categoryList[i].CreateFullCategoryPath() + " (" + categoryList[i].CategoryID + ")", categoryList[i].CategoryID ); uxCategoryDrop.Items.Add( listItem ); } PopulateListControls( "SortOrder" ); } }
namespace AngleSharp.Dom { using AngleSharp.Browser; using AngleSharp.Html.Dom; using AngleSharp.Io; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary> /// Useful methods for document objects. /// </summary> public static class DocumentExtensions { /// <summary> /// Creates an element of the given type or throws an exception, if /// there is no such type. /// </summary> /// <typeparam name="TElement">The type of the element.</typeparam> /// <param name="document">The responsible document.</param> /// <returns>The created element.</returns> public static TElement CreateElement<TElement>(this IDocument document) where TElement : IElement { if (document is null) { throw new ArgumentNullException(nameof(document)); } var type = typeof(BrowsingContext).Assembly.GetTypes() .Where(m => !m.IsAbstract && m.GetInterfaces().Contains(typeof(TElement))) .FirstOrDefault(); if (type != null) { var ctors = type.GetConstructors() .OrderBy(m => m.GetParameters().Length); foreach (var ctor in ctors) { var parameters = ctor.GetParameters(); var arguments = new Object?[parameters.Length]; for (var i = 0; i < parameters.Length; i++) { var isDocument = parameters[i].ParameterType == typeof(Document); arguments[i] = isDocument ? document : parameters[i].DefaultValue; } var obj = ctor.Invoke(arguments); if (obj != null) { var element = (TElement)obj; var baseElement = element as Element; baseElement?.SetupElement(); document.Adopt(element); return element; } } } throw new ArgumentException("No element could be created for the provided interface."); } /// <summary> /// Adopts the given node for the provided document context. /// </summary> /// <param name="document">The new owner of the node.</param> /// <param name="node">The node to change its owner.</param> public static void AdoptNode(this IDocument document, INode node) { if (node is Node adoptedNode) { adoptedNode.Parent?.RemoveChild(adoptedNode, false); adoptedNode.Owner = (document as Document)!; } else { throw new DomException(DomError.NotSupported); } } /// <summary> /// Queues an action in the event loop of the document. /// </summary> /// <param name="document"> /// The document that hosts the configuration. /// </param> /// <param name="action">The action that should be invoked.</param> internal static void QueueTask(this Document document, Action action) => document.Loop!.Enqueue(action); /// <summary> /// Queues an action in the event loop of the document, /// which can be awaited. /// </summary> /// <param name="document"> /// The document that hosts the configuration. /// </param> /// <param name="action">The action that should be invoked.</param> internal static Task QueueTaskAsync(this Document document, Action<CancellationToken> action) => document.Loop!.EnqueueAsync(_ => { action(_); return true; }); /// <summary> /// Queues a function in the event loop of the document, /// which can be awaited with the result returned. /// </summary> /// <param name="document"> /// The document that hosts the configuration. /// </param> /// <param name="func">The function that should be invoked.</param> internal static Task<T> QueueTaskAsync<T>(this Document document, Func<CancellationToken, T> func) => document.Loop!.EnqueueAsync(func); /// <summary> /// Queues a mutation record for the corresponding observers. /// </summary> /// <param name="document">The document to use.</param> /// <param name="record">The record to enqueue.</param> internal static void QueueMutation(this Document document, MutationRecord record) { var observers = document.Mutations.Observers.ToArray(); if (observers.Length > 0) { var nodes = record.Target.GetInclusiveAncestors(); for (var i = 0; i < observers.Length; i++) { var observer = observers[i]; var clearPreviousValue = default(Boolean?); foreach (var node in nodes) { var options = observer.ResolveOptions(node); if (options.IsInvalid || (node != record.Target && !options.IsObservingSubtree) || (record.IsAttribute && !options.IsObservingAttributes) || (record.IsAttribute && options.AttributeFilters != null && (!options.AttributeFilters.Contains(record.AttributeName) || record.AttributeNamespace != null)) || (record.IsCharacterData && !options.IsObservingCharacterData) || (record.IsChildList && !options.IsObservingChildNodes)) { continue; } if (!clearPreviousValue.HasValue || clearPreviousValue.Value) { clearPreviousValue = (record.IsAttribute && !options.IsExaminingOldAttributeValue) || (record.IsCharacterData && !options.IsExaminingOldCharacterData); } } if (clearPreviousValue != null) { observer.Enqueue(record.Copy(clearPreviousValue.Value)); } } document.PerformMicrotaskCheckpoint(); } } /// <summary> /// Adds a transient observer for the given node. /// </summary> /// <param name="document">The document to use.</param> /// <param name="node">The node to be removed.</param> internal static void AddTransientObserver(this Document document, INode node) { var ancestors = node.GetAncestors(); var observers = document.Mutations.Observers; foreach (var ancestor in ancestors) { foreach (var observer in observers) { observer.AddTransient(ancestor, node); } } } /// <summary> /// Applies the manifest to the given document. /// </summary> /// <param name="document">The document to modify.</param> internal static void ApplyManifest(this Document document) { if (document.IsInBrowsingContext) { if (document.DocumentElement is IHtmlHtmlElement root) { var manifest = root.Manifest; //TODO // Replace by algorithm to resolve the value of that attribute // to an absolute URL, relative to the newly created element. var CanResolve = new Predicate<String>(str => false); if (manifest is { Length: > 0 } && CanResolve(manifest)) { // Run the application cache selection algorithm with the // result of applying the URL serializer algorithm to the // resulting parsed URL with the exclude fragment flag set. } else { // Run the application cache selection algorithm with no // manifest. The algorithm must be passed the Document // object. } } } } /// <summary> /// Performs a microtask checkpoint using the mutations host. /// Queue a mutation observer compound microtask. /// </summary> /// <param name="document">The document to use.</param> internal static void PerformMicrotaskCheckpoint(this Document document) => document.Mutations.ScheduleCallback(); /// <summary> /// Provides a stable state by running the synchronous sections of /// asynchronously-running algorithms until the asynchronous algorithm /// can be resumed (if appropriate). /// </summary> /// <param name="document">The document to use.</param> internal static void ProvideStableState(this Document document) { //TODO } /// <summary> /// Checks if the document is waiting for a script to finish preparing. /// </summary> /// <param name="document">The document to use.</param> /// <returns>Enumerable of awaitable tasks.</returns> public static IEnumerable<Task> GetScriptDownloads(this IDocument document) => document.Context.GetDownloads<HtmlScriptElement>(); /// <summary> /// Checks if the document has any active stylesheets that block the /// scripts. A style sheet is blocking scripts if the responsible /// element was created by that Document's parser, and the element is /// either a style element or a link element that was an external /// resource link that contributes to the styling processing model when /// the element was created by the parser, and the element's style /// sheet was enabled when the element was created by the parser, and /// the element's style sheet ready flag is not yet set. /// http://www.w3.org/html/wg/drafts/html/master/document-metadata.html#has-no-style-sheet-that-is-blocking-scripts /// </summary> /// <param name="document">The document to use.</param> /// <returns>Enumerable of awaitable tasks.</returns> public static IEnumerable<Task> GetStyleSheetDownloads(this IDocument document) => document.Context.GetDownloads<HtmlLinkElement>(); /// <summary> /// Spins the event loop until all stylesheets are downloaded (if /// required) and all scripts are ready to be parser executed. /// http://www.w3.org/html/wg/drafts/html/master/syntax.html#the-end /// (bullet 3) /// </summary> /// <param name="document">The document to use.</param> /// <returns>Awaitable task.</returns> public static async Task WaitForReadyAsync(this IDocument document) { var scripts = document.GetScriptDownloads().ToArray(); await Task.WhenAll(scripts).ConfigureAwait(false); var styles = document.GetStyleSheetDownloads().ToArray(); await Task.WhenAll(styles).ConfigureAwait(false); } /// <summary> /// Gets all downloads associated with resources of the document. /// </summary> /// <param name="document">The document hosting the downloads.</param> /// <returns>The collection of elements hosting resources.</returns> public static IEnumerable<IDownload> GetDownloads(this IDocument document) { if (document is null) { throw new ArgumentNullException(nameof(document)); } foreach (var element in document.All) { if (element is ILoadableElement { CurrentDownload: IDownload download }) { yield return download; } } } } }
//----------------------------------------------------------------------- // <copyright file="EntityReader.cs" company="Genesys Source"> // Copyright (c) Genesys Source. All rights reserved. // 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. // </copyright> //----------------------------------------------------------------------- using Genesys.Extensions; using Genesys.Framework.Activity; using Genesys.Framework.Data; using Genesys.Framework.Operation; using System; using System.Data.SqlClient; using System.Linq; using System.Linq.Expressions; namespace Genesys.Framework.Repository { /// <summary> /// EF DbContext for read-only GetBy* operations /// </summary> public partial class EntityReader<TEntity> : IGetOperation<TEntity> where TEntity : EntityInfo<TEntity>, new() { /// <summary> /// Configuration class for dbContext options /// </summary> public IConfigurationEntity<TEntity> ConfigOptions { get; set; } = new ConfigurationEntity<TEntity>(); /// <summary> /// Results from any query operation /// </summary> public IQueryable<TEntity> Results { get; protected set; } = default(IQueryable<TEntity>); /// <summary> /// Can connect to database? /// </summary> public bool CanConnect { get { var returnValue = TypeExtension.DefaultBoolean; using (var connection = new SqlConnection(ConfigOptions.ConnectionString)) { returnValue = connection.CanOpen(); } return returnValue; } } /// <summary> /// Constructor /// </summary> public EntityReader(IConfigurationEntity<TEntity> databaseConfig) : this() { ConfigOptions = databaseConfig; AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Directory.GetCurrentDirectory()); } /// <summary> /// Retrieves data with purpose of displaying results over multiple pages (i.e. in Grid/table) /// </summary> /// <param name="whereClause">Expression for where clause</param> /// <returns></returns> public IQueryable<TEntity> Read(Expression<Func<TEntity, Boolean>> whereClause) { return GetByWhere(whereClause); } /// <summary> /// All data in this datastore subset /// Can add clauses, such as GetAll().Take(1), GetAll().Where(), etc. /// </summary> public IQueryable<TEntity> GetAll() { try { Results = Data; } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetAll()"); throw; } return Results; } /// <summary> /// All data in this datastore subset, except records with default Id/Key /// Criteria: Where Id != TypeExtension.DefaultInteger And Also Key != TypeExtension.DefaultGuid /// Goal: To exclude "Not Selected" records from lookup tables /// </summary> public IQueryable<TEntity> GetAllExcludeDefault() { try { Results = Data.Where(x => x.Id != TypeExtension.DefaultInteger && x.Key != TypeExtension.DefaultGuid); } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetAllExcludeDefault()"); throw; } return Results; } /// <summary> /// Gets database record with exact Id match /// </summary> /// <param name="id">Database Id of the record to pull</param> /// <returns>Single entity that matches by id, or an empty entity for not found</returns> public TEntity GetById(int id) { try { Results = Data.Where(x => x.Id == id); } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetById()"); throw; } return Results.FirstOrDefaultSafe(); } /// <summary> /// Gets database record with exact Key match /// </summary> /// <param name="key">Database Key of the record to pull</param> /// <returns>Single entity that matches by Key, or an empty entity for not found</returns> public TEntity GetByKey(Guid key) { try { Results = Data.Where(x => x.Key == key); } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetByKey()"); throw; } return Results.FirstOrDefaultSafe(); ; } /// <summary> /// Retrieves data with purpose of displaying results over multiple pages (i.e. in Grid/table) /// </summary> /// <param name="whereClause">Expression for where clause</param> /// <returns></returns> public IQueryable<TEntity> GetByWhere(Expression<Func<TEntity, Boolean>> whereClause) { try { Results = (whereClause != null) ? Data.Where<TEntity>(whereClause) : Data; } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetByWhere()"); throw; } return Results; } /// <summary> /// Retrieves data with purpose of displaying results over multiple pages (i.e. in Grid/table) /// </summary> /// <param name="whereClause">Expression for where clause</param> /// <param name="orderByClause">Expression for order by clause</param> /// <param name="pageSize">Size of each result</param> /// <param name="pageNumber">Page number</param> /// <returns>Page of data, based on passed clauses and page parameters</returns> public IQueryable<TEntity> GetByPage(Expression<Func<TEntity, bool>> whereClause, Expression<Func<TEntity, object>> orderByClause, int pageSize, int pageNumber) { var returnValue = default(IQueryable<TEntity>); try { returnValue = (Data).AsQueryable(); returnValue = (whereClause != null) ? returnValue.Where<TEntity>(whereClause).AsQueryable() : returnValue; returnValue = (orderByClause != null) ? returnValue.OrderBy(orderByClause).AsQueryable() : returnValue; returnValue = (pageNumber > 0 && pageSize > 0) ? returnValue.Skip(((pageNumber - 1) * pageSize)).Take(pageSize).AsQueryable() : returnValue; } catch (Exception ex) { ExceptionLogWriter.Create(ex, typeof(TEntity), "EntityReader.GetByPage()"); throw; } return returnValue; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // 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 BackgroundAudioShared; using BackgroundAudioShared.Messages; using SDKTemplate; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Media.Playback; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace BackgroundAudio { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario1 : Page { #region Private Fields and Properties private MainPage rootPage; private AutoResetEvent backgroundAudioTaskStarted; private bool _isMyBackgroundTaskRunning = false; private Dictionary<string, BitmapImage> albumArtCache = new Dictionary<string, BitmapImage>(); const int RPC_S_SERVER_UNAVAILABLE = -2147023174; // 0x800706BA /// <summary> /// Gets the information about background task is running or not by reading the setting saved by background task. /// This is used to determine when to start the task and also when to avoid sending messages. /// </summary> private bool IsMyBackgroundTaskRunning { get { if (_isMyBackgroundTaskRunning) return true; string value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.BackgroundTaskState) as string; if (value == null) { return false; } else { try { _isMyBackgroundTaskRunning = EnumHelper.Parse<BackgroundTaskState>(value) == BackgroundTaskState.Running; } catch(ArgumentException) { _isMyBackgroundTaskRunning = false; } return _isMyBackgroundTaskRunning; } } } #endregion /// <summary> /// You should never cache the MediaPlayer and always call Current. It is possible /// for the background task to go away for several different reasons. When it does /// an RPC_S_SERVER_UNAVAILABLE error is thrown. We need to reset the foreground state /// and restart the background task. /// </summary> private MediaPlayer CurrentPlayer { get { MediaPlayer mp = null; int retryCount = 2; while (mp == null && --retryCount >= 0) { try { mp = BackgroundMediaPlayer.Current; } catch (Exception ex) { if (ex.HResult == RPC_S_SERVER_UNAVAILABLE) { // The foreground app uses RPC to communicate with the background process. // If the background process crashes or is killed for any reason RPC_S_SERVER_UNAVAILABLE // is returned when calling Current. We must restart the task, the while loop will retry to set mp. ResetAfterLostBackground(); StartBackgroundAudioTask(); } else { throw; } } } if (mp == null) { throw new Exception("Failed to get a MediaPlayer instance."); } return mp; } } /// <summary> /// The background task did exist, but it has disappeared. Put the foreground back into an initial state. Unfortunately, /// any attempts to unregister things on BackgroundMediaPlayer.Current will fail with the RPC error once the background task has been lost. /// </summary> private void ResetAfterLostBackground() { BackgroundMediaPlayer.Shutdown(); _isMyBackgroundTaskRunning = false; backgroundAudioTaskStarted.Reset(); prevButton.IsEnabled = true; nextButton.IsEnabled = true; ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Unknown.ToString()); playButton.Content = "| |"; try { BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground; } catch (Exception ex) { if (ex.HResult == RPC_S_SERVER_UNAVAILABLE) { throw new Exception("Failed to get a MediaPlayer instance."); } else { throw; } } } public Scenario1() { this.InitializeComponent(); // Always use the cached page this.NavigationCacheMode = NavigationCacheMode.Required; // Create a static song list InitializeSongs(); // Setup the initialization lock backgroundAudioTaskStarted = new AutoResetEvent(false); } void InitializeSongs() { // Album art attribution // Ring01.jpg | Autumn Yellow Leaves | George Hodan // Ring02.jpg | Abstract Background | Larisa Koshkina // Ring03Part1.jpg | Snow Covered Mountains | Petr Kratochvil // Ring03Part2.jpg | Tropical Beach With Palm Trees | Petr Kratochvil // Ring03Part3.jpg | Alyssum Background | Anne Lowe // Initialize the playlist data/view model. // In a production app your data would be sourced from a data store or service. // Add complete tracks var song1 = new SongModel(); song1.Title = "Ring 1"; song1.MediaUri = new Uri("ms-appx:///Assets/Media/Ring01.wma"); song1.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring01.jpg"); playlistView.Songs.Add(song1); var song2 = new SongModel(); song2.Title = "Ring 2"; song2.MediaUri = new Uri("ms-appx:///Assets/Media/Ring02.wma"); song2.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring02.jpg"); playlistView.Songs.Add(song2); // Add gapless for (int i = 1; i <= 3; ++i) { var segment = new SongModel(); segment.Title = "Ring 3 Part " + i; segment.MediaUri = new Uri("ms-appx:///Assets/Media/Ring03Part" + i + ".wma"); segment.AlbumArtUri = new Uri("ms-appx:///Assets/Media/Ring03Part" + i + ".jpg"); playlistView.Songs.Add(segment); } // Pre-cache all album art to facilitate smooth gapless transitions. // A production app would have a more sophisticated object cache. foreach (var song in playlistView.Songs) { var bitmap = new BitmapImage(); bitmap.UriSource = song.AlbumArtUri; albumArtCache[song.AlbumArtUri.ToString()] = bitmap; } } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; // Subscribe to list UI changes playlistView.ItemClick += PlaylistView_ItemClick; // Adding App suspension handlers here so that we can unsubscribe handlers // that access BackgroundMediaPlayer events Application.Current.Suspending += ForegroundApp_Suspending; Application.Current.Resuming += ForegroundApp_Resuming; ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString()); } protected override void OnNavigatedFrom(NavigationEventArgs e) { if(_isMyBackgroundTaskRunning) { RemoveMediaPlayerEventHandlers(); ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Running.ToString()); } base.OnNavigatedFrom(e); } #region Foreground App Lifecycle Handlers /// <summary> /// Read persisted current track information from application settings /// </summary> private Uri GetCurrentTrackIdAfterAppResume() { object value = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId); if (value != null) return new Uri((String)value); else return null; } /// <summary> /// Sends message to background informing app has resumed /// Subscribe to MediaPlayer events /// </summary> void ForegroundApp_Resuming(object sender, object e) { ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Active.ToString()); // Verify the task is running if (IsMyBackgroundTaskRunning) { // If yes, it's safe to reconnect to media play handlers AddMediaPlayerEventHandlers(); // Send message to background task that app is resumed so it can start sending notifications again MessageService.SendMessageToBackground(new AppResumedMessage()); UpdateTransportControls(CurrentPlayer.CurrentState); var trackId = GetCurrentTrackIdAfterAppResume(); txtCurrentTrack.Text = trackId == null ? string.Empty : playlistView.GetSongById(trackId).Title; txtCurrentState.Text = CurrentPlayer.CurrentState.ToString(); } else { playButton.Content = ">"; // Change to play button txtCurrentTrack.Text = string.Empty; txtCurrentState.Text = "Background Task Not Running"; } } /// <summary> /// Send message to Background process that app is to be suspended /// Stop clock and slider when suspending /// Unsubscribe handlers for MediaPlayer events /// </summary> void ForegroundApp_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); // Only if the background task is already running would we do these, otherwise // it would trigger starting up the background task when trying to suspend. if (IsMyBackgroundTaskRunning) { // Stop handling player events immediately RemoveMediaPlayerEventHandlers(); // Tell the background task the foreground is suspended MessageService.SendMessageToBackground(new AppSuspendedMessage()); } // Persist that the foreground app is suspended ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, AppState.Suspended.ToString()); deferral.Complete(); } #endregion #region Background MediaPlayer Event handlers /// <summary> /// MediaPlayer state changed event handlers. /// Note that we can subscribe to events even if Media Player is playing media in background /// </summary> /// <param name="sender"></param> /// <param name="args"></param> async void MediaPlayer_CurrentStateChanged(MediaPlayer sender, object args) { var currentState = sender.CurrentState; // cache outside of completion or you might get a different value await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Update state label txtCurrentState.Text = currentState.ToString(); // Update controls UpdateTransportControls(currentState); }); } /// <summary> /// This event is raised when a message is recieved from BackgroundAudioTask /// </summary> async void BackgroundMediaPlayer_MessageReceivedFromBackground(object sender, MediaPlayerDataReceivedEventArgs e) { TrackChangedMessage trackChangedMessage; if(MessageService.TryParseMessage(e.Data, out trackChangedMessage)) { // When foreground app is active change track based on background message await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // If playback stopped then clear the UI if(trackChangedMessage.TrackId == null) { playlistView.SelectedIndex = -1; albumArt.Source = null; txtCurrentTrack.Text = string.Empty; prevButton.IsEnabled = false; nextButton.IsEnabled = false; return; } var songIndex = playlistView.GetSongIndexById(trackChangedMessage.TrackId); var song = playlistView.Songs[songIndex]; // Update list UI playlistView.SelectedIndex = songIndex; // Update the album art albumArt.Source = albumArtCache[song.AlbumArtUri.ToString()]; // Update song title txtCurrentTrack.Text = song.Title; // Ensure track buttons are re-enabled since they are disabled when pressed prevButton.IsEnabled = true; nextButton.IsEnabled = true; }); return; } BackgroundAudioTaskStartedMessage backgroundAudioTaskStartedMessage; if(MessageService.TryParseMessage(e.Data, out backgroundAudioTaskStartedMessage)) { // StartBackgroundAudioTask is waiting for this signal to know when the task is up and running // and ready to receive messages Debug.WriteLine("BackgroundAudioTask started"); backgroundAudioTaskStarted.Set(); return; } } #endregion #region Button and Control Click Event Handlers private void PlaylistView_ItemClick(object sender, ItemClickEventArgs e) { var song = e.ClickedItem as SongModel; Debug.WriteLine("Clicked item from App: " + song.MediaUri.ToString()); // Start the background task if it wasn't running if (!IsMyBackgroundTaskRunning || MediaPlayerState.Closed == CurrentPlayer.CurrentState) { // First update the persisted start track ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, song.MediaUri.ToString()); ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, new TimeSpan().ToString()); // Start task StartBackgroundAudioTask(); } else { // Switch to the selected track MessageService.SendMessageToBackground(new TrackChangedMessage(song.MediaUri)); } if (MediaPlayerState.Paused == CurrentPlayer.CurrentState) { CurrentPlayer.Play(); } } /// <summary> /// Sends message to the background task to skip to the previous track. /// </summary> private void prevButton_Click(object sender, RoutedEventArgs e) { MessageService.SendMessageToBackground(new SkipPreviousMessage()); // Prevent the user from repeatedly pressing the button and causing // a backlong of button presses to be handled. This button is re-eneabled // in the TrackReady Playstate handler. prevButton.IsEnabled = false; } /// <summary> /// If the task is already running, it will just play/pause MediaPlayer Instance /// Otherwise, initializes MediaPlayer Handlers and starts playback /// track or to pause if we're already playing. /// </summary> private void playButton_Click(object sender, RoutedEventArgs e) { Debug.WriteLine("Play button pressed from App"); if (IsMyBackgroundTaskRunning) { if (MediaPlayerState.Playing == CurrentPlayer.CurrentState) { CurrentPlayer.Pause(); } else if (MediaPlayerState.Paused == CurrentPlayer.CurrentState) { CurrentPlayer.Play(); } else if (MediaPlayerState.Closed == CurrentPlayer.CurrentState) { StartBackgroundAudioTask(); } } else { StartBackgroundAudioTask(); } } /// <summary> /// Tells the background audio agent to skip to the next track. /// </summary> /// <param name="sender">The button</param> /// <param name="e">Click event args</param> private void nextButton_Click(object sender, RoutedEventArgs e) { MessageService.SendMessageToBackground(new SkipNextMessage()); // Prevent the user from repeatedly pressing the button and causing // a backlong of button presses to be handled. This button is re-eneabled // in the TrackReady Playstate handler. nextButton.IsEnabled = false; } private void speedButton_Click(object sender, RoutedEventArgs e) { // Create menu and add commands var popupMenu = new PopupMenu(); popupMenu.Commands.Add(new UICommand("4.0x", command => CurrentPlayer.PlaybackRate = 4.0)); popupMenu.Commands.Add(new UICommand("2.0x", command => CurrentPlayer.PlaybackRate = 2.0)); popupMenu.Commands.Add(new UICommand("1.5x", command => CurrentPlayer.PlaybackRate = 1.5)); popupMenu.Commands.Add(new UICommand("1.0x", command => CurrentPlayer.PlaybackRate = 1.0)); popupMenu.Commands.Add(new UICommand("0.5x", command => CurrentPlayer.PlaybackRate = 0.5)); // Get button transform and then offset it by half the button // width to center. This will show the popup just above the button. var button = (Button)sender; var transform = button.TransformToVisual(null); var point = transform.TransformPoint(new Point(button.Width / 2, 0)); // Show popup var ignoreAsyncResult = popupMenu.ShowAsync(point); } #endregion Button Click Event Handlers #region Media Playback Helper methods private void UpdateTransportControls(MediaPlayerState state) { if (state == MediaPlayerState.Playing) { playButton.Content = "| |"; // Change to pause button } else { playButton.Content = ">"; // Change to play button } } /// <summary> /// Unsubscribes to MediaPlayer events. Should run only on suspend /// </summary> private void RemoveMediaPlayerEventHandlers() { try { BackgroundMediaPlayer.Current.CurrentStateChanged -= this.MediaPlayer_CurrentStateChanged; BackgroundMediaPlayer.MessageReceivedFromBackground -= BackgroundMediaPlayer_MessageReceivedFromBackground; } catch (Exception ex) { if (ex.HResult == RPC_S_SERVER_UNAVAILABLE) { // do nothing } else { throw; } } } /// <summary> /// Subscribes to MediaPlayer events /// </summary> private void AddMediaPlayerEventHandlers() { CurrentPlayer.CurrentStateChanged += this.MediaPlayer_CurrentStateChanged; try { BackgroundMediaPlayer.MessageReceivedFromBackground += BackgroundMediaPlayer_MessageReceivedFromBackground; } catch (Exception ex) { if (ex.HResult == RPC_S_SERVER_UNAVAILABLE) { // Internally MessageReceivedFromBackground calls Current which can throw RPC_S_SERVER_UNAVAILABLE ResetAfterLostBackground(); } else { throw; } } } /// <summary> /// Initialize Background Media Player Handlers and starts playback /// </summary> private void StartBackgroundAudioTask() { AddMediaPlayerEventHandlers(); var startResult = this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { bool result = backgroundAudioTaskStarted.WaitOne(10000); //Send message to initiate playback if (result == true) { MessageService.SendMessageToBackground(new UpdatePlaylistMessage(playlistView.Songs.ToList())); MessageService.SendMessageToBackground(new StartPlaybackMessage()); } else { throw new Exception("Background Audio Task didn't start in expected time"); } }); startResult.Completed = new AsyncActionCompletedHandler(BackgroundTaskInitializationCompleted); } private void BackgroundTaskInitializationCompleted(IAsyncAction action, AsyncStatus status) { if (status == AsyncStatus.Completed) { Debug.WriteLine("Background Audio Task initialized"); } else if (status == AsyncStatus.Error) { Debug.WriteLine("Background Audio Task could not initialized due to an error ::" + action.ErrorCode.ToString()); } } #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; public struct ValX0 {} public struct ValY0 {} public struct ValX1<T> {} public struct ValY1<T> {} public struct ValX2<T,U> {} public struct ValY2<T,U>{} public struct ValX3<T,U,V>{} public struct ValY3<T,U,V>{} public class RefX0 {} public class RefY0 {} public class RefX1<T> {} public class RefY1<T> {} public class RefX2<T,U> {} public class RefY2<T,U>{} public class RefX3<T,U,V>{} public class RefY3<T,U,V>{} public class Outer { public interface IGen<T> { void _Init(T fld1); bool InstVerify(System.Type t1); } } public struct GenInt : Outer.IGen<int> { int Fld1; public void _Init(int fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<int>) ); } return result; } } public struct GenDouble: Outer.IGen<double> { double Fld1; public void _Init(double fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<double>) ); } return result; } } public struct GenString : Outer.IGen<String> { string Fld1; public void _Init(string fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<string>) ); } return result; } } public struct GenObject : Outer.IGen<object> { object Fld1; public void _Init(object fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<object>) ); } return result; } } public struct GenGuid : Outer.IGen<Guid> { Guid Fld1; public void _Init(Guid fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<Guid>) ); } return result; } } public struct GenConstructedReference : Outer.IGen<RefX1<int>> { RefX1<int> Fld1; public void _Init(RefX1<int> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<RefX1<int>>) ); } return result; } } public struct GenConstructedValue: Outer.IGen<ValX1<string>> { ValX1<string> Fld1; public void _Init(ValX1<string> fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<ValX1<string>>) ); } return result; } } public struct Gen1DIntArray : Outer.IGen<int[]> { int[] Fld1; public void _Init(int[] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<int[]>) ); } return result; } } public struct Gen2DStringArray : Outer.IGen<string[,]> { string[,] Fld1; public void _Init(string[,] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<string[,]>) ); } return result; } } public struct GenJaggedObjectArray : Outer.IGen<object[][]> { object[][] Fld1; public void _Init(object[][] fld1) { Fld1 = fld1; } public bool InstVerify(System.Type t1) { bool result = true; if (!(Fld1.GetType().Equals(t1))) { result = false; Console.WriteLine("Failed to verify type of Fld1 in: " + typeof(Outer.IGen<object[][]>) ); } return result; } } public class Test { public static int counter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { Outer.IGen<int> IGenInt = new GenInt(); IGenInt._Init(new int()); Eval(IGenInt.InstVerify(typeof(int))); Outer.IGen<double> IGenDouble = new GenDouble(); IGenDouble._Init(new double()); Eval(IGenDouble.InstVerify(typeof(double))); Outer.IGen<string> IGenString = new GenString(); IGenString._Init("string"); Eval(IGenString.InstVerify(typeof(string))); Outer.IGen<object> IGenObject = new GenObject(); IGenObject._Init(new object()); Eval(IGenObject.InstVerify(typeof(object))); Outer.IGen<Guid> IGenGuid = new GenGuid(); IGenGuid._Init(new Guid()); Eval(IGenGuid.InstVerify(typeof(Guid))); Outer.IGen<RefX1<int>> IGenConstructedReference = new GenConstructedReference(); IGenConstructedReference._Init(new RefX1<int>()); Eval(IGenConstructedReference.InstVerify(typeof(RefX1<int>))); Outer.IGen<ValX1<string>> IGenConstructedValue = new GenConstructedValue(); IGenConstructedValue._Init(new ValX1<string>()); Eval(IGenConstructedValue.InstVerify(typeof(ValX1<string>))); Outer.IGen<int[]> IGen1DIntArray = new Gen1DIntArray(); IGen1DIntArray._Init(new int[1]); Eval(IGen1DIntArray.InstVerify(typeof(int[]))); Outer.IGen<string[,]> IGen2DStringArray = new Gen2DStringArray(); IGen2DStringArray._Init(new string[1,1]); Eval(IGen2DStringArray.InstVerify(typeof(string[,]))); Outer.IGen<object[][]> IGenJaggedObjectArray = new GenJaggedObjectArray(); IGenJaggedObjectArray._Init(new object[1][]); Eval(IGenJaggedObjectArray.InstVerify(typeof(object[][]))); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // X509Chain.cs // namespace System.Security.Cryptography.X509Certificates { using System.Collections; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using _FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; [Flags] public enum X509ChainStatusFlags { NoError = 0x00000000, NotTimeValid = 0x00000001, NotTimeNested = 0x00000002, Revoked = 0x00000004, NotSignatureValid = 0x00000008, NotValidForUsage = 0x00000010, UntrustedRoot = 0x00000020, RevocationStatusUnknown = 0x00000040, Cyclic = 0x00000080, InvalidExtension = 0x00000100, InvalidPolicyConstraints = 0x00000200, InvalidBasicConstraints = 0x00000400, InvalidNameConstraints = 0x00000800, HasNotSupportedNameConstraint = 0x00001000, HasNotDefinedNameConstraint = 0x00002000, HasNotPermittedNameConstraint = 0x00004000, HasExcludedNameConstraint = 0x00008000, PartialChain = 0x00010000, CtlNotTimeValid = 0x00020000, CtlNotSignatureValid = 0x00040000, CtlNotValidForUsage = 0x00080000, OfflineRevocation = 0x01000000, NoIssuanceChainPolicy = 0x02000000, ExplicitDistrust = 0x04000000, HasNotSupportedCriticalExtension = 0x08000000, HasWeakSignature = 0x00100000, } public struct X509ChainStatus { private X509ChainStatusFlags m_status; private string m_statusInformation; public X509ChainStatusFlags Status { get { return m_status; } set { m_status = value; } } public string StatusInformation { get { if (m_statusInformation == null) return String.Empty; return m_statusInformation; } set { m_statusInformation = value; } } } public class X509Chain { private uint m_status; private X509ChainPolicy m_chainPolicy; private X509ChainStatus[] m_chainStatus; private X509ChainElementCollection m_chainElementCollection; private SafeCertChainHandle m_safeCertChainHandle; private bool m_useMachineContext; private readonly object m_syncRoot = new object(); public static X509Chain Create() { return (X509Chain) CryptoConfig.CreateFromName("X509Chain"); } public X509Chain () : this (false) {} public X509Chain (bool useMachineContext) { m_status = 0; m_chainPolicy = null; m_chainStatus = null; m_chainElementCollection = new X509ChainElementCollection(); m_safeCertChainHandle = SafeCertChainHandle.InvalidHandle; m_useMachineContext = useMachineContext; } // Package protected constructor for creating a chain from a PCCERT_CHAIN_CONTEXT [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public X509Chain (IntPtr chainContext) { if (chainContext == IntPtr.Zero) throw new ArgumentNullException("chainContext"); m_safeCertChainHandle = CAPI.CertDuplicateCertificateChain(chainContext); if (m_safeCertChainHandle == null || m_safeCertChainHandle == SafeCertChainHandle.InvalidHandle) throw new CryptographicException(SR.GetString(SR.Cryptography_InvalidContextHandle), "chainContext"); Init(); } public IntPtr ChainContext { [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { return m_safeCertChainHandle.DangerousGetHandle(); } } public X509ChainPolicy ChainPolicy { get { if (m_chainPolicy == null) m_chainPolicy = new X509ChainPolicy(); return m_chainPolicy; } set { if (value == null) throw new ArgumentNullException("value"); m_chainPolicy = value; } } public X509ChainStatus[] ChainStatus { get { // We give the user a reference to the array since we'll never access it. if (m_chainStatus == null) { if (m_status == 0) { m_chainStatus = new X509ChainStatus[0]; // empty array } else { m_chainStatus = GetChainStatusInformation(m_status); } } return m_chainStatus; } } public X509ChainElementCollection ChainElements { get { return m_chainElementCollection; } } [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public bool Build (X509Certificate2 certificate) { lock (m_syncRoot) { if (certificate == null || certificate.CertContext.IsInvalid) throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "certificate"); // Chain building opens and enumerates the root store to see if the root of the chain is trusted. StorePermission sp = new StorePermission(StorePermissionFlags.OpenStore | StorePermissionFlags.EnumerateCertificates); sp.Demand(); X509ChainPolicy chainPolicy = this.ChainPolicy; if (chainPolicy.RevocationMode == X509RevocationMode.Online) { if (certificate.Extensions[CAPI.szOID_CRL_DIST_POINTS] != null || certificate.Extensions[CAPI.szOID_AUTHORITY_INFO_ACCESS] != null) { // If there is a CDP or AIA extension, we demand unrestricted network access and store add permission // since CAPI can download certificates into the CA store from the network. PermissionSet ps = new PermissionSet(PermissionState.None); ps.AddPermission(new WebPermission(PermissionState.Unrestricted)); ps.AddPermission(new StorePermission(StorePermissionFlags.AddToStore)); ps.Demand(); } } Reset(); int hr = BuildChain(m_useMachineContext ? new IntPtr(CAPI.HCCE_LOCAL_MACHINE) : new IntPtr(CAPI.HCCE_CURRENT_USER), certificate.CertContext, chainPolicy.ExtraStore, chainPolicy.ApplicationPolicy, chainPolicy.CertificatePolicy, chainPolicy.RevocationMode, chainPolicy.RevocationFlag, chainPolicy.VerificationTime, chainPolicy.UrlRetrievalTimeout, ref m_safeCertChainHandle); if (hr != CAPI.S_OK) return false; // Init. Init(); // Verify the chain using the specified policy. CAPI.CERT_CHAIN_POLICY_PARA PolicyPara = new CAPI.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_PARA))); CAPI.CERT_CHAIN_POLICY_STATUS PolicyStatus = new CAPI.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_POLICY_STATUS))); PolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags; if (!CAPI.CertVerifyCertificateChainPolicy(new IntPtr(CAPI.CERT_CHAIN_POLICY_BASE), m_safeCertChainHandle, ref PolicyPara, ref PolicyStatus)) // The API failed. throw new CryptographicException(Marshal.GetLastWin32Error()); CAPI.SetLastError(PolicyStatus.dwError); return (PolicyStatus.dwError == 0); } } [PermissionSetAttribute(SecurityAction.LinkDemand, Unrestricted=true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted=true)] public void Reset () { m_status = 0; m_chainStatus = null; m_chainElementCollection = new X509ChainElementCollection(); if (!m_safeCertChainHandle.IsInvalid) { m_safeCertChainHandle.Dispose(); m_safeCertChainHandle = SafeCertChainHandle.InvalidHandle; } } private unsafe void Init () { using (SafeCertChainHandle safeCertChainHandle = CAPI.CertDuplicateCertificateChain(m_safeCertChainHandle)) { CAPI.CERT_CHAIN_CONTEXT pChain = new CAPI.CERT_CHAIN_CONTEXT(Marshal.SizeOf(typeof(CAPI.CERT_CHAIN_CONTEXT))); uint cbSize = (uint) Marshal.ReadInt32(safeCertChainHandle.DangerousGetHandle()); if (cbSize > Marshal.SizeOf(pChain)) cbSize = (uint) Marshal.SizeOf(pChain); X509Utils.memcpy(m_safeCertChainHandle.DangerousGetHandle(), new IntPtr(&pChain), cbSize); m_status = pChain.dwErrorStatus; Debug.Assert(pChain.cChain > 0); m_chainElementCollection = new X509ChainElementCollection(Marshal.ReadIntPtr(pChain.rgpChain)); } } internal static X509ChainStatus[] GetChainStatusInformation (uint dwStatus) { if (dwStatus == 0) return new X509ChainStatus[0]; int count = 0; for (uint bits = dwStatus; bits != 0; bits = bits >> 1) { if ((bits & 0x1) != 0) count++; } X509ChainStatus[] chainStatus = new X509ChainStatus[count]; int index = 0; foreach (X509ChainErrorMapping mapping in s_x509ChainErrorMappings) { if ((dwStatus & mapping.Win32Flag) != 0) { Debug.Assert(index < chainStatus.Length); chainStatus[index].StatusInformation = X509Utils.GetSystemErrorString(mapping.Win32ErrorCode); chainStatus[index].Status = mapping.ChainStatusFlag; index++; dwStatus &= ~mapping.Win32Flag; } } int shiftCount = 0; for (uint bits = dwStatus; bits != 0; bits = bits >> 1) { if ((bits & 0x1) != 0) { Debug.Assert(index < chainStatus.Length); chainStatus[index].Status = (X509ChainStatusFlags) (1 << shiftCount); chainStatus[index].StatusInformation = SR.GetString(SR.Unknown_Error); index++; } shiftCount++; } Debug.Assert(index == chainStatus.Length); return chainStatus; } // // Builds a certificate chain. // internal static unsafe int BuildChain (IntPtr hChainEngine, SafeCertContextHandle pCertContext, X509Certificate2Collection extraStore, OidCollection applicationPolicy, OidCollection certificatePolicy, X509RevocationMode revocationMode, X509RevocationFlag revocationFlag, DateTime verificationTime, TimeSpan timeout, ref SafeCertChainHandle ppChainContext) { if (pCertContext == null || pCertContext.IsInvalid) throw new ArgumentException(SR.GetString(SR.Cryptography_InvalidContextHandle), "pCertContext"); SafeCertStoreHandle hCertStore = SafeCertStoreHandle.InvalidHandle; if (extraStore != null && extraStore.Count > 0) hCertStore = X509Utils.ExportToMemoryStore(extraStore); CAPI.CERT_CHAIN_PARA ChainPara = new CAPI.CERT_CHAIN_PARA(); // Initialize the structure size. ChainPara.cbSize = (uint) Marshal.SizeOf(ChainPara); SafeLocalAllocHandle applicationPolicyHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle certificatePolicyHandle = SafeLocalAllocHandle.InvalidHandle; try { // Application policy if (applicationPolicy != null && applicationPolicy.Count > 0) { ChainPara.RequestedUsage.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedUsage.Usage.cUsageIdentifier = (uint) applicationPolicy.Count; applicationPolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(applicationPolicy); ChainPara.RequestedUsage.Usage.rgpszUsageIdentifier = applicationPolicyHandle.DangerousGetHandle(); } // Certificate policy if (certificatePolicy != null && certificatePolicy.Count > 0) { ChainPara.RequestedIssuancePolicy.dwType = CAPI.USAGE_MATCH_TYPE_AND; ChainPara.RequestedIssuancePolicy.Usage.cUsageIdentifier = (uint) certificatePolicy.Count; certificatePolicyHandle = X509Utils.CopyOidsToUnmanagedMemory(certificatePolicy); ChainPara.RequestedIssuancePolicy.Usage.rgpszUsageIdentifier = certificatePolicyHandle.DangerousGetHandle(); } ChainPara.dwUrlRetrievalTimeout = (uint) Math.Floor(timeout.TotalMilliseconds); _FILETIME ft = new _FILETIME(); *((long*) &ft) = verificationTime.ToFileTime(); uint flags = X509Utils.MapRevocationFlags(revocationMode, revocationFlag); // Build the chain. if (!CAPI.CertGetCertificateChain(hChainEngine, pCertContext, ref ft, hCertStore, ref ChainPara, flags, IntPtr.Zero, ref ppChainContext)) return Marshal.GetHRForLastWin32Error(); } finally { applicationPolicyHandle.Dispose(); certificatePolicyHandle.Dispose(); } return CAPI.S_OK; } private struct X509ChainErrorMapping { public readonly uint Win32Flag; public readonly int Win32ErrorCode; public readonly X509ChainStatusFlags ChainStatusFlag; public X509ChainErrorMapping(uint win32Flag, int win32ErrorCode, X509ChainStatusFlags chainStatusFlag) { Win32Flag = win32Flag; Win32ErrorCode = win32ErrorCode; ChainStatusFlag = chainStatusFlag; } } private static readonly X509ChainErrorMapping[] s_x509ChainErrorMappings = new[] { new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_NOT_SIGNATURE_VALID, CAPI.TRUST_E_CERT_SIGNATURE, X509ChainStatusFlags.NotSignatureValid), new X509ChainErrorMapping(CAPI.CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID, CAPI.TRUST_E_CERT_SIGNATURE, X509ChainStatusFlags.CtlNotSignatureValid), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_UNTRUSTED_ROOT, CAPI.CERT_E_UNTRUSTEDROOT, X509ChainStatusFlags.UntrustedRoot), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_PARTIAL_CHAIN, CAPI.CERT_E_CHAINING, X509ChainStatusFlags.PartialChain), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_REVOKED, CAPI.CRYPT_E_REVOKED, X509ChainStatusFlags.Revoked), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_NOT_VALID_FOR_USAGE, CAPI.CERT_E_WRONG_USAGE, X509ChainStatusFlags.NotValidForUsage), new X509ChainErrorMapping(CAPI.CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE, CAPI.CERT_E_WRONG_USAGE, X509ChainStatusFlags.CtlNotValidForUsage), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_NOT_TIME_VALID, CAPI.CERT_E_EXPIRED, X509ChainStatusFlags.NotTimeValid), new X509ChainErrorMapping(CAPI.CERT_TRUST_CTL_IS_NOT_TIME_VALID, CAPI.CERT_E_EXPIRED, X509ChainStatusFlags.CtlNotTimeValid), new X509ChainErrorMapping(CAPI.CERT_TRUST_INVALID_NAME_CONSTRAINTS, CAPI.CERT_E_INVALID_NAME, X509ChainStatusFlags.InvalidNameConstraints), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT, CAPI.CERT_E_INVALID_NAME, X509ChainStatusFlags.HasNotSupportedNameConstraint), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT, CAPI.CERT_E_INVALID_NAME, X509ChainStatusFlags.HasNotDefinedNameConstraint), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT, CAPI.CERT_E_INVALID_NAME, X509ChainStatusFlags.HasNotPermittedNameConstraint), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT, CAPI.CERT_E_INVALID_NAME, X509ChainStatusFlags.HasExcludedNameConstraint), new X509ChainErrorMapping(CAPI.CERT_TRUST_INVALID_POLICY_CONSTRAINTS, CAPI.CERT_E_INVALID_POLICY, X509ChainStatusFlags.InvalidPolicyConstraints), new X509ChainErrorMapping(CAPI.CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY, CAPI.CERT_E_INVALID_POLICY, X509ChainStatusFlags.NoIssuanceChainPolicy), new X509ChainErrorMapping(CAPI.CERT_TRUST_INVALID_BASIC_CONSTRAINTS, CAPI.TRUST_E_BASIC_CONSTRAINTS, X509ChainStatusFlags.InvalidBasicConstraints), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_NOT_TIME_NESTED, CAPI.CERT_E_VALIDITYPERIODNESTING, X509ChainStatusFlags.NotTimeNested), new X509ChainErrorMapping(CAPI.CERT_TRUST_REVOCATION_STATUS_UNKNOWN, CAPI.CRYPT_E_NO_REVOCATION_CHECK, X509ChainStatusFlags.RevocationStatusUnknown), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_OFFLINE_REVOCATION, CAPI.CRYPT_E_REVOCATION_OFFLINE, X509ChainStatusFlags.OfflineRevocation), new X509ChainErrorMapping(CAPI.CERT_TRUST_IS_EXPLICIT_DISTRUST, CAPI.TRUST_E_EXPLICIT_DISTRUST, X509ChainStatusFlags.ExplicitDistrust), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT, CAPI.CERT_E_CRITICAL, X509ChainStatusFlags.HasNotSupportedCriticalExtension), new X509ChainErrorMapping(CAPI.CERT_TRUST_HAS_WEAK_SIGNATURE, CAPI.CERTSRV_E_WEAK_SIGNATURE_OR_KEY, X509ChainStatusFlags.HasWeakSignature), }; } }
// 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.Reflection.Context.Projection; using System.Reflection.Context.Virtual; namespace System.Reflection.Context.Custom { internal class CustomType : ProjectingType { private IEnumerable<PropertyInfo> _newProperties; public CustomType(Type template, CustomReflectionContext context) : base(template, context.Projector) { ReflectionContext = context; } public CustomReflectionContext ReflectionContext { get; } // Currently only the results of GetCustomAttributes can be customizaed. // We don't need to override GetCustomAttributesData. public override object[] GetCustomAttributes(bool inherit) { return GetCustomAttributes(typeof(object), inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return AttributeUtils.IsDefined(this, attributeType, inherit); } public override bool IsInstanceOfType(object o) { Type objectType = ReflectionContext.GetTypeForObject(o); return IsAssignableFrom(objectType); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { // list of properties on this type according to the underlying ReflectionContext PropertyInfo[] properties = base.GetProperties(bindingAttr); // Optimization: we currently don't support adding nonpublic or static properties, // so if Public or Instance is not set we don't need to check for new properties. bool getDeclaredOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly; bool getInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance; bool getPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public; if (!getPublic || !getInstance) return properties; List<PropertyInfo> results = new List<PropertyInfo>(properties); //Unlike in runtime reflection, the newly added properties don't hide properties with the same name and signature. results.AddRange(NewProperties); // adding new properties declared on base types if (!getDeclaredOnly) { CustomType baseType = BaseType as CustomType; while (baseType != null) { IEnumerable<PropertyInfo> newProperties = baseType.NewProperties; // We shouldn't add a base type property directly on a subtype. // A new property with a different ReflectedType should be used. foreach (PropertyInfo prop in newProperties) results.Add(new InheritedPropertyInfo(prop, this)); baseType = baseType.BaseType as CustomType; } } return results.ToArray(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { PropertyInfo property = base.GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers); bool getIgnoreCase = (bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase; bool getDeclaredOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly; bool getInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance; bool getPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public; // If the ReflectionContext adds a property with identical name and type to an existing property, // the behavior is unspecified. // In this implementation, we return the existing property. if (!getPublic || !getInstance) return property; // Adding indexer properties is currently not supported. if (types != null && types.Length > 0) return property; List<PropertyInfo> matchingProperties = new List<PropertyInfo>(); if (property != null) matchingProperties.Add(property); // If the ReflectionContext adds two or more properties with the same name and type, // the behavior is unspecified. // In this implementation, we throw AmbiguousMatchException even if the two properties are // defined on different types (base and sub classes). StringComparison comparison = getIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; CustomType type = this; foreach (PropertyInfo newDeclaredProperty in type.NewProperties) { if (string.Equals(newDeclaredProperty.Name, name, comparison)) matchingProperties.Add(newDeclaredProperty); } if (!getDeclaredOnly) { while ((type = type.BaseType as CustomType) != null) { foreach (PropertyInfo newBaseProperty in type.NewProperties) { if (string.Equals(newBaseProperty.Name, name, comparison)) matchingProperties.Add(new InheritedPropertyInfo(newBaseProperty, this)); } } } if (matchingProperties.Count == 0) return null; if (binder == null) binder = Type.DefaultBinder; return binder.SelectProperty(bindingAttr, matchingProperties.ToArray(), returnType, types, modifiers); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { // list of methods on this type according to the underlying ReflectionContext MethodInfo[] methods = base.GetMethods(bindingAttr); // Optimization: we currently don't support adding nonpublic or static property getters or setters, // so if Public or Instance is not set we don't need to check for new properties. bool getDeclaredOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly; bool getInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance; bool getPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public; if (!getPublic || !getInstance) return methods; List<MethodInfo> results = new List<MethodInfo>(methods); // in runtime reflection hidden methods are always returned in GetMethods foreach (PropertyInfo prop in NewProperties) { results.AddRange(prop.GetAccessors()); } // adding new methods declared on base types if (!getDeclaredOnly) { CustomType baseType = BaseType as CustomType; while (baseType != null) { // We shouldn't add a base type method directly on a subtype. // A new method with a different ReflectedType should be used. foreach (PropertyInfo prop in baseType.NewProperties) { PropertyInfo inheritedProperty = new InheritedPropertyInfo(prop, this); results.AddRange(inheritedProperty.GetAccessors()); } baseType = baseType.BaseType as CustomType; } } return results.ToArray(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { MethodInfo method = base.GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); bool getIgnoreCase = (bindingAttr & BindingFlags.IgnoreCase) == BindingFlags.IgnoreCase; bool getDeclaredOnly = (bindingAttr & BindingFlags.DeclaredOnly) == BindingFlags.DeclaredOnly; bool getInstance = (bindingAttr & BindingFlags.Instance) == BindingFlags.Instance; bool getPublic = (bindingAttr & BindingFlags.Public) == BindingFlags.Public; // If the ReflectionContext adds a property with identical name and type to an existing property, // the behavior is unspecified. // In this implementation, we return the existing method. if (!getPublic || !getInstance) return method; bool getPropertyGetter = false; bool getPropertySetter = false; StringComparison comparison = getIgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (name.Length > 4) { // Right now we don't support adding fabricated indexers on types getPropertyGetter = (types == null || types.Length == 0) && name.StartsWith("get_", comparison); if (!getPropertyGetter) getPropertySetter = (types == null || types.Length == 1) && name.StartsWith("set_", comparison); } // not a property getter or setter if (!getPropertyGetter && !getPropertySetter) return method; // get the target property name by removing "get_" or "set_" string targetPropertyName = name.Substring(4); List<MethodInfo> matchingMethods = new List<MethodInfo>(); if (method != null) matchingMethods.Add(method); // in runtime reflection hidden methods are always returned in GetMethods foreach (PropertyInfo newDeclaredProperty in NewProperties) { if (string.Equals(newDeclaredProperty.Name, targetPropertyName, comparison)) { MethodInfo accessor = getPropertyGetter ? newDeclaredProperty.GetGetMethod() : newDeclaredProperty.GetSetMethod(); if (accessor != null) matchingMethods.Add(accessor); } } // adding new methods declared on base types if (!getDeclaredOnly) { CustomType baseType = BaseType as CustomType; while (baseType != null) { // We shouldn't add a base type method directly on a subtype. // A new method with a different ReflectedType should be used. foreach (PropertyInfo newBaseProperty in baseType.NewProperties) { if (string.Equals(newBaseProperty.Name, targetPropertyName, comparison)) { PropertyInfo inheritedProperty = new InheritedPropertyInfo(newBaseProperty, this); MethodInfo accessor = getPropertyGetter ? inheritedProperty.GetGetMethod() : inheritedProperty.GetSetMethod(); if (accessor != null) matchingMethods.Add(accessor); } } baseType = baseType.BaseType as CustomType; } } if (matchingMethods.Count == 0) return null; if (types == null || getPropertyGetter) { Debug.Assert(types == null || types.Length == 0); // matches any signature if (matchingMethods.Count == 1) return matchingMethods[0]; else throw new AmbiguousMatchException(); } else { Debug.Assert(getPropertySetter && types != null && types.Length == 1); if (binder == null) binder = Type.DefaultBinder; return (MethodInfo)binder.SelectMethod(bindingAttr, matchingMethods.ToArray(), types, modifiers); } } private IEnumerable<PropertyInfo> NewProperties { get { if (_newProperties == null) { _newProperties = ReflectionContext.GetNewPropertiesForType(this); } return _newProperties; } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- $pref::GuiEditor::ShowEditorsProfile = true; $GUI_EDITOR_DEFAULT_PROFILE_FILENAME = "art/gui/customProfiles.cs"; $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY = "Other"; function GuiEditor::checkPM( %this ) { if( !isObject( "GuiEditorProfilesPM" ) ) new PersistenceManager( GuiEditorProfilesPM ); } //============================================================================================= // GuiEditor. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditor::createNewProfile( %this, %name, %copySource ) { if( %name $= "" ) return; // Make sure the object name is unique. if( isObject( %name ) ) %name = getUniqueName( %name ); // Create the profile. if( %copySource !$= "" ) eval( "new GuiControlProfile( " @ %name @ " : " @ %copySource.getName() @ " );" ); else eval( "new GuiControlProfile( " @ %name @ " );" ); // Add the item and select it. %category = %this.getProfileCategory( %name ); %group = GuiEditorProfilesTree.findChildItemByName( 0, %category ); %id = GuiEditorProfilesTree.insertItem( %group, %name @ " (" @ %name.getId() @ ")", %name.getId(), "" ); GuiEditorProfilesTree.sort( 0, true, true, false ); GuiEditorProfilesTree.clearSelection(); GuiEditorProfilesTree.selectItem( %id ); // Mark it as needing to be saved. %this.setProfileDirty( %name, true ); } //--------------------------------------------------------------------------------------------- function GuiEditor::getProfileCategory( %this, %profile ) { if( %this.isDefaultProfile( %name ) ) return "Default"; else if( %profile.category !$= "" ) return %profile.category; else return $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY; } //--------------------------------------------------------------------------------------------- function GuiEditor::showDeleteProfileDialog( %this, %profile ) { if( %profile $= "" ) return; if( %profile.isInUse() ) { LabMsgOK( "Error", "The profile '" @ %profile.getName() @ "' is still used by Gui controls." ); return; } LabMsgYesNo( "Delete Profile?", "Do you really want to delete '" @ %profile.getName() @ "'?", "GuiEditor.deleteProfile( " @ %profile @ " );" ); } //--------------------------------------------------------------------------------------------- function GuiEditor::deleteProfile( %this, %profile ) { %this.checkPM(); // Clear dirty state. %this.setProfileDirty( %profile, false ); // Remove from tree. %id = GuiEditorProfilesTree.findItemByValue( %profile.getId() ); GuiEditorProfilesTree.removeItem( %id ); // Remove from file. GuiEditorProfilesPM.removeObjectFromFile( %profile ); // Delete profile object. %profile.delete(); } //--------------------------------------------------------------------------------------------- function GuiEditor::showSaveProfileDialog( %this, %currentFileName ) { getSaveFileName( "TorqueScript Files|*.cs", %this @ ".doSaveProfile", %currentFileName ); } //--------------------------------------------------------------------------------------------- function GuiEditor::doSaveProfile( %this, %fileName ) { %path = makeRelativePath( %fileName, getMainDotCsDir() ); GuiEditorProfileFileName.setText( %path ); %this.saveProfile( GuiEditorProfilesTree.getSelectedProfile(), %path ); } function GuiEditor::forceSaveProfile( %this, %profile ) { %file = %profile.getFileName(); %this.saveProfile( %profile, %file, true ); } //--------------------------------------------------------------------------------------------- function GuiEditor::saveProfile( %this, %profile, %fileName,%forced ) { logc("GuiEditor::saveProfile",%profile.getname(),"Dirty?",GuiEditorProfilesPM.isDirty( %profile )); %this.checkPM(); if( !GuiEditorProfilesPM.isDirty( %profile ) && ( %fileName $= "" || %fileName $= %profile.getFileName() ) && !%forced ) return; //Never save special allignment profiles, use base profile instead (prof_C = 6 char = start at 4 ) %profName = %profile.getName(); %strLen = strlen(%profName); %lastChars = getSubStr(%profName,%strLen - 2); if (%lastChars $= "_C" || %lastChars $= "_R" || %lastChars $= "_L") { %newProf = strreplace(%profName,%lastChars,""); %profile = %newProf; if (!isObject(%profile)) { warnLog("Invalid allignement referenced profile to save:",%profile); return; } } // Update the filename, if requested. if( %fileName !$= "" ) { %profile.setFileName( %fileName ); GuiEditorProfilesPM.setDirty( %profile, %fileName ); } //Mud-H Modified to work with GUI style system and save changes to the selected style. //If not Style profile object found it will save as usual: GuiEditorProfilesPM.saveDirtyObject( %profile ); // saveSingleProfileStyleChanges(%profile); GuiEditorProfilesPM.saveDirtyObject( %profile ); // Save the object. // Clear its dirty state. %this.setProfileDirty( %profile, false, true ); } //--------------------------------------------------------------------------------------------- function GuiEditor::revertProfile( %this, %profile ) { // Revert changes. GuiEditorProfileChangeManager.revertEdits( %profile ); // Clear its dirty state. %this.setProfileDirty( %profile, false ); // Refresh inspector. if( GuiEditorProfileInspector.getInspectObject() == %profile ) GuiEditorProfileInspector.refresh(); } //--------------------------------------------------------------------------------------------- function GuiEditor::isProfileDirty( %this, %profile ) { if( !isObject( "GuiEditorProfilesPM" ) ) return false; return GuiEditorProfilesPM.isDirty( %profile ); } //--------------------------------------------------------------------------------------------- function fixNameId(%pid) { %id = GuiEditorProfilesTree.findItemByValue(%pid ); %name = GuiEditorProfilesTree.getItemText( %id ); %fixName = strreplace(%name," *",""); GuiEditorProfilesTree.editItem( %id, %fixName, %pid ); } function GuiEditor::setProfileDirty( %this, %profile, %value, %noCheck ) { logd("GuiEditor::setProfileDirty",%profile.getname(),"Value?",%value); %this.checkPM(); if( %value ) { if( !GuiEditorProfilesPM.isDirty( %profile ) || %noCheck ) { // If the profile hasn't yet been associated with a file, // put it in the default file. if( %profile.getFileName() $= "" ) %profile.setFileName( $GUI_EDITOR_DEFAULT_PROFILE_FILENAME ); // Add the profile to the dirty set. GuiEditorProfilesPM.setDirty( %profile ); // Show the item as dirty in the tree. %id = GuiEditorProfilesTree.findItemByValue( %profile.getId() ); GuiEditorProfilesTree.editItem( %id, GuiEditorProfilesTree.getItemText( %id ) SPC "*", %profile.getId() ); // Count the number of unsaved profiles. If this is // the first one, indicate in the window title that // we have unsaved profiles. %this.increaseNumDirtyProfiles(); } } else { if( GuiEditorProfilesPM.isDirty( %profile ) || %noCheck ) { // Remove from dirty list. GuiEditorProfilesPM.removeDirty( %profile ); // Clear the dirty marker in the tree. %id = GuiEditorProfilesTree.findItemByValue( %profile.getId() ); %text = GuiEditorProfilesTree.getItemText( %id ); GuiEditorProfilesTree.editItem( %id, getSubStr( %text, 0, strlen( %text ) - 2 ), %profile.getId() ); // Count saved profiles. If this was the last unsaved profile, // remove the unsaved changes indicator from the window title. %this.decreaseNumDirtyProfiles(); // Remove saved edits from the change manager. GuiEditorProfileChangeManager.clearEdits( %profile ); } } } //--------------------------------------------------------------------------------------------- /// Return true if the given profile name is the default profile for a /// GuiControl class or if it's the ToolsDefaultProfile. function GuiEditor::isDefaultProfile( %this, %name ) { if( %name $= "ToolsDefaultProfile" ) return true; if( !endsWith( %name, "Profile" ) ) return false; %className = getSubStr( %name, 0, strlen( %name ) - 7 ) @ "Ctrl"; if( !isClass( %className ) ) return false; return true; } //--------------------------------------------------------------------------------------------- function GuiEditor::increaseNumDirtyProfiles( %this ) { %this.numDirtyProfiles ++; if( %this.numDirtyProfiles == 1 ) { %tab = GuiEditorTabBook-->profilesPage; %tab.setText( %tab.text @ " *" ); } } //--------------------------------------------------------------------------------------------- function GuiEditor::decreaseNumDirtyProfiles( %this ) { %this.numDirtyProfiles --; if( !%this.numDirtyProfiles ) { %tab = GuiEditorTabBook-->profilesPage; %title = %tab.text; %title = getSubstr( %title, 0, strlen( %title ) - 2 ); %tab.setText( %title ); } } //============================================================================================= // GuiEditorProfilesTree. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::init( %this ) { %this.clear(); %defaultGroup = %this.insertItem( 0, "Default", -1 ); %otherGroup = %this.insertItem( 0, $GUI_EDITOR_DEFAULT_PROFILE_CATEGORY, -1 ); foreach( %obj in GuiDataGroup ) { if( !%obj.isMemberOfClass( "GuiControlProfile" ) ) continue; // If it's an Editor profile, skip if showing them is not enabled. if( %obj.category $= "Editor" && !GuiEditor.showEditorProfiles && !$pref::GuiEditor::ShowEditorsProfile) continue; // Create a visible name. %name = %obj.getName(); if( %name $= "" ) %name = "<Unnamed>"; %text = %name @ " (" @ %obj.getId() @ ")"; // Find which group to put the control in. %isDefaultProfile = GuiEditor.isDefaultProfile( %name ); if( %isDefaultProfile ) %group = %defaultGroup; else if( %obj.category !$= "" ) { %group = %this.findChildItemByName( 0, %obj.category ); if( !%group ) %group = %this.insertItem( 0, %obj.category ); } else %group = %otherGroup; // Insert the item. %this.insertItem( %group, %text, %obj.getId(), "" ); } %this.sort( 0, true, true, false ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::onSelect( %this, %id ) { %obj = %this.getItemValue( %id ); if( %obj == -1 ) return; GuiEditorProfileInspector.inspect( %obj ); %fileName = %obj.getFileName(); if( %fileName $= "" ) %fileName = $GUI_EDITOR_DEFAULT_PROFILE_FILENAME; GuiEditorProfileFileName.setText( %fileName ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::onUnselect( %this, %id ) { GuiEditorProfileInspector.inspect( 0 ); GuiEditorProfileFileName.setText( "" ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::onProfileRenamed( %this, %profile, %newName ) { %item = %this.findItemByValue( %profile.getId() ); if( %item == -1 ) return; %newText = %newName @ " (" @ %profile.getId() @ ")"; if( GuiEditor.isProfileDirty( %profile ) ) %newText = %newText @ " *"; %this.editItem( %item, %newText, %profile.getId() ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::getSelectedProfile( %this ) { return %this.getItemValue( %this.getSelectedItem() ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfilesTree::setSelectedProfile( %this, %profile ) { %id = %this.findItemByValue( %profile.getId() ); %this.selectItem( %id ); } //============================================================================================= // GuiEditorProfileInspector. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) { GuiEditorProfileFieldInfo.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onFieldAdded( %this, %object, %fieldName ) { GuiEditor.setProfileDirty( %object, true ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onFieldRemoved( %this, %object, %fieldName ) { GuiEditor.setProfileDirty( %object, true ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onFieldRenamed( %this, %object, %oldFieldName, %newFieldName ) { GuiEditor.setProfileDirty( %object, true ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue ) { GuiEditor.setProfileDirty( %object, true ); // If it's the name field, make sure to sync up the treeview. if( %fieldName $= "name" ) GuiEditorProfilesTree.onProfileRenamed( %object, %newValue ); // Add change record. GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue ); // Add undo. pushInstantGroup(); %nameOrClass = %object.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %oldValue; arrayIndex = %arrayIndex; inspectorGui = %this; }; popInstantGroup(); %action.addToManager( GuiEditor.getUndoManager() ); GuiEditor.updateUndoMenu(); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex ) { pushInstantGroup(); %undoManager = GuiEditor.getUndoManager(); %object = %this.getInspectObject(); %nameOrClass = %object.getName(); if( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %object.getFieldValue( %fieldName, %arrayIndex ); arrayIndex = %arrayIndex; inspectorGui = %this; }; %this.currentFieldEditAction = %action; popInstantGroup(); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onInspectorPostFieldModification( %this ) { %action = %this.currentFieldEditAction; %object = %action.objectId; %fieldName = %action.fieldName; %arrayIndex = %action.arrayIndex; %oldValue = %action.fieldValue; %newValue = %object.getFieldValue( %fieldName, %arrayIndex ); // If it's the name field, make sure to sync up the treeview. if( %action.fieldName $= "name" ) GuiEditorProfilesTree.onProfileRenamed( %object, %newValue ); // Add change record. GuiEditorProfileChangeManager.registerEdit( %object, %fieldName, %arrayIndex, %oldValue ); %this.currentFieldEditAction.addToManager( GuiEditor.getUndoManager() ); %this.currentFieldEditAction = ""; GuiEditor.updateUndoMenu(); GuiEditor.setProfileDirty( %object, true ); } //--------------------------------------------------------------------------------------------- function GuiEditorProfileInspector::onInspectorDiscardFieldModification( %this ) { %this.currentFieldEditAction.undo(); %this.currentFieldEditAction.delete(); %this.currentFieldEditAction = ""; } //============================================================================================= // GuiEditorProfileChangeManager. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditorProfileChangeManager::registerEdit( %this, %profile, %fieldName, %arrayIndex, %oldValue ) { // Early-out if we already have a registered edit on the same field. foreach( %obj in %this ) { if( %obj.profile != %profile ) continue; if( %obj.fieldName $= %fieldName && %obj.arrayIndex $= %arrayIndex ) return; } // Create a new change record. new ScriptObject() { parentGroup = %this; profile = %profile; fieldName = %fieldName; arrayIndex = %arrayIndex; oldValue = %oldValue; }; } //--------------------------------------------------------------------------------------------- function GuiEditorProfileChangeManager::clearEdits( %this, %profile ) { for( %i = 0; %i < %this.getCount(); %i ++ ) { %obj = %this.getObject( %i ); if( %obj.profile != %profile ) continue; %obj.delete(); %i --; } } //--------------------------------------------------------------------------------------------- function GuiEditorProfileChangeManager::revertEdits( %this, %profile ) { for( %i = 0; %i < %this.getCount(); %i ++ ) { %obj = %this.getObject( %i ); if( %obj.profile != %profile ) continue; %profile.setFieldValue( %obj.fieldName, %obj.oldValue, %obj.arrayIndex ); %obj.delete(); %i --; } } //--------------------------------------------------------------------------------------------- function GuiEditorProfileChangeManager::getEdits( %this, %profile ) { %set = new SimSet(); foreach( %obj in %this ) if( %obj.profile == %profile ) %set.add( %obj ); return %set; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCReadSubtree : BridgeHelpers { //[Variation("ReadSubtree only works on Element Node")] public void ReadSubtreeOnlyWorksOnElementNode() { XmlReader DataReader = GetReader(); while (DataReader.Read()) { if (DataReader.NodeType != XmlNodeType.Element) { string nodeType = DataReader.NodeType.ToString(); bool flag = true; try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { TestLog.WriteLine("ReadSubtree doesn't throw InvalidOp Exception on NodeType : " + nodeType); throw new TestException(TestResult.Failed, ""); } // now try next read try { DataReader.Read(); } catch (XmlException) { TestLog.WriteLine("Cannot Read after an invalid operation exception"); throw new TestException(TestResult.Failed, ""); } } else { if (DataReader.HasAttributes) { bool flag = true; DataReader.MoveToFirstAttribute(); try { DataReader.ReadSubtree(); } catch (InvalidOperationException) { flag = false; } if (flag) { TestLog.WriteLine("ReadSubtree doesn't throw InvalidOp Exception on Attribute Node Type"); throw new TestException(TestResult.Failed, ""); } //now try next read. try { DataReader.Read(); } catch (XmlException) { TestLog.WriteLine("Cannot Read after an invalid operation exception"); throw new TestException(TestResult.Failed, ""); } } } }//end while } private string _xml = "<root><elem1><elempi/><?pi target?><elem2 xmlns='xyz'><elem/><!--Comment--><x:elem3 xmlns:x='pqr'><elem4 attr4='4'/></x:elem3></elem2></elem1><elem5/><elem6/></root>"; //[Variation("ReadSubtree Test on Root", Priority = 0, Params = new object[] { "root", "", "ELEMENT", "", "", "NONE" })] //[Variation("ReadSubtree Test depth=1", Priority = 0, Params = new object[] { "elem1", "", "ELEMENT", "elem5", "", "ELEMENT" })] //[Variation("ReadSubtree Test depth=2", Priority = 0, Params = new object[] { "elem2", "", "ELEMENT", "elem1", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=3", Priority = 0, Params = new object[] { "x:elem3", "", "ELEMENT", "elem2", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test depth=4", Priority = 0, Params = new object[] { "elem4", "", "ELEMENT", "x:elem3", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test empty element", Priority = 0, Params = new object[] { "elem5", "", "ELEMENT", "elem6", "", "ELEMENT" })] //[Variation("ReadSubtree Test empty element before root", Priority = 0, Params = new object[] { "elem6", "", "ELEMENT", "root", "", "ENDELEMENT" })] //[Variation("ReadSubtree Test PI after element", Priority = 0, Params = new object[] { "elempi", "", "ELEMENT", "pi", "target", "PROCESSINGINSTRUCTION" })] //[Variation("ReadSubtree Test Comment after element", Priority = 0, Params = new object[] { "elem", "", "ELEMENT", "", "Comment", "COMMENT" })] public void v2() { int count = 0; string name = Variation.Params[count++].ToString(); string value = Variation.Params[count++].ToString(); string type = Variation.Params[count++].ToString(); string oname = Variation.Params[count++].ToString(); string ovalue = Variation.Params[count++].ToString(); string otype = Variation.Params[count++].ToString(); XmlReader DataReader = GetReader(new StringReader(_xml)); PositionOnElement(DataReader, name); XmlReader r = DataReader.ReadSubtree(); TestLog.Compare(r.ReadState, ReadState.Initial, "Reader state is not Initial"); TestLog.Compare(r.Name, String.Empty, "Name is not empty"); TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); TestLog.Compare(r.Depth, 0, "Depth is not zero"); r.Read(); TestLog.Compare(r.ReadState, ReadState.Interactive, "Reader state is not Interactive"); TestLog.Compare(r.Name, name, "Subreader name doesn't match"); TestLog.Compare(r.Value, value, "Subreader value doesn't match"); TestLog.Compare(r.NodeType.ToString().ToUpperInvariant(), type, "Subreader nodetype doesn't match"); TestLog.Compare(r.Depth, 0, "Subreader Depth is not zero"); while (r.Read()) ; r.Dispose(); TestLog.Compare(r.ReadState, ReadState.Closed, "Reader state is not Initial"); TestLog.Compare(r.Name, String.Empty, "Name is not empty"); TestLog.Compare(r.NodeType, XmlNodeType.None, "Nodetype is not empty"); DataReader.Read(); TestLog.Compare(DataReader.Name, oname, "Main name doesn't match"); TestLog.Compare(DataReader.Value, ovalue, "Main value doesn't match"); TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), otype, "Main nodetype doesn't match"); DataReader.Dispose(); } //[Variation("Read with entities", Priority = 1)] public void v3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "PLAY"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) { if (r.NodeType == XmlNodeType.EntityReference) { if (r.CanResolveEntity) r.ResolveEntity(); } } r.Dispose(); DataReader.Dispose(); } //[Variation("Inner XML on Subtree reader", Priority = 1)] public void v4() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.ReadInnerXml(), "<elem2 />", "Inner Xml Fails"); TestLog.Compare(r.Read(), false, "Read returns false"); r.Dispose(); DataReader.Dispose(); } //[Variation("Outer XML on Subtree reader", Priority = 1)] public void v5() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.ReadOuterXml(), "<elem1><elem2 /></elem1>", "Outer Xml Fails"); TestLog.Compare(r.Read(), false, "Read returns true"); r.Dispose(); DataReader.Dispose(); } //[Variation("ReadString on Subtree reader", Priority = 1)] public void v6() { string xmlStr = "<elem1><elem2/></elem1>"; XmlReader DataReader = GetReaderStr(xmlStr); PositionOnElement(DataReader, "elem1"); XmlReader r = DataReader.ReadSubtree(); r.Read(); TestLog.Compare(r.Read(), true, "Read returns false"); r.Dispose(); DataReader.Dispose(); } //[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "true" })] //[Variation("Close on inner reader with CloseInput should not close the outer reader", Priority = 1, Params = new object[] { "false" })] public void v7() { XmlReader DataReader = GetReader(); bool ci = Boolean.Parse(Variation.Params[0].ToString()); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = ci; PositionOnElement(DataReader, "elem2"); XmlReader r = DataReader.ReadSubtree(); r.Dispose(); TestLog.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive"); DataReader.Dispose(); } private XmlReader NestRead(XmlReader r) { r.Read(); r.Read(); if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element)) { NestRead(r.ReadSubtree()); } r.Dispose(); return r; } //[Variation("Nested Subtree reader calls", Priority = 2)] public void v8() { string xmlStr = "<elem1><elem2><elem3><elem4><elem5><elem6><elem7><elem8><elem9><elem0></elem0></elem9></elem8></elem7></elem6></elem5></elem4></elem3></elem2></elem1>"; XmlReader r = GetReader(new StringReader(xmlStr)); NestRead(r); TestLog.Compare(r.ReadState, ReadState.Closed, "Reader Read State is not closed"); } //[Variation("ReadSubtree for element depth more than 4K chars", Priority = 2)] public void v100() { ManagedNodeWriter mnw = new ManagedNodeWriter(); mnw.PutPattern("X"); do { mnw.OpenElement(); mnw.CloseElement(); } while (mnw.GetNodes().Length < 4096); mnw.Finish(); XmlReader DataReader = GetReader(new StringReader(mnw.GetNodes())); PositionOnElement(DataReader, "ELEMENT_2"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; r.Dispose(); DataReader.Read(); TestLog.Compare(DataReader.Name, "ELEMENT_1", "Main name doesn't match"); TestLog.Compare(DataReader.Value, "", "Main value doesn't match"); TestLog.Compare(DataReader.NodeType.ToString().ToUpperInvariant(), "ENDELEMENT", "Main nodetype doesn't match"); DataReader.Dispose(); } //[Variation("Multiple Namespaces on Subtree reader", Priority = 1)] public void MultipleNamespacesOnSubtreeReader() { string xmlStr = "<root xmlns:p1='a' xmlns:p2='b'><e p1:a='' p2:a=''></e></root>"; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "e"); XmlReader r = DataReader.ReadSubtree(); while (r.Read()) ; r.Dispose(); DataReader.Dispose(); } //[Variation("Subtree Reader caches the NodeType and reports node type of Attribute on subsequent reads.", Priority = 1)] public void SubtreeReaderCachesNodeTypeAndReportsNodeTypeOfAttributeOnSubsequentReads() { string xmlStr = "<root xmlns='foo'><b blah='blah'/><b/></root>"; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "root"); XmlReader xxr = DataReader.ReadSubtree(); //Now on root. xxr.Read(); TestLog.Compare(xxr.Name, "root", "Root Elem"); TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 1"); TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "XMLNS NT"); TestLog.Compare(xxr.Name, "xmlns", "XMLNS Attr"); TestLog.Compare(xxr.Value, "foo", "XMLNS Value"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 2"); //Now on b. xxr.Read(); TestLog.Compare(xxr.Name, "b", "b Elem"); TestLog.Compare(xxr.MoveToNextAttribute(), true, "MTNA 3"); TestLog.Compare(xxr.NodeType, XmlNodeType.Attribute, "blah NT"); TestLog.Compare(xxr.Name, "blah", "blah Attr"); TestLog.Compare(xxr.Value, "blah", "blah Value"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 4"); // Now on /b. xxr.Read(); TestLog.Compare(xxr.Name, "b", "b EndElem"); TestLog.Compare(xxr.NodeType, XmlNodeType.Element, "b Elem NT"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 5"); xxr.Read(); TestLog.Compare(xxr.Name, "root", "root EndElem"); TestLog.Compare(xxr.NodeType, XmlNodeType.EndElement, "root EndElem NT"); TestLog.Compare(xxr.MoveToNextAttribute(), false, "MTNA 6"); xxr.Dispose(); DataReader.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace KIARA { public delegate void ConnectionMessageDelegate(string data); public delegate void ConnectionCloseDelegate(); public delegate void ConnectionErrorDelegate(string reason); public interface IWebSocketJSONConnection { // Event should be triggered on every new message. event ConnectionMessageDelegate OnMessage; // Event should be triggered when the connection is closed. event ConnectionCloseDelegate OnClose; // Event should be triggered when an error is encountered. event ConnectionErrorDelegate OnError; // Sends a message. bool Send(string message); // Starts receiving messages (and triggering OnMessage). Previous messages should be cached // until this method is called. void Listen(); } public partial class Connection { public Connection(IWebSocketJSONConnection connection) { Implementation = new WebSocketJSONConnectionImplementation(connection); Implementation.OnClose += delegate(string reason) { if (OnClose != null) OnClose(reason); }; } } #region Private implementation internal class WebSocketJSONConnectionImplementation : Connection.IImplementation { public event Connection.CloseDelegate OnClose; public void LoadIDL(string uri) { // TODO(rryk): Load and parse IDL. } public WebSocketJSONConnectionImplementation(IWebSocketJSONConnection connection) { Connection = connection; Connection.OnMessage += HandleMessage; Connection.OnClose += HandleClose; Connection.OnError += HandleError; Connection.Listen(); } public FunctionWrapper GenerateFuncWrapper(string qualifiedMethodName, string typeMapping, Dictionary<string, Delegate> defaultHandlers) { // Validate default handlers. foreach (KeyValuePair<string, Delegate> defaultHandler in defaultHandlers) FunctionCall.ValidateHandler(defaultHandler.Key, defaultHandler.Value); return (FunctionWrapper)delegate(object[] parameters) { int callID = NextCallID++; List<object> callMessage = new List<object>(); callMessage.Add("call"); callMessage.Add(callID); callMessage.Add(qualifiedMethodName); callMessage.AddRange(parameters); string serializedMessage = JsonConvert.SerializeObject(callMessage); Connection.Send(serializedMessage); if (IsOneWay(qualifiedMethodName)) return null; FunctionCall callObj = new FunctionCall(); foreach (KeyValuePair<string, Delegate> defaultHandler in defaultHandlers) callObj.On(defaultHandler.Key, defaultHandler.Value); ActiveCalls.Add(callID, callObj); return callObj; }; } private bool IsOneWay(string qualifiedMethodName) { List<string> onewayMethods = new List<string>{ "omp.connectClient.handshake", "omp.connectInit.useCircuitCode", "omp.connectServer.handshakeReply", "omp.objectSync.updateObject", "omp.objectSync.deleteObject", "omp.objectSync.locationUpdate", "omp.movement.updateAvatarLocation", "omp.movement.updateAvatarMovement", "omp.chatServer.messageFromClient", "omp.chatClient.messageFromServer", "omp.animationServer.startAnimation" }; return onewayMethods.Contains(qualifiedMethodName); } private void HandleMessage(string message) { List<object> data = null; // FIXME: Occasionally we receive JSON with some random bytes appended. The reason is // unclear, but to be safe we ignore messages that have parsing errors. try { data = JsonConvert.DeserializeObject<List<object>>(message); } catch (JsonException) { return; } string msgType = (string)data[0]; if (msgType == "call-reply") { int callID = Convert.ToInt32(data[1]); if (ActiveCalls.ContainsKey(callID)) { bool success = (bool)data[2]; object retValOrException = data[3]; ActiveCalls[callID].SetResult(success ? "result" : "exception", retValOrException); ActiveCalls.Remove(callID); } else { throw new Error(ErrorCode.CONNECTION_ERROR, "Received a response for an unrecognized call id: " + callID); } } else if (msgType == "call") { int callID = Convert.ToInt32(data[1]); string methodName = (string)data[2]; if (RegisteredFunctions.ContainsKey(methodName)) { Delegate nativeMethod = RegisteredFunctions[methodName]; ParameterInfo[] paramInfo = nativeMethod.Method.GetParameters(); if (paramInfo.Length != data.Count - 3) { throw new Error(ErrorCode.INVALID_ARGUMENT, "Incorrect number of arguments for method: " + methodName + ". Expected: " + paramInfo.Length + ". Got: " + (data.Count - 3)); } List<object> parameters = new List<object>(); for (int i = 0; i < paramInfo.Length; i++) { parameters.Add(ConversionUtils.CastJObject( data[i + 3], paramInfo[i].ParameterType)); } object returnValue = null; object exception = null; bool success = true; try { returnValue = nativeMethod.DynamicInvoke(parameters.ToArray()); } catch (Exception e) { exception = e; success = false; } if (!IsOneWay(methodName)) { // Send call-reply message. List<object> callReplyMessage = new List<object>(); callReplyMessage.Add("call-reply"); callReplyMessage.Add(callID); callReplyMessage.Add(success); if (!success) callReplyMessage.Add(exception); else if (nativeMethod.Method.ReturnType != typeof(void)) callReplyMessage.Add(returnValue); Connection.Send(JsonConvert.SerializeObject(callReplyMessage)); } } else { throw new Error(ErrorCode.CONNECTION_ERROR, "Received a call for an unregistered method: " + methodName); } } else throw new Error(ErrorCode.CONNECTION_ERROR, "Unknown message type: " + msgType); } public void HandleClose() { HandleError("Connection closed."); } public void HandleError(string reason) { foreach (KeyValuePair<int, FunctionCall> call in ActiveCalls) call.Value.SetResult("error", reason); ActiveCalls.Clear(); if (OnClose != null) OnClose(reason); } public void RegisterFuncImplementation(string qualifiedMethodName, string typeMapping, Delegate nativeMethod) { RegisteredFunctions[qualifiedMethodName] = nativeMethod; } private IWebSocketJSONConnection Connection; private int NextCallID = 0; private Dictionary<int, FunctionCall> ActiveCalls = new Dictionary<int, FunctionCall>(); private Dictionary<string, Delegate> RegisteredFunctions = new Dictionary<string, Delegate>(); } #endregion }
namespace CleanSqlite { public partial class Sqlite3 { /* ** 2007 August 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** ** This file implements a special kind of sqlite3_file object used ** by SQLite to create journal files if the atomic-write optimization ** is enabled. ** ** The distinctive characteristic of this sqlite3_file is that the ** actual on disk file is created lazily. When the file is created, ** the caller specifies a buffer size for an in-memory buffer to ** be used to service read() and write() requests. The actual file ** on disk is not created or populated until either: ** ** 1) The in-memory representation grows too large for the allocated ** buffer, or ** 2) The sqlite3JournalCreate() function is called. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ #if SQLITE_ENABLE_ATOMIC_WRITE //#include "sqliteInt.h" /* ** A JournalFile object is a subclass of sqlite3_file used by ** as an open file handle for journal files. */ struct JournalFile { sqlite3_io_methods pMethod; /* I/O methods on journal files */ int nBuf; /* Size of zBuf[] in bytes */ string zBuf; /* Space to buffer journal writes */ int iSize; /* Amount of zBuf[] currently used */ int flags; /* xOpen flags */ sqlite3_vfs pVfs; /* The "real" underlying VFS */ sqlite3_file pReal; /* The "real" underlying file descriptor */ string zJournal; /* Name of the journal file */ }; typedef struct JournalFile JournalFile; /* ** If it does not already exists, create and populate the on-disk file ** for JournalFile p. */ static int createFile(JournalFile p){ int rc = SQLITE_OK; if( null==p.pReal ){ sqlite3_file pReal = (sqlite3_file )&p[1]; rc = sqlite3OsOpen(p.pVfs, p.zJournal, pReal, p.flags, 0); if( rc==SQLITE_OK ){ p.pReal = pReal; if( p.iSize>0 ){ Debug.Assert(p.iSize<=p.nBuf); rc = sqlite3OsWrite(p.pReal, p.zBuf, p.iSize, 0); } } } return rc; } /* ** Close the file. */ static int jrnlClose(sqlite3_file pJfd){ JournalFile p = (JournalFile )pJfd; if( p.pReal ){ sqlite3OsClose(p.pReal); } sqlite3DbFree(db,p.zBuf); return SQLITE_OK; } /* ** Read data from the file. */ static int jrnlRead( sqlite3_file *pJfd, /* The journal file from which to read */ void *zBuf, /* Put the results here */ int iAmt, /* Number of bytes to read */ sqlite_int64 iOfst /* Begin reading at this offset */ ){ int rc = SQLITE_OK; JournalFile *p = (JournalFile )pJfd; if( p->pReal ){ rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst); }else if( (iAmt+iOfst)>p->iSize ){ rc = SQLITE_IOERR_SHORT_READ; }else{ memcpy(zBuf, &p->zBuf[iOfst], iAmt); } return rc; } /* ** Write data to the file. */ static int jrnlWrite( sqlite3_file pJfd, /* The journal file into which to write */ string zBuf, /* Take data to be written from here */ int iAmt, /* Number of bytes to write */ sqlite_int64 iOfst /* Begin writing at this offset into the file */ ){ int rc = SQLITE_OK; JournalFile p = (JournalFile )pJfd; if( null==p.pReal && (iOfst+iAmt)>p.nBuf ){ rc = createFile(p); } if( rc==SQLITE_OK ){ if( p.pReal ){ rc = sqlite3OsWrite(p.pReal, zBuf, iAmt, iOfst); }else{ memcpy(p.zBuf[iOfst], zBuf, iAmt); if( p.iSize<(iOfst+iAmt) ){ p.iSize = (iOfst+iAmt); } } } return rc; } /* ** Truncate the file. */ static int jrnlTruncate(sqlite3_file pJfd, sqlite_int64 size){ int rc = SQLITE_OK; JournalFile p = (JournalFile )pJfd; if( p.pReal ){ rc = sqlite3OsTruncate(p.pReal, size); }else if( size<p.iSize ){ p.iSize = size; } return rc; } /* ** Sync the file. */ static int jrnlSync(sqlite3_file pJfd, int flags){ int rc; JournalFile p = (JournalFile )pJfd; if( p.pReal ){ rc = sqlite3OsSync(p.pReal, flags); }else{ rc = SQLITE_OK; } return rc; } /* ** Query the size of the file in bytes. */ static int jrnlFileSize(sqlite3_file pJfd, sqlite_int64 pSize){ int rc = SQLITE_OK; JournalFile p = (JournalFile )pJfd; if( p.pReal ){ rc = sqlite3OsFileSize(p.pReal, pSize); }else{ pSize = (sqlite_int64) p.iSize; } return rc; } /* ** Table of methods for JournalFile sqlite3_file object. */ static struct sqlite3_io_methods JournalFileMethods = { 1, /* iVersion */ jrnlClose, /* xClose */ jrnlRead, /* xRead */ jrnlWrite, /* xWrite */ jrnlTruncate, /* xTruncate */ jrnlSync, /* xSync */ jrnlFileSize, /* xFileSize */ 0, /* xLock */ 0, /* xUnlock */ 0, /* xCheckReservedLock */ 0, /* xFileControl */ 0, /* xSectorSize */ 0, /* xDeviceCharacteristics */ 0, /* xShmMap */ 0, /* xShmLock */ 0, /* xShmBarrier */ 0 /* xShmUnmap */ }; /* ** Open a journal file. */ int sqlite3JournalOpen( sqlite3_vfs pVfs, /* The VFS to use for actual file I/O */ string zName, /* Name of the journal file */ sqlite3_file pJfd, /* Preallocated, blank file handle */ int flags, /* Opening flags */ int nBuf /* Bytes buffered before opening the file */ ){ JournalFile p = (JournalFile )pJfd; memset(p, 0, sqlite3JournalSize(pVfs)); if( nBuf>0 ){ p.zBuf = sqlite3MallocZero(nBuf); if( null==p.zBuf ){ return SQLITE_NOMEM; } }else{ return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0); } p.pMethod = JournalFileMethods; p.nBuf = nBuf; p.flags = flags; p.zJournal = zName; p.pVfs = pVfs; return SQLITE_OK; } /* ** If the argument p points to a JournalFile structure, and the underlying ** file has not yet been created, create it now. */ int sqlite3JournalCreate(sqlite3_file p){ if( p.pMethods!=&JournalFileMethods ){ return SQLITE_OK; } return createFile((JournalFile )p); } /* ** Return the number of bytes required to store a JournalFile that uses vfs ** pVfs to create the underlying on-disk files. */ int sqlite3JournalSize(sqlite3_vfs pVfs){ return (pVfs->szOsFile+sizeof(JournalFile)); } #endif } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Scoring; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osuTK; namespace osu.Game.Overlays.BeatmapSet.Scores { public class TopScoreStatisticsSection : CompositeDrawable { private const float margin = 10; private readonly FontUsage smallFont = OsuFont.GetFont(size: 20); private readonly FontUsage largeFont = OsuFont.GetFont(size: 25); private readonly TextColumn totalScoreColumn; private readonly TextColumn accuracyColumn; private readonly TextColumn maxComboColumn; private readonly TextColumn ppColumn; private readonly FillFlowContainer<InfoColumn> statisticsColumns; private readonly ModsInfoColumn modsColumn; public TopScoreStatisticsSection() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10, 0), Children = new Drawable[] { new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { statisticsColumns = new FillFlowContainer<InfoColumn> { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), }, ppColumn = new TextColumn("pp", smallFont), modsColumn = new ModsInfoColumn(), } }, new FillFlowContainer { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(margin, 0), Children = new Drawable[] { totalScoreColumn = new TextColumn("total score", largeFont), accuracyColumn = new TextColumn("accuracy", largeFont), maxComboColumn = new TextColumn("max combo", largeFont) } }, } }; } /// <summary> /// Sets the score to be displayed. /// </summary> public ScoreInfo Score { set { totalScoreColumn.Text = $@"{value.TotalScore:N0}"; accuracyColumn.Text = $@"{value.Accuracy:P2}"; maxComboColumn.Text = $@"{value.MaxCombo:N0}x"; ppColumn.Text = $@"{value.PP:N0}"; statisticsColumns.ChildrenEnumerable = value.Statistics.Select(kvp => createStatisticsColumn(kvp.Key, kvp.Value)); modsColumn.Mods = value.Mods; } } private TextColumn createStatisticsColumn(HitResult hitResult, int count) => new TextColumn(hitResult.GetDescription(), smallFont) { Text = count.ToString() }; private class InfoColumn : CompositeDrawable { private readonly Box separator; public InfoColumn(string title, Drawable content) { AutoSizeAxes = Axes.Both; InternalChild = new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Vertical, Spacing = new Vector2(0, 2), Children = new[] { new OsuSpriteText { Font = OsuFont.GetFont(size: 12, weight: FontWeight.Black), Text = title.ToUpper() }, separator = new Box { RelativeSizeAxes = Axes.X, Height = 2 }, content } }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { separator.Colour = colours.Gray5; } } private class TextColumn : InfoColumn { private readonly SpriteText text; public TextColumn(string title, FontUsage font) : this(title, new OsuSpriteText { Font = font }) { } private TextColumn(string title, SpriteText text) : base(title, text) { this.text = text; } public LocalisedString Text { set => text.Text = value; } } private class ModsInfoColumn : InfoColumn { private readonly FillFlowContainer modsContainer; public ModsInfoColumn() : this(new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(1), }) { } private ModsInfoColumn(FillFlowContainer modsContainer) : base("mods", modsContainer) { this.modsContainer = modsContainer; } public IEnumerable<Mod> Mods { set { modsContainer.Clear(); foreach (Mod mod in value) { modsContainer.Add(new ModIcon(mod) { AutoSizeAxes = Axes.Both, Scale = new Vector2(0.3f), }); } } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.Cryptography.X509Certificates.X509Certificate2.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security.Cryptography.X509Certificates { public partial class X509Certificate2 : X509Certificate { #region Methods and constructors public static X509ContentType GetCertContentType(byte[] rawData) { return default(X509ContentType); } public static X509ContentType GetCertContentType(string fileName) { return default(X509ContentType); } public string GetNameInfo(X509NameType nameType, bool forIssuer) { return default(string); } public override void Import(string fileName, System.Security.SecureString password, X509KeyStorageFlags keyStorageFlags) { } public override void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData, System.Security.SecureString password, X509KeyStorageFlags keyStorageFlags) { } public override void Import(byte[] rawData) { } public override void Import(string fileName) { } public override void Reset() { } public override string ToString(bool verbose) { return default(string); } public override string ToString() { return default(string); } public bool Verify() { return default(bool); } public X509Certificate2(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(byte[] rawData, System.Security.SecureString password, X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(string fileName) { } public X509Certificate2(byte[] rawData, System.Security.SecureString password) { } public X509Certificate2() { } public X509Certificate2(byte[] rawData) { } public X509Certificate2(byte[] rawData, string password) { } public X509Certificate2(IntPtr handle) { } public X509Certificate2(X509Certificate certificate) { } protected X509Certificate2(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public X509Certificate2(string fileName, System.Security.SecureString password, X509KeyStorageFlags keyStorageFlags) { } public X509Certificate2(string fileName, string password) { } public X509Certificate2(string fileName, System.Security.SecureString password) { } public X509Certificate2(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { } #endregion #region Properties and indexers public bool Archived { get { return default(bool); } set { } } public X509ExtensionCollection Extensions { get { Contract.Ensures(Contract.Result<System.Security.Cryptography.X509Certificates.X509ExtensionCollection>() != null); return default(X509ExtensionCollection); } } public string FriendlyName { get { return default(string); } set { Contract.Ensures(0 <= value.Length); Contract.Ensures(value.Length <= 1073741822); } } public bool HasPrivateKey { get { return default(bool); } } public X500DistinguishedName IssuerName { get { Contract.Ensures(Contract.Result<System.Security.Cryptography.X509Certificates.X500DistinguishedName>() != null); return default(X500DistinguishedName); } } public DateTime NotAfter { get { return default(DateTime); } } public DateTime NotBefore { get { return default(DateTime); } } public System.Security.Cryptography.AsymmetricAlgorithm PrivateKey { get { return default(System.Security.Cryptography.AsymmetricAlgorithm); } set { } } public PublicKey PublicKey { get { Contract.Ensures(Contract.Result<System.Security.Cryptography.X509Certificates.PublicKey>() != null); return default(PublicKey); } } public byte[] RawData { get { return default(byte[]); } } public string SerialNumber { get { return default(string); } } public System.Security.Cryptography.Oid SignatureAlgorithm { get { Contract.Ensures(Contract.Result<System.Security.Cryptography.Oid>() != null); return default(System.Security.Cryptography.Oid); } } public X500DistinguishedName SubjectName { get { Contract.Ensures(Contract.Result<System.Security.Cryptography.X509Certificates.X500DistinguishedName>() != null); return default(X500DistinguishedName); } } public string Thumbprint { get { return default(string); } } public int Version { get { return default(int); } } #endregion } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; namespace BusinessObjects.MDSubjects { [Serializable] public partial class cMDSubjects_Company: cMDSubjects_Subject<cMDSubjects_Company> { #region Business Methods private static readonly PropertyInfo<System.DateTime?> establishedDateProperty = RegisterProperty<System.DateTime?>(p => p.EstablishedDate, string.Empty, System.DateTime.Now); public System.DateTime? EstablishedDate { get { return GetProperty(establishedDateProperty); } set { SetProperty(establishedDateProperty, value); } } private static readonly PropertyInfo<System.Int32?> mDSubjects_Enums_CompanyTypeIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_Enums_CompanyTypeId, string.Empty, (System.Int32?)null); public System.Int32? MDSubjects_Enums_CompanyTypeId { get { return GetProperty(mDSubjects_Enums_CompanyTypeIdProperty); } set { SetProperty(mDSubjects_Enums_CompanyTypeIdProperty, value); } } private static readonly PropertyInfo<System.Int32?> numberOfEmployeesProperty = RegisterProperty<System.Int32?>(p => p.NumberOfEmployees, string.Empty, (System.Int32?)null); public System.Int32? NumberOfEmployees { get { return GetProperty(numberOfEmployeesProperty); } set { SetProperty(numberOfEmployeesProperty, value); } } private static readonly PropertyInfo<System.Int32?> mDSubjects_Enums_CoreBussinessIdProperty = RegisterProperty<System.Int32?>(p => p.MDSubjects_Enums_CoreBussinessId, string.Empty, (System.Int32?)null); public System.Int32? MDSubjects_Enums_CoreBussinessId { get { return GetProperty(mDSubjects_Enums_CoreBussinessIdProperty); } set { SetProperty(mDSubjects_Enums_CoreBussinessIdProperty, value); } } private static readonly PropertyInfo<System.String> coreBusinessDescriptionProperty = RegisterProperty<System.String>(p => p.CoreBusinessDescription, string.Empty, (System.String)null); public System.String CoreBusinessDescription { get { return GetProperty(coreBusinessDescriptionProperty); } set { SetProperty(coreBusinessDescriptionProperty, (value ?? "").Trim()); } } //private static readonly PropertyInfo<System.String> cRO_OIBProperty = RegisterProperty<System.String>(p => p.CRO_OIB, string.Empty); //[System.ComponentModel.DataAnnotations.StringLength(11, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] //[Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] //public System.String CRO_OIB //{ // get { return GetProperty(cRO_OIBProperty); } // set { SetProperty(cRO_OIBProperty, (value ?? "").Trim()); } //} private static readonly PropertyInfo<System.String> cRO_MBRProperty = RegisterProperty<System.String>(p => p.CRO_MBR, string.Empty, (System.String)null); public System.String CRO_MBR { get { return GetProperty(cRO_MBRProperty); } set { SetProperty(cRO_MBRProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.Int32?> billToAddress_PlaceIdProperty = RegisterProperty<System.Int32?>(p => p.BillToAddress_PlaceId, string.Empty); public System.Int32? BillToAddress_PlaceId { get { return GetProperty(billToAddress_PlaceIdProperty); } set { SetProperty(billToAddress_PlaceIdProperty, value); } } private static readonly PropertyInfo<System.String> billToAddress_StreetProperty = RegisterProperty<System.String>(p => p.BillToAddress_Street, string.Empty, (System.String)null); public System.String BillToAddress_Street { get { return GetProperty(billToAddress_StreetProperty); } set { SetProperty(billToAddress_StreetProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.String> billToAddress_NumberProperty = RegisterProperty<System.String>(p => p.BillToAddress_Number, string.Empty, (System.String)null); public System.String BillToAddress_Number { get { return GetProperty(billToAddress_NumberProperty); } set { SetProperty(billToAddress_NumberProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.String> billToAddress_DescriptionProperty = RegisterProperty<System.String>(p => p.BillToAddress_Description, string.Empty, (System.String)null); public System.String BillToAddress_Description { get { return GetProperty(billToAddress_DescriptionProperty); } set { SetProperty(billToAddress_DescriptionProperty, (value ?? "").Trim()); } } private static readonly PropertyInfo<System.Int32?> pDVTypeProperty = RegisterProperty<System.Int32?>(p => p.PDVType, string.Empty); public System.Int32? PDVType { get { return GetProperty(pDVTypeProperty); } set { SetProperty(pDVTypeProperty, value); } } private static readonly PropertyInfo<System.DateTime?> iS_DateProperty = RegisterProperty<System.DateTime?>(p => p.IS_Date, string.Empty, System.DateTime.Now); public System.DateTime? IS_Date { get { return GetProperty(iS_DateProperty); } set { SetProperty(iS_DateProperty, value); } } private static readonly PropertyInfo<System.Int32?> iS_MDGeneral_Enums_CurrencyIdProperty = RegisterProperty<System.Int32?>(p => p.IS_MDGeneral_Enums_CurrencyId, string.Empty); public System.Int32? IS_MDGeneral_Enums_CurrencyId { get { return GetProperty(iS_MDGeneral_Enums_CurrencyIdProperty); } set { SetProperty(iS_MDGeneral_Enums_CurrencyIdProperty, value); } } private static readonly PropertyInfo<System.Decimal?> iS_CourseProperty = RegisterProperty<System.Decimal?>(p => p.IS_Course, string.Empty, Convert.ToDecimal(1)); public System.Decimal? IS_Course { get { return GetProperty(iS_CourseProperty); } set { SetProperty(iS_CourseProperty, value); } } private static readonly PropertyInfo<System.Decimal?> iS_DemandFromPartnerProperty = RegisterProperty<System.Decimal?>(p => p.IS_DemandFromPartner, string.Empty, Convert.ToDecimal(0)); public System.Decimal? IS_DemandFromPartner { get { return GetProperty(iS_DemandFromPartnerProperty); } set { SetProperty(iS_DemandFromPartnerProperty, value); } } private static readonly PropertyInfo<System.Decimal?> iS_DebitToPartnerProperty = RegisterProperty<System.Decimal?>(p => p.IS_DebitToPartner, string.Empty, Convert.ToDecimal(0)); public System.Decimal? IS_DebitToPartner { get { return GetProperty(iS_DebitToPartnerProperty); } set { SetProperty(iS_DebitToPartnerProperty, value); } } #endregion #region Factory Methods public static cMDSubjects_Company NewMDSubjects_Company() { return DataPortal.Create<cMDSubjects_Company>(); } public static cMDSubjects_Company GetMDSubjects_Company(int uniqueId) { return DataPortal.Fetch<cMDSubjects_Company>(new SingleCriteria<cMDSubjects_Company, int>(uniqueId)); } internal static cMDSubjects_Company GetMDSubjects_Company(MDSubjects_Company data) { return DataPortal.Fetch<cMDSubjects_Company>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Company, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = ctx.ObjectContext.MDSubjects_Subject.OfType<MDSubjects_Company>().First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LoadProperty<Guid>(GUIDProperty, data.GUID); LoadProperty<short>(subjectTypeProperty, data.SubjectType); LoadProperty<string>(nameProperty, data.Name); LoadProperty<string>(longNameProperty, data.LongName); LoadProperty<bool>(residentProperty, data.Resident); LoadProperty<bool?>(isCustomerProperty, data.IsCustomer); LoadProperty<bool?>(isContractorProperty, data.IsContractor); LoadProperty<bool>(inactiveProperty, data.Inactive); LoadProperty<DateTime>(lastActivityDateProperty, data.LastActivityDate); LoadProperty<int>(employeeWhoLastChanedItIdProperty, data.EmployeeWhoLastChanedItId); LoadProperty<int?>(homeAddress_PlaceIdProperty, data.HomeAddress_PlaceId); LoadProperty<string>(homeAddress_StreetProperty, data.HomeAddress_Street); LoadProperty<string>(homeAddress_NumberProperty, data.HomeAddress_Number); LoadProperty<string>(homeAddress_DescriptionProperty, data.HomeAddress_Description); LoadProperty<string>(oIBProperty, data.OIB); LoadProperty<DateTime?>(establishedDateProperty, data.EstablishedDate); LoadProperty<int?>(mDSubjects_Enums_CompanyTypeIdProperty, data.MDSubjects_Enums_CompanyTypeId); LoadProperty<int?>(numberOfEmployeesProperty, data.NumberOfEmployees); LoadProperty<int?>(mDSubjects_Enums_CoreBussinessIdProperty, data.MDSubjects_Enums_CoreBussinessId); LoadProperty<string>(coreBusinessDescriptionProperty, data.CoreBusinessDescription); LoadProperty<string>(cRO_MBRProperty, data.CRO_MBR); LoadProperty<int?>(billToAddress_PlaceIdProperty, data.BillToAddress_PlaceId); LoadProperty<string>(billToAddress_StreetProperty, data.BillToAddress_Street); LoadProperty<string>(billToAddress_NumberProperty, data.BillToAddress_Number); LoadProperty<string>(billToAddress_DescriptionProperty, data.BillToAddress_Description); LoadProperty<int?>(pDVTypeProperty, data.PDVType); LoadProperty<DateTime?>(iS_DateProperty, data.IS_Date); LoadProperty<int?>(iS_MDGeneral_Enums_CurrencyIdProperty, data.IS_MDGeneral_Enums_CurrencyId); LoadProperty<decimal?>(iS_CourseProperty, data.IS_Course); LoadProperty<decimal?>(iS_DemandFromPartnerProperty, data.IS_DemandFromPartner); LoadProperty<decimal?>(iS_DebitToPartnerProperty, data.IS_DebitToPartner); LastChanged = data.LastChanged; LoadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty, cMDSubjects_Subject_AccountsCol.GetcMDSubjects_Subject_AccountsCol(data.MDSubjects_Subject_AccountsCol)); LoadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty, cMDSubjects_Subject_ContactsCol.GetcMDSubjects_Subject_ContactsCol(data.MDSubjects_Subject_ContactsCol)); LoadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty, cMDSubjects_Subject_PermissionsForClientsCol.GetcMDSubjects_Subject_PermissionsForClientsCol(data.MDSubjects_Subject_PermissionsForClientsCol)); BusinessRules.CheckRules(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Company(); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.SubjectType = (short)Common.SubjectType.Company; data.Name = ReadProperty<string>(nameProperty); data.LongName = ReadProperty<string>(longNameProperty); data.Resident = ReadProperty<bool>(residentProperty); data.IsCustomer = ReadProperty<bool?>(isCustomerProperty); data.IsContractor = ReadProperty<bool?>(isContractorProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.EmployeeWhoLastChanedItId = ReadProperty<int>(employeeWhoLastChanedItIdProperty); data.HomeAddress_PlaceId = ReadProperty<int?>(homeAddress_PlaceIdProperty); data.HomeAddress_Street = ReadProperty<string>(homeAddress_StreetProperty); data.HomeAddress_Number = ReadProperty<string>(homeAddress_NumberProperty); data.HomeAddress_Description = ReadProperty<string>(homeAddress_DescriptionProperty); data.OIB = ReadProperty<string>(oIBProperty); data.EstablishedDate = ReadProperty<DateTime?>(establishedDateProperty); data.MDSubjects_Enums_CompanyTypeId = ReadProperty<int?>(mDSubjects_Enums_CompanyTypeIdProperty); data.NumberOfEmployees = ReadProperty<int?>(numberOfEmployeesProperty); data.MDSubjects_Enums_CoreBussinessId = ReadProperty<int?>(mDSubjects_Enums_CoreBussinessIdProperty); data.CoreBusinessDescription = ReadProperty<string>(coreBusinessDescriptionProperty); data.CRO_MBR = ReadProperty<string>(cRO_MBRProperty); data.BillToAddress_PlaceId = ReadProperty<int?>(billToAddress_PlaceIdProperty); data.BillToAddress_Street = ReadProperty<string>(billToAddress_StreetProperty); data.BillToAddress_Number = ReadProperty<string>(billToAddress_NumberProperty); data.BillToAddress_Description = ReadProperty<string>(billToAddress_DescriptionProperty); data.PDVType = ReadProperty<int?>(pDVTypeProperty); data.IS_Date= ReadProperty<DateTime?>(iS_DateProperty); data.IS_MDGeneral_Enums_CurrencyId = ReadProperty<int?>(iS_MDGeneral_Enums_CurrencyIdProperty); data.IS_Course = ReadProperty<decimal?>(iS_CourseProperty); data.IS_DemandFromPartner = ReadProperty<decimal?>(iS_DemandFromPartnerProperty); data.IS_DebitToPartner = ReadProperty<decimal?>(iS_DebitToPartnerProperty); ctx.ObjectContext.AddToMDSubjects_Subject(data); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty), data); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty), data); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty), data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Company(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.CompanyUsingServiceId = ReadProperty<int>(companyUsingServiceIdProperty); data.GUID = ReadProperty<Guid>(GUIDProperty); data.SubjectType = ReadProperty<short>(subjectTypeProperty); data.Name = ReadProperty<string>(nameProperty); data.LongName = ReadProperty<string>(longNameProperty); data.Resident = ReadProperty<bool>(residentProperty); data.IsCustomer = ReadProperty<bool?>(isCustomerProperty); data.IsContractor = ReadProperty<bool?>(isContractorProperty); data.Inactive = ReadProperty<bool>(inactiveProperty); data.LastActivityDate = ReadProperty<DateTime>(lastActivityDateProperty); data.EmployeeWhoLastChanedItId = ReadProperty<int>(employeeWhoLastChanedItIdProperty); data.HomeAddress_PlaceId = ReadProperty<int?>(homeAddress_PlaceIdProperty); data.HomeAddress_Street = ReadProperty<string>(homeAddress_StreetProperty); data.HomeAddress_Number = ReadProperty<string>(homeAddress_NumberProperty); data.HomeAddress_Description = ReadProperty<string>(homeAddress_DescriptionProperty); data.OIB = ReadProperty<string>(oIBProperty); data.EstablishedDate = ReadProperty<DateTime?>(establishedDateProperty); data.MDSubjects_Enums_CompanyTypeId = ReadProperty<int?>(mDSubjects_Enums_CompanyTypeIdProperty); data.NumberOfEmployees = ReadProperty<int?>(numberOfEmployeesProperty); data.MDSubjects_Enums_CoreBussinessId = ReadProperty<int?>(mDSubjects_Enums_CoreBussinessIdProperty); data.CoreBusinessDescription = ReadProperty<string>(coreBusinessDescriptionProperty); data.CRO_MBR = ReadProperty<string>(cRO_MBRProperty); data.BillToAddress_PlaceId = ReadProperty<int?>(billToAddress_PlaceIdProperty); data.BillToAddress_Street = ReadProperty<string>(billToAddress_StreetProperty); data.BillToAddress_Number = ReadProperty<string>(billToAddress_NumberProperty); data.BillToAddress_Description = ReadProperty<string>(billToAddress_DescriptionProperty); data.PDVType = ReadProperty<int?>(pDVTypeProperty); data.IS_Date = ReadProperty<DateTime?>(iS_DateProperty); data.IS_MDGeneral_Enums_CurrencyId = ReadProperty<int?>(iS_MDGeneral_Enums_CurrencyIdProperty); data.IS_Course = ReadProperty<decimal?>(iS_CourseProperty); data.IS_DemandFromPartner = ReadProperty<decimal?>(iS_DemandFromPartnerProperty); data.IS_DebitToPartner = ReadProperty<decimal?>(iS_DebitToPartnerProperty); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_AccountsCol>(MDSubjects_Subject_AccountsColProperty), data); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_ContactsCol>(MDSubjects_Subject_ContactsColProperty), data); DataPortal.UpdateChild(ReadProperty<cMDSubjects_Subject_PermissionsForClientsCol>(MDSubjects_Subject_PermissionsForClientsColProperty), data); ctx.ObjectContext.SaveChanges(); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Threading.Tasks.Channels.Tests { public class TaskChannelTests : TestBase { [Fact] public void Completion_Idempotent() { var t = new TaskCompletionSource<int>().Task; IReadableChannel<int> c = Channel.CreateFromTask(t); Assert.NotNull(c.Completion); Assert.NotSame(t, c.Completion); Assert.Same(c.Completion, c.Completion); } [Fact] public void Precancellation() { IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42)); var cts = new CancellationTokenSource(); cts.Cancel(); AssertSynchronouslyCanceled(c.WaitToReadAsync(cts.Token), cts.Token); AssertSynchronouslyCanceled(c.ReadAsync(cts.Token).AsTask(), cts.Token); } [Fact] public void SuccessTask_BeforeTryRead_Success() { IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42)); AssertSynchronousTrue(c.WaitToReadAsync()); Assert.False(c.Completion.IsCompleted); int result; Assert.True(c.TryRead(out result)); Assert.Equal(42, result); Assert.True(c.Completion.IsCompleted); AssertSynchronousFalse(c.WaitToReadAsync()); Assert.False(c.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task SuccessTask_BeforeReadAsync_Success() { IReadableChannel<int> c = Channel.CreateFromTask(Task.FromResult(42)); AssertSynchronousTrue(c.WaitToReadAsync()); Task<int> read = c.ReadAsync().AsTask(); Assert.Equal(TaskStatus.RanToCompletion, read.Status); Assert.Equal(42, read.Result); AssertSynchronousFalse(c.WaitToReadAsync()); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.ReadAsync().AsTask()); } [Fact] public async Task SuccessTask_AfterReadAsync_Success() { var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); IReadableChannel<int> c = Channel.CreateFromTask(tcs.Task); int result; Assert.False(c.TryRead(out result)); Task<int> read = c.ReadAsync().AsTask(); Assert.False(read.IsCompleted); tcs.SetResult(42); Assert.Equal(42, await read); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.ReadAsync().AsTask()); } [Fact] public async Task SuccessTask_AfterWaitAsync_Success() { var tcs = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); IReadableChannel<int> c = Channel.CreateFromTask(tcs.Task); Task<bool> read = c.WaitToReadAsync(); Assert.False(read.IsCompleted); tcs.SetResult(42); Assert.True(await read); AssertSynchronousTrue(c.WaitToReadAsync()); } [Fact] public async Task FaultedTask_BeforeCreation() { Task<int> t = Task.FromException<int>(new FormatException()); IReadableChannel<int> c = Channel.CreateFromTask(t); Assert.Equal(TaskStatus.Faulted, c.Completion.Status); Assert.Same(t.Exception.InnerException, c.Completion.Exception.InnerException); AssertSynchronousFalse(c.WaitToReadAsync()); await Assert.ThrowsAsync<FormatException>(() => c.ReadAsync().AsTask()); int result; Assert.False(c.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task CanceledTask_BeforeCreation() { Task<int> t = Task.FromCanceled<int>(new CancellationToken(true)); IReadableChannel<int> c = Channel.CreateFromTask(t); Assert.Equal(TaskStatus.Canceled, c.Completion.Status); AssertSynchronousFalse(c.WaitToReadAsync()); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.ReadAsync().AsTask()); int result; Assert.False(c.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task FaultedTask_AfterCreation() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); tcs.SetException(new FormatException()); Assert.Equal(t.Exception.InnerException, await Assert.ThrowsAsync<FormatException>(() => c.Completion)); AssertSynchronousFalse(c.WaitToReadAsync()); await Assert.ThrowsAsync<FormatException>(() => c.ReadAsync().AsTask()); int result; Assert.False(c.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task CanceledTask_AfterCreation() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); tcs.SetCanceled(); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Completion); AssertSynchronousFalse(c.WaitToReadAsync()); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.ReadAsync().AsTask()); int result; Assert.False(c.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task FaultedTask_AfterReadAsync() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); Task<int> read = c.ReadAsync().AsTask(); tcs.SetException(new FormatException()); Assert.Equal(t.Exception.InnerException, await Assert.ThrowsAsync<FormatException>(() => c.Completion)); Assert.Equal(t.Exception.InnerException, await Assert.ThrowsAsync<FormatException>(() => read)); } [Fact] public async Task CanceledTask_AfterReadAsync() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); Task<int> read = c.ReadAsync().AsTask(); tcs.SetCanceled(); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Completion); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => read); } [Fact] public async Task FaultedTask_AfterWaitAsync() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); Task<bool> read = c.WaitToReadAsync(); tcs.SetException(new FormatException()); Assert.Equal(t.Exception.InnerException, await Assert.ThrowsAsync<FormatException>(() => c.Completion)); Assert.False(await read); } [Fact] public async Task CanceledTask_AfterWaitAsync() { var tcs = new TaskCompletionSource<int>(); Task<int> t = tcs.Task; IReadableChannel<int> c = Channel.CreateFromTask(t); Task<bool> read = c.WaitToReadAsync(); tcs.SetCanceled(); await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Completion); Assert.False(await read); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Provider; using Android.Database; using Java.IO; using Android.Webkit; namespace Plugin.FilePicker { public class IOUtil { public static String getPath(Context context, Android.Net.Uri uri) { bool isKitKat = Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat; // DocumentProvider if (isKitKat && DocumentsContract.IsDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { String docId = DocumentsContract.GetDocumentId(uri); String[] split = docId.Split(':'); String type = split[0]; if ("primary".Equals(type, StringComparison.OrdinalIgnoreCase)) { return Android.OS.Environment.ExternalStorageDirectory + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { String id = DocumentsContract.GetDocumentId(uri); Android.Net.Uri contentUri = ContentUris.WithAppendedId( Android.Net.Uri.Parse("content://downloads/public_downloads"), long.Parse(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { String docId = DocumentsContract.GetDocumentId(uri); String[] split = docId.Split(':'); String type = split[0]; Android.Net.Uri contentUri = null; if ("image".Equals(type)) { contentUri = MediaStore.Images.Media.ExternalContentUri; } else if ("video".Equals(type)) { contentUri = MediaStore.Video.Media.ExternalContentUri; } else if ("audio".Equals(type)) { contentUri = MediaStore.Audio.Media.ExternalContentUri; } String selection = "_id=?"; String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase)) { return getDataColumn(context, uri, null, null); } // File else if ("file".Equals(uri.Scheme, StringComparison.OrdinalIgnoreCase)) { return uri.Path; } return null; } public static String getDataColumn(Context context, Android.Net.Uri uri, String selection, String[] selectionArgs) { ICursor cursor = null; String column = "_data"; String[] projection = { column }; try { cursor = context.ContentResolver.Query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.MoveToFirst()) { int column_index = cursor.GetColumnIndexOrThrow(column); return cursor.GetString(column_index); } } finally { if (cursor != null) cursor.Close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static bool isExternalStorageDocument(Android.Net.Uri uri) { return "com.android.externalstorage.documents".Equals(uri.Authority); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static bool isDownloadsDocument(Android.Net.Uri uri) { return "com.android.providers.downloads.documents".Equals(uri.Authority); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static bool isMediaDocument(Android.Net.Uri uri) { return "com.android.providers.media.documents".Equals(uri.Authority); } public static byte[] readFile(String file) { try { return readFile(new File(file)); } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); return new byte[0]; } } public static byte[] readFile(File file) { // Open file RandomAccessFile f = new RandomAccessFile(file, "r"); try { // Get and check length long longlength = f.Length(); int length = (int)longlength; if (length != longlength) throw new IOException("Tamanho do arquivo excede o permitido!"); // Read file and return data byte[] data = new byte[length]; f.ReadFully(data); return data; } catch (Exception ex) { System.Diagnostics.Debug.Write(ex); return new byte[0]; } finally { f.Close(); } } public static string GetMimeType(string url) { String type = null; String extension = MimeTypeMap.GetFileExtensionFromUrl(url); if (extension != null) { type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension); } return type; } } }
// =========================================================== // Copyright (C) 2014-2015 Kendar.org // // 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 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.Net; using System; using System.Collections; using System.Threading.Tasks; using System.Web.Caching; using System.Web; using System.Web.Routing; using System.Threading; using System.Text; using System.IO; using System.Collections.Specialized; using Http.Shared.Contexts; namespace Http.Contexts { public class ListenerHttpResponse : HttpResponseBase, IHttpResponse { public ListenerHttpResponse() { } public object SourceObject { get { return _httpListenerResponse; } } private readonly HttpListenerResponse _httpListenerResponse; public ListenerHttpResponse(HttpListenerResponse httpListenerResponse) { _httpListenerResponse = httpListenerResponse; _httpListenerResponse.SendChunked = true; InitializeUnsettable(); } public override void AddCacheItemDependency(String cacheKey) { //TODO Missing AddCacheItemDependency for HttpListenerResponse } public override void AddCacheItemDependencies(ArrayList cacheKeys) { //TODO Missing AddCacheItemDependencies for HttpListenerResponse } public override void AddCacheItemDependencies(String[] cacheKeys) { //TODO Missing AddCacheItemDependencies for HttpListenerResponse } public override void AddCacheDependency(params CacheDependency[] dependencies) { //TODO Missing AddCacheDependency for HttpListenerResponse } public override void AddFileDependency(String filename) { //TODO Missing AddFileDependency for HttpListenerResponse } public override void AddFileDependencies(ArrayList filenames) { //TODO Missing AddFileDependencies for HttpListenerResponse } public override void AddFileDependencies(String[] filenames) { //TODO Missing AddFileDependencies for HttpListenerResponse } public override void AddHeader(String name, String value) { _httpListenerResponse.AddHeader(name, value); } public override void AppendHeader(String name, String value) { _httpListenerResponse.AppendHeader(name, value); } public override void AppendToLog(String param) { //TODO Missing AppendToLog for HttpListenerResponse } public override String ApplyAppPathModifier(String virtualPath) { //TODO Missing ApplyAppPathModifier for HttpListenerResponse return null; } public override IAsyncResult BeginFlush(AsyncCallback callback, Object state) { //TODO Missing BeginFlush for HttpListenerResponse return null; } public override void BinaryWrite(Byte[] buffer) { _httpListenerResponse.OutputStream.Write(buffer, 0, buffer.Length); } public override void Clear() { //TODO Missing Clear for HttpListenerResponse } public override void ClearContent() { //TODO Missing ClearContent for HttpListenerResponse } public override void ClearHeaders() { _httpListenerResponse.Headers.Clear(); } public override void Close() { _httpListenerResponse.Close(); ContextsManager.OnClose(); } public override void DisableKernelCache() { //TODO Missing DisableKernelCache for HttpListenerResponse } public override void DisableUserCache() { //TODO Missing DisableUserCache for HttpListenerResponse } public override void End() { //TODO Missing End for HttpListenerResponse } public override void EndFlush(IAsyncResult asyncResult) { //TODO Missing EndFlush for HttpListenerResponse } public override void Flush() { //TODO Missing Flush for HttpListenerResponse } public override void Pics(String value) { //TODO Missing Pics for HttpListenerResponse } public override void Redirect(String url) { _httpListenerResponse.Redirect(url); } public override void RedirectToRoute(Object routeValues) { //TODO Missing RedirectToRoute for HttpListenerResponse } public override void RedirectToRoute(String routeName) { //TODO Missing RedirectToRoute for HttpListenerResponse } public override void RedirectToRoute(RouteValueDictionary routeValues) { //TODO Missing RedirectToRoute for HttpListenerResponse } public override void RedirectToRoute(String routeName, Object routeValues) { //TODO Missing RedirectToRoute for HttpListenerResponse } public override void RedirectToRoute(String routeName, RouteValueDictionary routeValues) { //TODO Missing RedirectToRoute for HttpListenerResponse } public override void RedirectToRoutePermanent(Object routeValues) { //TODO Missing RedirectToRoutePermanent for HttpListenerResponse } public override void RedirectToRoutePermanent(String routeName) { //TODO Missing RedirectToRoutePermanent for HttpListenerResponse } public override void RedirectToRoutePermanent(RouteValueDictionary routeValues) { //TODO Missing RedirectToRoutePermanent for HttpListenerResponse } public override void RedirectToRoutePermanent(String routeName, Object routeValues) { //TODO Missing RedirectToRoutePermanent for HttpListenerResponse } public override void RedirectToRoutePermanent(String routeName, RouteValueDictionary routeValues) { //TODO Missing RedirectToRoutePermanent for HttpListenerResponse } public override void RedirectPermanent(String url) { //TODO Missing RedirectPermanent for HttpListenerResponse } public override void RedirectPermanent(String url, Boolean endResponse) { //TODO Missing RedirectPermanent for HttpListenerResponse } public override void RemoveOutputCacheItem(String path) { //TODO Missing RemoveOutputCacheItem for HttpListenerResponse } public override void RemoveOutputCacheItem(String path, String providerName) { //TODO Missing RemoveOutputCacheItem for HttpListenerResponse } public override void TransmitFile(String filename) { //TODO Missing TransmitFile for HttpListenerResponse } public override void TransmitFile(String filename, Int64 offset, Int64 length) { //TODO Missing TransmitFile for HttpListenerResponse } public override void Write(Char ch) { if (ContentEncoding == null) ContentEncoding = Encoding.UTF8; var bytes = ContentEncoding.GetBytes(new[] { ch }); _httpListenerResponse.OutputStream.Write(bytes, 0, bytes.Length); } public override void Write(Char[] buffer, Int32 index, Int32 count) { if (ContentEncoding == null) ContentEncoding = Encoding.UTF8; var bytes = ContentEncoding.GetBytes(buffer); _httpListenerResponse.OutputStream.Write(bytes, index, count); } public override void Write(Object obj) { //TODO Missing Write for HttpListenerResponse } public override void Write(String s) { if (ContentEncoding == null) ContentEncoding = Encoding.UTF8; var bytes = ContentEncoding.GetBytes(s); _httpListenerResponse.OutputStream.Write(bytes, 0, bytes.Length); } public override void WriteFile(String filename) { var response = this; var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); file.CopyToAsync(_httpListenerResponse.OutputStream) .ContinueWith(a => { response.Close(); file.Close(); }); } public override void WriteFile(String filename, Boolean readIntoMemory) { //TODO Missing WriteFile for HttpListenerResponse } public override void WriteFile(String filename, Int64 offset, Int64 size) { //TODO Missing WriteFile for HttpListenerResponse } public override void WriteFile(IntPtr fileHandle, Int64 offset, Int64 size) { //TODO Missing WriteFile for HttpListenerResponse } public override void WriteSubstitution(HttpResponseSubstitutionCallback callback) { //TODO Missing WriteSubstitution for HttpListenerResponse } public override bool Buffer { get; set; } public override bool BufferOutput { get; set; } private HttpCachePolicyBase _cache; public override HttpCachePolicyBase Cache { get { return _cache; } } public void SetCache(HttpCachePolicyBase val) { _cache = val; } public override string CacheControl { get; set; } public override string Charset { get; set; } private CancellationToken _clientDisconnectedToken; public override CancellationToken ClientDisconnectedToken { get { return _clientDisconnectedToken; } } public void SetClientDisconnectedToken(CancellationToken val) { _clientDisconnectedToken = val; } public override Encoding ContentEncoding { set { _httpListenerResponse.ContentEncoding = value; } get { return _httpListenerResponse.ContentEncoding; } } public override String ContentType { set { _httpListenerResponse.ContentType = value; } get { return _httpListenerResponse.ContentType; } } public override int Expires { get; set; } public override DateTime ExpiresAbsolute { get; set; } public override Stream Filter { get; set; } public override NameValueCollection Headers { get { return _httpListenerResponse.Headers; } } public void SetHeaders(NameValueCollection val) { } public override Encoding HeaderEncoding { get; set; } private Boolean _isClientConnected; public override Boolean IsClientConnected { get { return _isClientConnected; } } public void SetIsClientConnected(Boolean val) { _isClientConnected = val; } private Boolean _isRequestBeingRedirected; public override Boolean IsRequestBeingRedirected { get { return _isRequestBeingRedirected; } } public void SetIsRequestBeingRedirected(Boolean val) { _isRequestBeingRedirected = val; } public override TextWriter Output { get; set; } public override Stream OutputStream { get { return _httpListenerResponse.OutputStream; } } public void SetOutputStream(Stream val) { } public override String RedirectLocation { set { _httpListenerResponse.RedirectLocation = value; } get { return _httpListenerResponse.RedirectLocation; } } public override string Status { get; set; } public override Int32 StatusCode { set { _httpListenerResponse.StatusCode = value; } get { return _httpListenerResponse.StatusCode; } } public override String StatusDescription { set { _httpListenerResponse.StatusDescription = value; } get { return _httpListenerResponse.StatusDescription; } } public override int SubStatusCode { get; set; } private Boolean _supportsAsyncFlush; public override Boolean SupportsAsyncFlush { get { return _supportsAsyncFlush; } } public void SetSupportsAsyncFlush(Boolean val) { _supportsAsyncFlush = val; } public override bool SuppressContent { get; set; } public override bool SuppressFormsAuthenticationRedirect { get; set; } public override bool TrySkipIisCustomErrors { get; set; } public void InitializeUnsettable() { _cookies = ConverCookies(_httpListenerResponse.Cookies); //_cache=_httpListenerResponse.Cache; //_clientDisconnectedToken=_httpListenerResponse.ClientDisconnectedToken; //_isClientConnected=_httpListenerResponse.IsClientConnected; //_isRequestBeingRedirected=_httpListenerResponse.IsRequestBeingRedirected; //_supportsAsyncFlush=_httpListenerResponse.SupportsAsyncFlush; } public override void AppendCookie(HttpCookie cookie) { var discard = cookie.Expires.ToUniversalTime() < DateTime.UtcNow; _httpListenerResponse.AppendCookie(new Cookie(cookie.Name, cookie.Value) { Path = "/", Expires = discard ? DateTime.Now.AddDays(-1) : cookie.Expires, Secure = cookie.Secure }); } public override void Redirect(String url, Boolean endResponse) { _httpListenerResponse.Redirect(url); } public override void SetCookie(HttpCookie cookie) { var discard = cookie.Expires.ToUniversalTime() < DateTime.UtcNow; _httpListenerResponse.AppendCookie(new Cookie(cookie.Name, cookie.Value) { Path = "/", Expires = discard ? DateTime.Now.AddDays(-1) : cookie.Expires, Secure = cookie.Secure }); } private HttpCookieCollection _cookies; public override HttpCookieCollection Cookies { get { return _cookies; } } public void SetCookies(HttpCookieCollection val) { } private HttpCookieCollection ConverCookies(CookieCollection cookies) { var cc = new HttpCookieCollection(); foreach (Cookie cookie in cookies) { cc.Add(new HttpCookie(cookie.Name, cookie.Value) { //Domain = cookie.Domain, Expires = cookie.Expires, HttpOnly = cookie.HttpOnly, Path = "/", Secure = cookie.Secure }); } return cc; } public void Close(byte[] data, bool willblock = false) { _httpListenerResponse.Close(data, willblock); } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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. *********************************************************************/ #region license /* DirectShowLib - Provide access to DirectShow interfaces via .NET Copyright (C) 2006 http://sourceforge.net/projects/directshownet/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion using System; using System.Drawing; using System.Runtime.InteropServices; namespace DirectShowLib { #region Declarations /// <summary> /// From MPEG_REQUEST_TYPE /// </summary> public enum MPEGRequestType { // Fields PES_STREAM = 6, SECTION = 1, SECTION_ASYNC = 2, SECTIONS_STREAM = 5, TABLE = 3, TABLE_ASYNC = 4, TS_STREAM = 7, START_MPE_STREAM = 8, UNKNOWN = 0 } /// <summary> /// From MPEG_CONTEXT_TYPE /// </summary> public enum MPEGContextType { BCSDeMux = 0, WinSock = 1 } /// <summary> /// From MPEG_PACKET_LIST /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct MPEGPacketList { public short wPacketCount; public IntPtr PacketList; } /// <summary> /// From DSMCC_FILTER_OPTIONS /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct DSMCCFilterOptions { [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyProtocol; public byte Protocol; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyType; public byte Type; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyMessageId; public short MessageId; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyTransactionId; [MarshalAs(UnmanagedType.Bool)] public bool fUseTrxIdMessageIdMask; public int TransactionId; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyModuleVersion; public byte ModuleVersion; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyBlockNumber; public short BlockNumber; [MarshalAs(UnmanagedType.Bool)] public bool fGetModuleCall; public short NumberOfBlocksInModule; } /// <summary> /// From ATSC_FILTER_OPTIONS /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct ATSCFilterOptions { [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyEtmId; public int EtmId; } /// <summary> /// From MPEG2_FILTER /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public class MPEG2Filter { public byte bVersionNumber; public short wFilterSize; [MarshalAs(UnmanagedType.Bool)] public bool fUseRawFilteringBits; [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)] public byte[] Filter; [MarshalAs(UnmanagedType.ByValArray, SizeConst=16)] public byte[] Mask; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyTableIdExtension; public short TableIdExtension; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyVersion; public byte Version; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifySectionNumber; public byte SectionNumber; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyCurrentNext; [MarshalAs(UnmanagedType.Bool)] public bool fNext; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyDsmccOptions; [MarshalAs(UnmanagedType.Struct)] public DSMCCFilterOptions Dsmcc; [MarshalAs(UnmanagedType.Bool)] public bool fSpecifyAtscOptions; [MarshalAs(UnmanagedType.Struct)] public ATSCFilterOptions Atsc; } /// <summary> /// From unnamed union /// </summary> [StructLayout(LayoutKind.Explicit, Pack=1)] public struct MPEGContextUnion { // Fields [FieldOffset(0)] public BCSDeMux Demux; [FieldOffset(0)] public MPEGWinSock Winsock; } /// <summary> /// From MPEG_BCS_DEMUX /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct BCSDeMux { public int AVMGraphId; } /// <summary> /// From MPEG_WINSOCK /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public struct MPEGWinSock { public int AVMGraphId; } /// <summary> /// From MPEG_CONTEXT /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public class MPEGContext { public MPEGContextType Type; public MPEGContextUnion U; } /// <summary> /// From MPEG_STREAM_BUFFER /// </summary> [StructLayout(LayoutKind.Sequential, Pack=1)] public class MPEGStreamBuffer { //[MarshalAs(UnmanagedType.Error)] public int hr; public int dwDataBufferSize; public int dwSizeOfDataRead; public IntPtr pDataBuffer; } #endregion #region Interfaces [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("9B396D40-F380-4E3C-A514-1A82BF6EBFE6")] public interface IMpeg2Data { [PreserveSig] int GetSection( [In] short pid, [In] byte tid, [In] MPEG2Filter pFilter, [In] int dwTimeout, [MarshalAs(UnmanagedType.Interface)] out ISectionList ppSectionList ); [PreserveSig] int GetTable( [In] short pid, [In] byte tid, [In] MPEG2Filter pFilter, [In] int dwTimeout, [MarshalAs(UnmanagedType.Interface)] out ISectionList ppSectionList ); [PreserveSig] int GetStreamOfSections( [In] short pid, [In] byte tid, [In] MPEG2Filter pFilter, [In] IntPtr hDataReadyEvent, [MarshalAs(UnmanagedType.Interface)] out IMpeg2Stream ppMpegStream ); } [ComImport, Guid("400CC286-32A0-4CE4-9041-39571125A635"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMpeg2Stream { [PreserveSig] int Initialize( [In] MPEGRequestType requestType, [In, MarshalAs(UnmanagedType.Interface)] IMpeg2Data pMpeg2Data, [In, MarshalAs(UnmanagedType.LPStruct)] MPEGContext pContext, [In] short pid, [In] byte tid, [In, MarshalAs(UnmanagedType.LPStruct)] MPEG2Filter pFilter, [In] IntPtr hDataReadyEvent ); [PreserveSig] int SupplyDataBuffer( [In] MPEGStreamBuffer pStreamBuffer ); } [ComImport, Guid("AFEC1EB5-2A64-46C6-BF4B-AE3CCB6AFDB0"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ISectionList { [PreserveSig] int Initialize( [In] MPEGRequestType requestType, [In, MarshalAs(UnmanagedType.Interface)] IMpeg2Data pMpeg2Data, [In, MarshalAs(UnmanagedType.LPStruct)] MPEGContext pContext, [In] short pid, [In] byte tid, [In, MarshalAs(UnmanagedType.LPStruct)] MPEG2Filter pFilter, [In] int timeout, [In] IntPtr hDoneEvent ); [PreserveSig] int InitializeWithRawSections( [In] ref MPEGPacketList pmplSections ); [PreserveSig] int CancelPendingRequest(); [PreserveSig] int GetNumberOfSections( out short pCount ); [PreserveSig] int GetSectionData( [In] short SectionNumber, [Out] out int pdwRawPacketLength, [Out] out IntPtr ppSection // PSECTION* ); [PreserveSig] int GetProgramIdentifier( out short pPid ); [PreserveSig] int GetTableIdentifier( out byte pTableId ); } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for SnapshotsOperations. /// </summary> public static partial class SnapshotsOperationsExtensions { /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> public static Snapshot CreateOrUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot) { return operations.CreateOrUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> CreateOrUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> public static Snapshot Update(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot) { return operations.UpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> UpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static Snapshot Get(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.GetAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Gets information about a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> GetAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse Delete(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.DeleteAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> DeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<Snapshot> ListByResourceGroup(this ISnapshotsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListByResourceGroupAsync(this ISnapshotsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Snapshot> List(this ISnapshotsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListAsync(this ISnapshotsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> public static AccessUri GrantAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData) { return operations.GrantAccessAsync(resourceGroupName, snapshotName, grantAccessData).GetAwaiter().GetResult(); } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessUri> GrantAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GrantAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, grantAccessData, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse RevokeAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.RevokeAccessAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> RevokeAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RevokeAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> public static Snapshot BeginCreateOrUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Put disk operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginCreateOrUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, Snapshot snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> public static Snapshot BeginUpdate(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot) { return operations.BeginUpdateAsync(resourceGroupName, snapshotName, snapshot).GetAwaiter().GetResult(); } /// <summary> /// Updates (patches) a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='snapshot'> /// Snapshot object supplied in the body of the Patch snapshot operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Snapshot> BeginUpdateAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, SnapshotUpdate snapshot, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(resourceGroupName, snapshotName, snapshot, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse BeginDelete(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.BeginDeleteAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> BeginDeleteAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> public static AccessUri BeginGrantAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData) { return operations.BeginGrantAccessAsync(resourceGroupName, snapshotName, grantAccessData).GetAwaiter().GetResult(); } /// <summary> /// Grants access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='grantAccessData'> /// Access data object supplied in the body of the get snapshot access /// operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<AccessUri> BeginGrantAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, GrantAccessData grantAccessData, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGrantAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, grantAccessData, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> public static OperationStatusResponse BeginRevokeAccess(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName) { return operations.BeginRevokeAccessAsync(resourceGroupName, snapshotName).GetAwaiter().GetResult(); } /// <summary> /// Revokes access to a snapshot. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='snapshotName'> /// The name of the snapshot within the given subscription and resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<OperationStatusResponse> BeginRevokeAccessAsync(this ISnapshotsOperations operations, string resourceGroupName, string snapshotName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginRevokeAccessWithHttpMessagesAsync(resourceGroupName, snapshotName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Snapshot> ListByResourceGroupNext(this ISnapshotsOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListByResourceGroupNextAsync(this ISnapshotsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<Snapshot> ListNext(this ISnapshotsOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Lists snapshots under a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Snapshot>> ListNextAsync(this ISnapshotsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Linq; using NUnit.Framework; namespace AGO.WorkQueue.Tests { [TestFixture] public abstract class AbstractQueueConsumptionTest { protected IWorkQueue Queue; protected abstract IWorkQueue CreateQueue(); [SetUp] public virtual void SetUp() { Queue = CreateQueue(); } [TearDown] public virtual void TearDown() { Queue = null; } [Test] public void QueueReturnItemForRequestedProject() { const string proj1 = "proj1"; const string proj2 = "proj2"; var p1Item = new QueueItem("a", Guid.NewGuid(), proj1, "u1"); var p2Item = new QueueItem("a", Guid.NewGuid(), proj2, "u2"); Queue.Add(p2Item); Queue.Add(p1Item); var item = Queue.Get(proj1); Assert.AreEqual(p1Item.Project, item.Project); Assert.AreEqual(p1Item.TaskType, item.TaskType); Assert.AreEqual(p1Item.TaskId, item.TaskId); } [Test] public void QueueReturnNullForNonExistingProject() { const string proj1 = "proj1"; Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, "u")); var item = Queue.Get("non existing project"); Assert.IsNull(item); } [Test] public void QueueReturnTaskForUserWithHigherPriority() { const string proj = "proj1"; const string user1 = "u1"; const string user2 = "u2"; var i1 = new QueueItem("a", Guid.NewGuid(), proj, user1) { PriorityType = 1, UserPriority = 10 }; var i2 = new QueueItem("a", Guid.NewGuid(), proj, user2) { PriorityType = 1, UserPriority = 20 }; Queue.Add(i1); Queue.Add(i2); var item = Queue.Get(proj); Assert.AreEqual(i2.TaskId, item.TaskId); } [Test] public void QueueReturnOldestTaskForUserWhenPrioritiesEquals() { const string proj = "proj1"; const string uid = "u"; var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid) { PriorityType = 1, UserPriority = 10 }; var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid) { PriorityType = 1, UserPriority = 10 }; Queue.Add(i1); Queue.Add(i2); var item = Queue.Get(proj); Assert.AreEqual(i1.TaskId, item.TaskId); } [Test] public void QueueReturnOldestTaskWhenPriorityNotUsed() { const string proj = "proj1"; const string uid = "u"; var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid); //PriorityType = 0 by default, so, not used var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid); Queue.Add(i1); Queue.Add(i2); var item = Queue.Get(proj); Assert.AreEqual(i1.TaskId, item.TaskId); } [Test] public void QueueReturnOldestTaskWhenPriorityNotUsed2() { const string proj = "proj1"; const string uid = "u"; var i1 = new QueueItem("a", Guid.NewGuid(), proj, uid); var i2 = new QueueItem("a", Guid.NewGuid(), proj, uid) { UserPriority = 10}; Queue.Add(i1); Queue.Add(i2); var item = Queue.Get(proj); Assert.AreEqual(i1.TaskId, item.TaskId); } [Test] public void QueueDumpDataAsRawShallowCopyList() { Queue.Add(new QueueItem("a", Guid.NewGuid(), "p1", "u1")); Queue.Add(new QueueItem("a", Guid.NewGuid(), "p2", "u2")); Queue.Add(new QueueItem("a", Guid.NewGuid(), "p3", "u3")); // ReSharper disable PossibleMultipleEnumeration var dump = Queue.Dump(); //special not materialize - test dump is copy, not reference to underlying data Assert.AreEqual(3, dump.Count()); Assert.IsTrue(dump.Any(qi => qi.Project == "p1")); Assert.IsTrue(dump.Any(qi => qi.Project == "p2")); Assert.IsTrue(dump.Any(qi => qi.Project == "p3")); Queue.Clear(); Assert.AreEqual(3, dump.Count()); Assert.IsTrue(dump.Any(qi => qi.Project == "p1")); Assert.IsTrue(dump.Any(qi => qi.Project == "p2")); Assert.IsTrue(dump.Any(qi => qi.Project == "p3")); // ReSharper restore PossibleMultipleEnumeration } [Test] public void QueueCalculateOrderForEachUserTaskInProjectWithPriority() { const string u1 = "u1"; const string u2 = "u2"; const string p1 = "proj1"; const string p2 = "proj2"; const string p3 = "proj3"; var i1 = new QueueItem("a", Guid.NewGuid(), p1, u1){ PriorityType = 1, UserPriority = 20}; var i2 = new QueueItem("a", Guid.NewGuid(), p1, u1) { PriorityType = 1, UserPriority = 20 }; var i3 = new QueueItem("a", Guid.NewGuid(), p1, u1); var i4 = new QueueItem("a", Guid.NewGuid(), p2, u1) {PriorityType = 1, UserPriority = 10}; var i5 = new QueueItem("a", Guid.NewGuid(), p2, u1); var i6 = new QueueItem("a", Guid.NewGuid(), p1, u2) {PriorityType = 1, UserPriority = 40}; var i7 = new QueueItem("a", Guid.NewGuid(), p2, u2) {PriorityType = 1, UserPriority = 10}; var i8 = new QueueItem("a", Guid.NewGuid(), p3, u1); var i9 = new QueueItem("a", Guid.NewGuid(), p3, u2); Queue.Add(i1); Queue.Add(i2); Queue.Add(i3); Queue.Add(i4); Queue.Add(i5); Queue.Add(i6); Queue.Add(i7); Queue.Add(i8); Queue.Add(i9); var snapshot = Queue.Snapshot(); /* * u1: priority 20 in proj1 * u1: priority 10 in proj2 * u2: priority 40 in proj1 * u2: priority 10 in proj2 * * var PriorityType Priority User * proj1 i6 1 40 u2 * i1 1 20 u1 * i2 1 20 u1 * i3 0 -- u1 * * proj2 i4 1 10 u1 * i7 1 10 u2 * i5 0 -- u1 * * proj3 * i8 0 -- u1 * i9 0 -- u2 * * */ Assert.IsNotNull(snapshot); Assert.AreEqual(2, snapshot.Count); //u1 proj1 Assert.AreEqual(i1.TaskId, snapshot[u1][p1][0].TaskId); Assert.AreEqual(i2.TaskId, snapshot[u1][p1][1].TaskId); Assert.AreEqual(i3.TaskId, snapshot[u1][p1][2].TaskId); Assert.AreEqual(2, snapshot[u1][p1][0].OrderInQueue); Assert.AreEqual(3, snapshot[u1][p1][1].OrderInQueue); Assert.AreEqual(4, snapshot[u1][p1][2].OrderInQueue); //u1 proj2 Assert.AreEqual(i4.TaskId, snapshot[u1][p2][0].TaskId); Assert.AreEqual(i5.TaskId, snapshot[u1][p2][1].TaskId); Assert.AreEqual(1, snapshot[u1][p2][0].OrderInQueue); Assert.AreEqual(3, snapshot[u1][p2][1].OrderInQueue); //u1 proj3 Assert.AreEqual(i8.TaskId, snapshot[u1][p3][0].TaskId); Assert.AreEqual(1, snapshot[u1][p3][0].OrderInQueue); //u2 proj1 Assert.AreEqual(i6.TaskId, snapshot[u2][p1][0].TaskId); Assert.AreEqual(1, snapshot[u2][p1][0].OrderInQueue); //u2 proj2 Assert.AreEqual(i7.TaskId, snapshot[u2][p2][0].TaskId); Assert.AreEqual(2, snapshot[u2][p2][0].OrderInQueue); //u2 proj3 Assert.AreEqual(i9.TaskId, snapshot[u2][p3][0].TaskId); Assert.AreEqual(2, snapshot[u2][p3][0].OrderInQueue); } [Test] public void QueueReturnUniqueProjectCodes() { const string proj1 = "proj1"; const string proj2 = "proj2"; const string proj3 = "proj3"; const string user = "user"; Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user)); Queue.Add(new QueueItem("a", Guid.NewGuid(), proj2, user)); Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user)); Queue.Add(new QueueItem("a", Guid.NewGuid(), proj3, user)); Queue.Add(new QueueItem("a", Guid.NewGuid(), proj2, user)); Queue.Add(new QueueItem("a", Guid.NewGuid(), proj1, user)); var projects = Queue.UniqueProjects().ToArray(); Assert.AreEqual(3, projects.Length); Assert.IsTrue(projects.Contains(proj1)); Assert.IsTrue(projects.Contains(proj2)); Assert.IsTrue(projects.Contains(proj3)); } [Test] public void QueueRemoveTaskById() { var taskId = Guid.NewGuid(); Queue.Add(new QueueItem("a", taskId, "p", "u")); Queue.Remove(taskId); Assert.IsFalse(Queue.Dump().Any(qi => qi.TaskId == taskId)); } [Test] public void QueueRemoveNotExistingTask() { //Don't thow exceptions Queue.Remove(Guid.NewGuid()); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using NLog.Targets; using Xunit; using Xunit.Extensions; public class ColoredConsoleTargetTests : NLogTestBase { [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextTest(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " At The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextIgnoreCase(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The C", "at", " S", "at", " ", "At", " The Bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingTextWholeWords(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = "at", WholeWords = true, CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The cat sat ", "at", " the bar." }); } [Theory] [InlineData(true)] [InlineData(false)] public void WordHighlightingRegex(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }); AssertOutput(target, "The cat sat at the bar.", new string[] { "The ", "cat", " ", "sat", " at the bar." }); } [Fact] public void ColoredConsoleAnsi_OverlappingWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big warning", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "warn", ForegroundColor = ConsoleOutputColor.DarkMagenta, BackgroundColor = ConsoleOutputColor.NoChange }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "a", ForegroundColor = ConsoleOutputColor.DarkGreen, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big warning message", new string[] { "The \x1B[31mbig \x1B[35mw\x1B[32ma\x1B[35mrn\x1B[31ming\x1B[0m mess\x1B[32ma\x1B[0mge\x1B[0m" }); } [Fact] public void ColoredConsoleAnsi_RepeatedWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big big", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big big big big warning message", new string[] { "The \x1B[31mbig big\x1B[0m \x1B[31mbig big\x1B[0m warning message\x1B[0m" }); } [Theory] [InlineData("The big warning message", "\x1B[42mThe big warning message\x1B[0m")] [InlineData("The big\r\nwarning message", "\x1B[42mThe big\x1B[0m\r\n\x1B[42mwarning message\x1B[0m")] public void ColoredConsoleAnsi_RowColor_VerificationTest(string inputText, string expectedResult) { var target = new ColoredConsoleTarget { Layout = "${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { BackgroundColor = ConsoleOutputColor.DarkGreen }); AssertOutput(target, inputText, new string[] { expectedResult }, string.Empty); } [Fact] public void ColoredConsoleAnsi_RowColorWithWordHighlight_VerificationTest() { var target = new ColoredConsoleTarget { Layout = "${message}", EnableAnsiOutput = true }; target.UseDefaultRowHighlightingRules = false; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule() { BackgroundColor = ConsoleOutputColor.Green }); target.WordHighlightingRules.Add(new ConsoleWordHighlightingRule { Text = "big big", ForegroundColor = ConsoleOutputColor.DarkRed, BackgroundColor = ConsoleOutputColor.NoChange }); AssertOutput(target, "The big big big big warning message", new string[] { "\x1B[102mThe \x1B[31mbig big\x1B[0m\x1B[102m \x1B[31mbig big\x1B[0m\x1B[102m warning message\x1B[0m" }, string.Empty); } /// <summary> /// With or without CompileRegex, CompileRegex is never null, even if not used when CompileRegex=false. (needed for backwards-compatibility) /// </summary> /// <param name="compileRegex"></param> [Theory] [InlineData(true)] [InlineData(false)] public void CompiledRegexPropertyNotNull(bool compileRegex) { var rule = new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Regex = "\\wat", CompileRegex = compileRegex }; Assert.NotNull(rule.CompiledRegex); } [Theory] [InlineData(true)] [InlineData(false)] public void DonRemoveIfRegexIsEmpty(bool compileRegex) { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}" }; target.WordHighlightingRules.Add( new ConsoleWordHighlightingRule { ForegroundColor = ConsoleOutputColor.Red, Text = null, IgnoreCase = true, CompileRegex = compileRegex }); AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } [Fact] public void ColortedConsoleAutoFlushOnWrite() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", AutoFlush = true }; AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } #if !NET3_5 && !MONO [Fact] public void ColoredConsoleRaceCondtionIgnoreTest() { var configXml = @" <nlog throwExceptions='true'> <targets> <target name='console' type='coloredConsole' layout='${message}' /> <target name='console2' type='coloredConsole' layout='${message}' /> <target name='console3' type='coloredConsole' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Trace' writeTo='console,console2,console3' /> </rules> </nlog>"; ConsoleTargetTests.ConsoleRaceCondtionIgnoreInnerTest(configXml); } #endif #if NET4_5 [Fact] public void ColoredConsoleDetectOutputRedirectedTest() { var target = new ColoredConsoleTarget { Layout = "${logger} ${message}", DetectOutputRedirected = true }; AssertOutput(target, "The Cat Sat At The Bar.", new string[] { "The Cat Sat At The Bar." }); } #endif private static void AssertOutput(Target target, string message, string[] expectedParts, string loggerName = "Logger ") { var consoleOutWriter = new PartsWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, loggerName.Trim(), message).WithContinuation(exceptions.Add)); target.Close(); Assert.Single(exceptions); Assert.True(exceptions.TrueForAll(e => e == null)); } finally { Console.SetOut(oldConsoleOutWriter); } var expected = Enumerable.Repeat(loggerName + expectedParts[0], 1).Concat(expectedParts.Skip(1)); Assert.Equal(expected, consoleOutWriter.Values); Assert.True(consoleOutWriter.SingleWriteLine); Assert.True(consoleOutWriter.SingleFlush); } private class PartsWriter : StringWriter { public PartsWriter() { Values = new List<string>(); } public List<string> Values { get; private set; } public bool SingleWriteLine { get; private set; } public bool SingleFlush { get; private set; } public override void Write(string value) { Values.Add(value); } public override void Flush() { if (SingleFlush) { throw new InvalidOperationException("Single Flush only"); } SingleFlush = true; base.Flush(); } public override void WriteLine(string value) { if (SingleWriteLine) { Values.Clear(); throw new InvalidOperationException("Single WriteLine only"); } SingleWriteLine = true; if (!string.IsNullOrEmpty(value)) Values.Add(value); } public override void WriteLine() { if (SingleWriteLine) { Values.Clear(); throw new InvalidOperationException("Single WriteLine only"); } SingleWriteLine = true; } } } }
// 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.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Azure resources can be locked to prevent other users in your /// organization from deleting or modifying resources. /// </summary> public partial class ManagementLockClient : Microsoft.Rest.ServiceClient<ManagementLockClient>, IManagementLockClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The ID of the target subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version to use for the operation. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IManagementLocksOperations. /// </summary> public virtual IManagementLocksOperations ManagementLocks { get; private set; } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLockClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLockClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ManagementLockClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ManagementLockClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ManagementLockClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ManagementLockClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ManagementLockClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLockClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ManagementLockClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.ManagementLocks = new ManagementLocksOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.ApiVersion = "2016-09-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.IO.FileSystem.Tests { public class Directory_Move_str_str : FileSystemTest { #region Utilities public virtual void Move(string sourceDir, string destDir) { Directory.Move(sourceDir, destDir); } #endregion #region UniversalTests [Fact] public void NullPath() { Assert.Throws<ArgumentNullException>(() => Move(null, ".")); Assert.Throws<ArgumentNullException>(() => Move(".", null)); } [Fact] public void EmptyPath() { Assert.Throws<ArgumentException>(() => Move(string.Empty, ".")); Assert.Throws<ArgumentException>(() => Move(".", string.Empty)); } [Fact] public void NonExistentDirectory() { DirectoryInfo valid = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<DirectoryNotFoundException>(() => Move(GetTestFilePath(), valid.FullName)); Assert.Throws<DirectoryNotFoundException>(() => Move(valid.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()))); } [Fact] public void MoveOntoExistingDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<IOException>(() => Move(testDir.FullName, testDir.FullName)); } [Fact] public void MoveIntoCurrentDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<IOException>(() => Move(testDir.FullName, Path.Combine(testDir.FullName, "."))); } [Fact] public void MoveOntoParentDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<IOException>(() => Move(testDir.FullName, Path.Combine(testDir.FullName, ".."))); } [Fact] public void BasicMove() { string testDirSource = Path.Combine(TestDirectory, GetTestFileName()); string testDirDest = Path.Combine(TestDirectory, GetTestFileName()); Directory.CreateDirectory(testDirSource); Move(testDirSource, testDirDest); Assert.True(Directory.Exists(testDirDest)); } [Fact] public void MultipleMoves() { string testDir = GetTestFilePath(); string testDirSource = Path.Combine(testDir, GetTestFileName()); string testDirDest1 = Path.Combine(testDir, GetTestFileName()); string testDirDest2 = Path.Combine(testDir, GetTestFileName()); Directory.CreateDirectory(testDirSource); Move(testDirSource, testDirDest1); Move(testDirDest1, testDirDest2); Assert.True(Directory.Exists(testDirDest2)); Assert.False(Directory.Exists(testDirDest1)); Assert.False(Directory.Exists(testDirSource)); } [Fact] public void DirectoryNameWithSpaces() { string testDirSource = Path.Combine(TestDirectory, GetTestFileName()); string testDirDest = Path.Combine(TestDirectory, " e n d"); Directory.CreateDirectory(testDirSource); Move(testDirSource, testDirDest); Assert.True(Directory.Exists(testDirDest)); } [Fact] public void TrailingDirectorySeparators() { string testDirSource = Path.Combine(TestDirectory, GetTestFileName()); string testDirDest = Path.Combine(TestDirectory, GetTestFileName()); Directory.CreateDirectory(testDirSource); Move(testDirSource + Path.DirectorySeparatorChar, testDirDest + Path.DirectorySeparatorChar); Assert.True(Directory.Exists(testDirDest)); } [Fact] public void IncludeSubdirectories() { string testDirSource = Path.Combine(TestDirectory, GetTestFileName()); string testDirSubDirectory = GetTestFileName(); string testDirDest = Path.Combine(TestDirectory, GetTestFileName()); Directory.CreateDirectory(testDirSource); Directory.CreateDirectory(Path.Combine(testDirSource, testDirSubDirectory)); Move(testDirSource, testDirDest); Assert.True(Directory.Exists(testDirDest)); Assert.False(Directory.Exists(testDirSource)); Assert.True(Directory.Exists(Path.Combine(testDirDest, testDirSubDirectory))); } [Fact] public void LongPath() { //Create a destination path longer than the traditional Windows limit of 256 characters string testDirSource = Path.Combine(TestDirectory, GetTestFileName()); string testDirDest = Path.Combine(TestDirectory, new string('a', 300)); Directory.CreateDirectory(testDirSource); // TODO #645: Requires long path support //Move(testDirSource, testDirDest); //Assert.True(Directory.Exists(testDirDest)); //Assert.False(Directory.Exists(testDirSource)); Assert.Throws<PathTooLongException>(() => Move(testDirSource, testDirDest)); Assert.Throws<PathTooLongException>(() => Move(Path.Combine(TestDirectory, new string('a', 300)), TestDirectory)); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsWildCharacterPath() { Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath())); Assert.Throws<ArgumentException>(() => Move(TestDirectory, "*")); Assert.Throws<ArgumentException>(() => Move(TestDirectory, "Test*t")); Assert.Throws<ArgumentException>(() => Move(TestDirectory, "*Test")); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWildCharacterPath() { // Wildcards are allowed in paths for Unix move commands as literals as well as functional wildcards, // but to implement the latter in .NET would be confusing (e.g. having a DirectoryInfo represent multiple directories), // so the implementation assumes the former. // Thus, any "*" characters will act the same as any other character when used in a file/directory name. string testDir = GetTestFilePath(); string testDirSource = Path.Combine(testDir, "*"); string testDirShouldntMove = Path.Combine(testDir, "*t"); string testDirDest = Path.Combine(testDir, "*" + GetTestFileName()); Directory.CreateDirectory(testDirSource); Directory.CreateDirectory(testDirShouldntMove); Move(testDirSource, testDirDest); Assert.True(Directory.Exists(testDirDest)); Assert.False(Directory.Exists(testDirSource)); Assert.True(Directory.Exists(testDirShouldntMove)); Move(testDirDest, testDirSource); Assert.False(Directory.Exists(testDirDest)); Assert.True(Directory.Exists(testDirSource)); Assert.True(Directory.Exists(testDirShouldntMove)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsWhitespacePath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, " ")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\n")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, ">")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "<")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\0")); Assert.Throws<ArgumentException>(() => Move(testDir.FullName, "\t")); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWhitespacePath() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testDirToMove = Path.Combine(testDir.FullName, GetTestFileName()); Directory.CreateDirectory(testDirToMove); Move(testDirToMove, Path.Combine(testDir.FullName, " ")); Move(Path.Combine(testDir.FullName, " "), Path.Combine(testDir.FullName, "\n")); Move(Path.Combine(testDir.FullName, "\n"), Path.Combine(testDir.FullName, "\t")); Move(Path.Combine(testDir.FullName, "\t"), Path.Combine(testDir.FullName, ">")); Move(Path.Combine(testDir.FullName, ">"), Path.Combine(testDir.FullName, "< ")); Assert.True(Directory.Exists(Path.Combine(testDir.FullName, "< "))); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExistingDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string testDirSource = Path.Combine(testDir.FullName, GetTestFileName()); string testDirDest = Path.Combine(testDir.FullName, GetTestFileName()); Directory.CreateDirectory(testDirSource); Directory.CreateDirectory(testDirDest); Assert.Throws<IOException>(() => Move(testDirSource, testDirDest)); Assert.True(Directory.Exists(testDirDest)); Assert.True(Directory.Exists(testDirSource)); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void BetweenDriveLabels() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = Path.GetFullPath(testDir.FullName); if (path.Substring(0, 3) == @"d:\" || path.Substring(0, 3) == @"D:\") Assert.Throws<IOException>(() => Move(path, "C:\\DoesntExist")); else Assert.Throws<IOException>(() => Move(path, "D:\\DoesntExist")); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixExistingDirectory() { // Moving to an-empty directory is supported on Unix, but moving to a non-empty directory is not string testDirSource = GetTestFilePath(); string testDirDestEmpty = GetTestFilePath(); string testDirDestNonEmpty = GetTestFilePath(); Directory.CreateDirectory(testDirSource); Directory.CreateDirectory(testDirDestEmpty); Directory.CreateDirectory(testDirDestNonEmpty); using (File.Create(Path.Combine(testDirDestNonEmpty, GetTestFileName()))) { Assert.Throws<IOException>(() => Move(testDirSource, testDirDestNonEmpty)); Assert.True(Directory.Exists(testDirDestNonEmpty)); Assert.True(Directory.Exists(testDirSource)); } Move(testDirSource, testDirDestEmpty); Assert.True(Directory.Exists(testDirDestEmpty)); Assert.False(Directory.Exists(testDirSource)); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Web.UI; using Vevo; using Vevo.Domain; using Vevo.Domain.Marketing; using Vevo.Domain.Stores; using Vevo.Domain.Users; using Vevo.Shared.DataAccess; using Vevo.WebAppLib; using Vevo.Base.Domain; using Vevo.Deluxe.WebUI.Marketing; public partial class AccountDetails : Vevo.Deluxe.WebUI.Base.BaseLicenseLanguagePage { #region Private private string CurrentID { get { return DataAccessContext.CustomerRepository.GetIDFromUserName( Page.User.Identity.Name ); } } private string EditMode { get { if (!String.IsNullOrEmpty( Request.QueryString["EditMode"] )) return Request.QueryString["EditMode"]; else return ""; } } private bool IsWholesale { get { return (bool) ViewState["IsWholesale"]; } set { ViewState["IsWholesale"] = value; } } private void ShowHideSaleTaxExempt() { if (IsSaleTaxExemptVisible() && !String.IsNullOrEmpty( uxTaxExemptID.Text ) && !EditMode.Equals( "account" )) { uxCustomerTaxExemptPanel.Visible = true; } else { uxCustomerTaxExemptPanel.Visible = false; } } private void ShowHideControls() { ShowHideSaleTaxExempt(); } private void PopulateControls() { Customer customer = DataAccessContext.CustomerRepository.GetOne( CurrentID ); uxUserName.Text = customer.UserName; uxFirstName.Text = customer.BillingAddress.FirstName; uxLastName.Text = customer.BillingAddress.LastName; uxCompany.Text = customer.BillingAddress.Company; uxAddress1.Text = customer.BillingAddress.Address1; uxAddress2.Text = customer.BillingAddress.Address2; uxCity.Text = customer.BillingAddress.City; uxZip.Text = customer.BillingAddress.Zip; uxCountryAndState.CurrentCountry = customer.BillingAddress.Country; uxCountryAndState.CurrentState = customer.BillingAddress.State; uxPhone.Text = customer.BillingAddress.Phone; uxFax.Text = customer.BillingAddress.Fax; uxEmail.Text = customer.Email; IsWholesale = customer.IsWholesale; if (customer.IsTaxExempt) { uxTaxExemptID.Text = customer.TaxExemptID; uxTaxExemptCountry.Text = customer.TaxExemptCountry; uxTaxExemptState.Text = customer.TaxExemptState; } StoreRetriever storeRetriever = new StoreRetriever(); NewsLetter newsLetter = DataAccessContext.NewsLetterRepository.GetOne( customer.Email, storeRetriever.GetStore() ); if (!newsLetter.IsNull) uxSubscribeCheckBox.Checked = true; else uxSubscribeCheckBox.Checked = false; } private bool VerifyCountryAndState() { bool result = true; bool validateCountryState, validateCountry, validateState; validateCountryState = uxCountryAndState.Validate( out validateCountry, out validateState ); if (!validateCountryState) { uxBillingCountryStateDiv.Visible = true; if (!validateCountry) { uxBillingCountryStateMessage.Text = "Required Country."; } else if (!validateState) { uxBillingCountryStateMessage.Text = "Required State."; } result = false; } return result; } private bool MoreThanOneUserSubscribeWithEmail( string email ) { IList<Customer> customerList = DataAccessContext.CustomerRepository.GetCustomerByEmail( email ); return customerList.Count > 1; } private void UpdateEmailSubscriber( string email, string emailOld ) { StoreRetriever storeRetriever = new StoreRetriever(); Store store = storeRetriever.GetStore(); string emailHash = SecurityUtilities.HashMD5( email + WebConfiguration.SecretKey ); if (uxSubscribeCheckBox.Checked) { NewsLetter newsLetterOld = DataAccessContext.NewsLetterRepository.GetOne( emailOld, store ); NewsLetter newsLetter = DataAccessContext.NewsLetterRepository.GetOne( email, store ); if (newsLetterOld.IsNull) { if (newsLetter.IsNull) { newsLetter.Email = email; newsLetter.EmailHash = emailHash; newsLetter.JoinDate = DateTime.Now; newsLetter.StoreID = store.StoreID; DataAccessContext.NewsLetterRepository.Create( newsLetter ); } } else { if (MoreThanOneUserSubscribeWithEmail( emailOld )) { // No need to delete old email if (newsLetter.IsNull) { newsLetter.Email = email; newsLetter.EmailHash = emailHash; newsLetter.JoinDate = DateTime.Now; newsLetter.StoreID = store.StoreID; DataAccessContext.NewsLetterRepository.Create( newsLetter ); } } else { if (String.Compare( email, emailOld ) != 0) { // No need to keep old email if (newsLetter.IsNull) { newsLetterOld.EmailHash = emailHash; DataAccessContext.NewsLetterRepository.Update( newsLetterOld, email, store.StoreID ); } else { DataAccessContext.NewsLetterRepository.DeleteEmailNoHash( emailOld, store ); } } } } } else { if (!MoreThanOneUserSubscribeWithEmail( email )) DataAccessContext.NewsLetterRepository.DeleteEmail( emailHash, store ); } } private void UpdateCustomer() { Customer customer = DataAccessContext.CustomerRepository.GetOne( CurrentID ); string emailOld = customer.Email; UpdateEmailSubscriber( uxEmail.Text.ToString().Trim(), emailOld ); Address billingAddress = new Address( uxFirstName.Text, uxLastName.Text, uxCompany.Text, uxAddress1.Text, uxAddress2.Text, uxCity.Text, uxCountryAndState.CurrentState, uxZip.Text, uxCountryAndState.CurrentCountry, uxPhone.Text, uxFax.Text ); customer.UserName = uxUserName.Text; customer.BillingAddress = billingAddress; customer.Email = uxEmail.Text; for (int i = 0; i < customer.ShippingAddresses.Count; i++) { if (customer.ShippingAddresses[i].IsSameAsBillingAddress) { string id = customer.ShippingAddresses[i].ShippingAddressID; string aliasName = customer.ShippingAddresses[i].AliasName; bool residentialValue = customer.ShippingAddresses[i].Residential; customer.ShippingAddresses[i] = new Vevo.Base.Domain.ShippingAddress( billingAddress, residentialValue ); customer.ShippingAddresses[i].ShippingAddressID = id; customer.ShippingAddresses[i].AliasName = aliasName; customer.ShippingAddresses[i].IsSameAsBillingAddress = true; } } DataAccessContext.CustomerRepository.Save( customer ); } #endregion #region Protected protected void Page_Load( object sender, EventArgs e ) { if (!IsPostBack) { PopulateControls(); } uxBillingCountryStateDiv.Visible = false; } protected void Page_PreRender( object sender, EventArgs e ) { if (EditMode == "account") uxBillingPanel.Style["display"] = "none"; else if (EditMode == "address") uxAccountPanel.Style["display"] = "none"; ShowHideControls(); } protected void uxUpdateImageButton_Click( object sender, EventArgs e ) { try { if (Page.IsValid && VerifyCountryAndState()) { UpdateCustomer(); AffiliateHelper.UpdateAffiliateReference( uxUserName.Text ); uxMessage.DisplayMessage( "[$UpdateComplete]" ); } } catch (DataAccessException ex) { uxMessage.DisplayError( ex.Message ); } } protected void uxAddNewShippingAddress_Click( object sender, EventArgs e ) { Response.Redirect( "ShippingAddress.aspx" ); } protected bool IsSaleTaxExemptVisible() { return DataAccessContext.Configurations.GetBoolValue( "SaleTaxExempt" ); } #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. namespace System { //Only contains static methods. Does not require serialization using System; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; using System.Runtime; #if BIT64 using nuint = System.UInt64; #else // BIT64 using nuint = System.UInt32; #endif // BIT64 public static class Buffer { // Copies from one primitive array to another primitive array without // respecting types. This calls memmove internally. The count and // offset parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count); // A very simple and efficient memmove that assumes all of the // parameter validation has already been done. The count and offset // parameters here are in bytes. If you want to use traditional // array element indices and counts, use Array.Copy. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalBlockCopy(Array src, int srcOffsetBytes, Array dst, int dstOffsetBytes, int byteCount); // This is ported from the optimized CRT assembly in memchr.asm. The JIT generates // pretty good code here and this ends up being within a couple % of the CRT asm. // It is however cross platform as the CRT hasn't ported their fast version to 64-bit // platforms. // internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count) { Debug.Assert(src != null, "src should not be null"); byte* pByte = src + index; // Align up the pointer to sizeof(int). while (((int)pByte & 3) != 0) { if (count == 0) return -1; else if (*pByte == value) return (int)(pByte - src); count--; pByte++; } // Fill comparer with value byte for comparisons // // comparer = 0/0/value/value uint comparer = (((uint)value << 8) + (uint)value); // comparer = value/value/value/value comparer = (comparer << 16) + comparer; // Run through buffer until we hit a 4-byte section which contains // the byte we're looking for or until we exhaust the buffer. while (count > 3) { // Test the buffer for presence of value. comparer contains the byte // replicated 4 times. uint t1 = *(uint*)pByte; t1 = t1 ^ comparer; uint t2 = 0x7efefeff + t1; t1 = t1 ^ 0xffffffff; t1 = t1 ^ t2; t1 = t1 & 0x81010100; // if t1 is zero then these 4-bytes don't contain a match if (t1 != 0) { // We've found a match for value, figure out which position it's in. int foundIndex = (int)(pByte - src); if (pByte[0] == value) return foundIndex; else if (pByte[1] == value) return foundIndex + 1; else if (pByte[2] == value) return foundIndex + 2; else if (pByte[3] == value) return foundIndex + 3; } count -= 4; pByte += 4; } // Catch any bytes that might be left at the tail of the buffer while (count > 0) { if (*pByte == value) return (int)(pByte - src); count--; pByte++; } // If we don't have a match return -1; return -1; } // Returns a bool to indicate if the array is of primitive data types // or not. [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsPrimitiveTypeArray(Array array); // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return ((byte*)array) + index. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern byte _GetByte(Array array, int index); public static byte GetByte(Array array, int index) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); return _GetByte(array, index); } // Sets a particular byte in an the array. The array must be an // array of primitives. // // This essentially does the following: // *(((byte*)array) + index) = value. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _SetByte(Array array, int index, byte value); public static void SetByte(Array array, int index, byte value) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); // Is the index in valid range of the array? if (index < 0 || index >= _ByteLength(array)) throw new ArgumentOutOfRangeException(nameof(index)); // Make the FCall to do the work _SetByte(array, index, value); } // Gets a particular byte out of the array. The array must be an // array of primitives. // // This essentially does the following: // return array.length * sizeof(array.UnderlyingElementType). // [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int _ByteLength(Array array); public static int ByteLength(Array array) { // Is the array present? if (array == null) throw new ArgumentNullException(nameof(array)); // Is it of primitive types? if (!IsPrimitiveTypeArray(array)) throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array)); return _ByteLength(array); } internal unsafe static void ZeroMemory(byte* src, long len) { while (len-- > 0) *(src + len) = 0; } internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) { Debug.Assert((srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len == 0) return; fixed (byte* pDest = dest) { Memcpy(pDest + destIndex, src + srcIndex, len); } } internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Debug.Assert((srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!"); Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src"); // If dest has 0 elements, the fixed statement will throw an // IndexOutOfRangeException. Special-case 0-byte copies. if (len == 0) return; fixed (byte* pSrc = src) { Memcpy(pDest + destIndex, pSrc + srcIndex, len); } } // This is tricky to get right AND fast, so lets make it useful for the whole Fx. // E.g. System.Runtime.WindowsRuntime!WindowsRuntimeBufferExtensions.MemCopy uses it. // This method has a slightly different behavior on arm and other platforms. // On arm this method behaves like memcpy and does not handle overlapping buffers. // While on other platforms it behaves like memmove and handles overlapping buffers. // This behavioral difference is unfortunate but intentional because // 1. This method is given access to other internal dlls and this close to release we do not want to change it. // 2. It is difficult to get this right for arm and again due to release dates we would like to visit it later. [FriendAccessAllowed] #if ARM [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern void Memcpy(byte* dest, byte* src, int len); #else // ARM [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Debug.Assert(len >= 0, "Negative length in memcopy!"); Memmove(dest, src, (uint)len); } #endif // ARM // This method has different signature for x64 and other platforms and is done for performance reasons. internal unsafe static void Memmove(byte* dest, byte* src, nuint len) { // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway. if ((nuint)dest - (nuint)src < len) goto PInvoke; // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do. // // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as // possible yet and so we have this implementation here for now. // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (len) { case 0: return; case 1: *dest = *src; return; case 2: *(short*)dest = *(short*)src; return; case 3: *(short*)dest = *(short*)src; *(dest + 2) = *(src + 2); return; case 4: *(int*)dest = *(int*)src; return; case 5: *(int*)dest = *(int*)src; *(dest + 4) = *(src + 4); return; case 6: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); return; case 7: *(int*)dest = *(int*)src; *(short*)(dest + 4) = *(short*)(src + 4); *(dest + 6) = *(src + 6); return; case 8: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif return; case 9: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(dest + 8) = *(src + 8); return; case 10: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); return; case 11: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(short*)(dest + 8) = *(short*)(src + 8); *(dest + 10) = *(src + 10); return; case 12: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); return; case 13: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(dest + 12) = *(src + 12); return; case 14: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); return; case 15: #if BIT64 *(long*)dest = *(long*)src; #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); #endif *(int*)(dest + 8) = *(int*)(src + 8); *(short*)(dest + 12) = *(short*)(src + 12); *(dest + 14) = *(src + 14); return; case 16: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif return; case 17: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(dest + 16) = *(src + 16); return; case 18: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); return; case 19: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(short*)(dest + 16) = *(short*)(src + 16); *(dest + 18) = *(src + 18); return; case 20: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); return; case 21: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(dest + 20) = *(src + 20); return; case 22: #if BIT64 *(long*)dest = *(long*)src; *(long*)(dest + 8) = *(long*)(src + 8); #else *(int*)dest = *(int*)src; *(int*)(dest + 4) = *(int*)(src + 4); *(int*)(dest + 8) = *(int*)(src + 8); *(int*)(dest + 12) = *(int*)(src + 12); #endif *(int*)(dest + 16) = *(int*)(src + 16); *(short*)(dest + 20) = *(short*)(src + 20); return; } // P/Invoke into the native version for large lengths if (len >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if (((int)dest & 3) != 0) { if (((int)dest & 1) != 0) { *(dest + i) = *(src + i); i += 1; if (((int)dest & 2) != 0) goto IntAligned; } *(short*)(dest + i) = *(short*)(src + i); i += 2; } IntAligned: #if BIT64 // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)dest % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if ((((int)dest - 1) & 4) == 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } #endif // BIT64 nuint end = len - 16; len -= i; // lower 4 bits of len represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to dest/src. #if BIT64 *(long*)(dest + i) = *(long*)(src + i); *(long*)(dest + i + 8) = *(long*)(src + i + 8); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); *(int*)(dest + i + 8) = *(int*)(src + i + 8); *(int*)(dest + i + 12) = *(int*)(src + i + 12); #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((len & 8) != 0) { #if BIT64 *(long*)(dest + i) = *(long*)(src + i); #else *(int*)(dest + i) = *(int*)(src + i); *(int*)(dest + i + 4) = *(int*)(src + i + 4); #endif i += 8; } if ((len & 4) != 0) { *(int*)(dest + i) = *(int*)(src + i); i += 4; } if ((len & 2) != 0) { *(short*)(dest + i) = *(short*)(src + i); i += 2; } if ((len & 1) != 0) { *(dest + i) = *(src + i); // We're not using i after this, so not needed // i += 1; } return; PInvoke: _Memmove(dest, src, len); } // Non-inlinable wrapper around the QCall that avoids poluting the fast path // with P/Invoke prolog/epilog. [MethodImplAttribute(MethodImplOptions.NoInlining)] private unsafe static void _Memmove(byte* dest, byte* src, nuint len) { __Memmove(dest, src, len); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] extern private unsafe static void __Memmove(byte* dest, byte* src, nuint len); // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy)); } // The attributes on this method are chosen for best JIT performance. // Please do not edit unless intentional. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } #if BIT64 Memmove((byte*)destination, (byte*)source, sourceBytesToCopy); #else // BIT64 Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy)); #endif // BIT64 } } }
// // 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 System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for /// more information) /// </summary> internal partial class ServiceCertificateOperations : IServiceOperations<ComputeManagementClient>, IServiceCertificateOperations { /// <summary> /// Initializes a new instance of the ServiceCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceCertificateOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The Begin Creating Service Certificate operation adds a certificate /// to a hosted service. This operation is an asynchronous operation. /// To determine whether the management service has finished /// processing the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginCreatingAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Data == null) { throw new ArgumentNullException("parameters.Data"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2017-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement certificateFileElement = new XElement(XName.Get("CertificateFile", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(certificateFileElement); XElement dataElement = new XElement(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); dataElement.Value = Convert.ToBase64String(parameters.Data); certificateFileElement.Add(dataElement); XElement certificateFormatElement = new XElement(XName.Get("CertificateFormat", "http://schemas.microsoft.com/windowsazure")); certificateFormatElement.Value = ComputeManagementClient.CertificateFormatToString(parameters.CertificateFormat); certificateFileElement.Add(certificateFormatElement); if (parameters.Password != null) { XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.microsoft.com/windowsazure")); passwordElement.Value = parameters.Password; certificateFileElement.Add(passwordElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Deleting Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Deleting Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginDeletingAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2017-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Service Certificate operation adds a certificate to a /// hosted service. This operation is an asynchronous operation. To /// determine whether the management service has finished processing /// the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> CreateAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginCreatingAsync(serviceName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Delete Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Delete Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Get Service Certificate operation returns the public data for /// the specified X.509 certificate associated with a hosted service. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Get Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Service Certificate operation response. /// </returns> public async Task<ServiceCertificateGetResponse> GetAsync(ServiceCertificateGetParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2017-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificateElement = responseDoc.Element(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); if (certificateElement != null) { XElement dataElement = certificateElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); result.Data = dataInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Service Certificates operation lists all of the service /// certificates associated with the specified hosted service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your hosted service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Service Certificates operation response. /// </returns> public async Task<ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2017-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure")); if (certificatesSequenceElement != null) { foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"))) { ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate(); result.Certificates.Add(certificateInstance); XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure")); if (certificateUrlElement != null) { Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value); certificateInstance.CertificateUri = certificateUrlInstance; } XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure")); if (thumbprintElement != null) { string thumbprintInstance = thumbprintElement.Value; certificateInstance.Thumbprint = thumbprintInstance; } XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); if (thumbprintAlgorithmElement != null) { string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value; certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance; } XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); certificateInstance.Data = dataInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// We add an option contract using <see cref="QCAlgorithm.AddOptionContract"/> and place a trade, the underlying /// gets deselected from the universe selection but should still be present since we manually added the option contract. /// Later we call <see cref="QCAlgorithm.RemoveOptionContract"/> and expect both option and underlying to be removed. /// </summary> public class AddOptionContractFromUniverseRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private DateTime _expiration = new DateTime(2014, 06, 21); private SecurityChanges _securityChanges = SecurityChanges.None; private Symbol _option; private Symbol _aapl; private Symbol _twx; private bool _traded; public override void Initialize() { _twx = QuantConnect.Symbol.Create("TWX", SecurityType.Equity, Market.USA); _aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA); UniverseSettings.Resolution = Resolution.Minute; UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw; SetStartDate(2014, 06, 05); SetEndDate(2014, 06, 09); AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl }, enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl }); } public override void OnData(Slice data) { if (_option != null && Securities[_option].Price != 0 && !_traded) { _traded = true; Buy(_option, 1); } if (Time.Date > new DateTime(2014, 6, 5)) { if (Time < new DateTime(2014, 6, 6, 14, 0, 0)) { var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx); // assert underlying still there after the universe selection removed it, still used by the manually added option contract if (!configs.Any()) { throw new Exception($"Was expecting configurations for {_twx}" + $" even after it has been deselected from coarse universe because we still have the option contract."); } } else if (Time == new DateTime(2014, 6, 6, 14, 0, 0)) { // liquidate & remove the option RemoveOptionContract(_option); } // assert underlying was finally removed else if(Time > new DateTime(2014, 6, 6, 14, 0, 0)) { foreach (var symbol in new[] { _option, _option.Underlying }) { var configs = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol); if (configs.Any()) { throw new Exception($"Unexpected configuration for {symbol} after it has been deselected from coarse universe and option contract is removed."); } } } } } public override void OnSecuritiesChanged(SecurityChanges changes) { if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any()) { throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!"); } if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any()) { throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!"); } // keep track of all removed and added securities _securityChanges += changes; if (changes.AddedSecurities.Any(security => security.Symbol.SecurityType == SecurityType.Option)) { return; } foreach (var addedSecurity in changes.AddedSecurities) { var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time) .OrderBy(symbol => symbol.ID.Symbol) .First(optionContract => optionContract.ID.Date == _expiration && optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American); AddOptionContract(option); foreach (var symbol in new[] { option, option.Underlying }) { var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList(); if (!config.Any()) { throw new Exception($"Was expecting configurations for {symbol}"); } if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw)) { throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}"); } } // just keep the first we got if (_option == null) { _option = option; } } } public override void OnEndOfAlgorithm() { if (SubscriptionManager.Subscriptions.Any(dataConfig => dataConfig.Symbol == _twx || dataConfig.Symbol.Underlying == _twx)) { throw new Exception($"Was NOT expecting any configurations for {_twx} or it's options, since we removed the contract"); } if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol != _aapl)) { throw new Exception($"Was expecting configurations for {_aapl}"); } if (SubscriptionManager.Subscriptions.All(dataConfig => dataConfig.Symbol.Underlying != _aapl)) { throw new Exception($"Was expecting options configurations for {_aapl}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "2"}, {"Average Win", "0%"}, {"Average Loss", "-0.23%"}, {"Compounding Annual Return", "-15.596%"}, {"Drawdown", "0.200%"}, {"Expectancy", "-1"}, {"Net Profit", "-0.232%"}, {"Sharpe Ratio", "-7.739"}, {"Probabilistic Sharpe Ratio", "1.216%"}, {"Loss Rate", "100%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.024"}, {"Beta", "-0.171"}, {"Annual Standard Deviation", "0.006"}, {"Annual Variance", "0"}, {"Information Ratio", "-11.082"}, {"Tracking Error", "0.043"}, {"Treynor Ratio", "0.291"}, {"Total Fees", "$2.00"}, {"Estimated Strategy Capacity", "$2800000.00"}, {"Lowest Capacity Asset", "AOL VRKS95ENLBYE|AOL R735QTJ8XC9X"}, {"Fitness Score", "0"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-19.883"}, {"Return Over Maximum Drawdown", "-67.224"}, {"Portfolio Turnover", "0.014"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "ae0b430e9c728966e3736fb352a689c6"} }; } }
// 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 Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class SpecifyIFormatProviderTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } [Fact] public void CA1305_StringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static string SpecifyIFormatProvider1() { return string.Format(""Foo {0}"", ""bar""); } public static string SpecifyIFormatProvider2() { return string.Format(""Foo {0} {1}"", ""bar"", ""foo""); } public static string SpecifyIFormatProvider3() { return string.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar""); } public static string SpecifyIFormatProvider4() { return string.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """"); } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 16, "string.Format(string, object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(15, 16, "string.Format(string, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(20, 16, "string.Format(string, object, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(25, 16, "string.Format(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "string.Format(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider() { IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string LeadingIFormatProviderReturningString(string format) { return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format); } public static string LeadingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(string format) { return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture); } public static string TrailingIFormatProviderReturningString(string format, IFormatProvider provider) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string UserDefinedParamsMatchMethodOverload(string format, params object[] objects) { return null; } public static string UserDefinedParamsMatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, string)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningNoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider6() { IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar""); } public static void SpecifyIFormatProvider7() { IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string IFormatProviderAsDerivedTypeOverload(string format) { return null; } public static string IFormatProviderAsDerivedTypeOverload(DerivedClass provider, string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } } public class DerivedClass : IFormatProvider { public object GetFormat(Type formatType) { throw new NotImplementedException(); } }"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; public static class IFormatProviderStringTest { public static void TestMethod() { int x = Convert.ToInt32(""1""); long y = Convert.ToInt64(""1""); IFormatProviderOverloads.LeadingIFormatProvider(""1""); IFormatProviderOverloads.TrailingIFormatProvider(""1""); } } internal static class IFormatProviderOverloads { public static void LeadingIFormatProvider(string format) { LeadingIFormatProvider(CultureInfo.CurrentCulture, format); } public static void LeadingIFormatProvider(IFormatProvider provider, string format) { Console.WriteLine(string.Format(provider, format)); } public static void TrailingIFormatProvider(string format) { TrailingIFormatProvider(format, CultureInfo.CurrentCulture); } public static void TrailingIFormatProvider(string format, IFormatProvider provider) { Console.WriteLine(string.Format(provider, format)); } }", GetIFormatProviderAlternateRuleCSharpResultAt(9, 17, "Convert.ToInt32(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(10, 18, "Convert.ToInt64(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.LeadingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, string)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.TrailingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(string, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_TargetMethodNoGenerics_CSharp() { VerifyCSharp(@" using System; public static class IFormatProviderStringTest { public static void TestMethod() { IFormatProviderOverloads.TargetMethodIsNonGeneric(""1""); IFormatProviderOverloads.TargetMethodIsGeneric<int>(""1""); // No Diagnostics because the target method can be generic } } internal static class IFormatProviderOverloads { public static void TargetMethodIsNonGeneric(string format) { } public static void TargetMethodIsNonGeneric<T>(string format, IFormatProvider provider) { } public static void TargetMethodIsGeneric<T>(string format) { } public static void TargetMethodIsGeneric(string format, IFormatProvider provider) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(8, 9, "IFormatProviderOverloads.TargetMethodIsNonGeneric(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TargetMethodIsNonGeneric<T>(string, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static string IFormatProviderReturningString(string format, IFormatProvider provider) { return null; } public static string IFormatProviderReturningString(string format, IFormatProvider provider, IFormatProvider provider2) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningNonStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static void IFormatProviderReturningNonString(string format, IFormatProvider provider) { } public static void IFormatProviderReturningNonString(string format, IFormatProvider provider, IFormatProvider provider2) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_RuleException_NoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void TrailingThreadCurrentUICulture() { var s = new System.Resources.ResourceManager(null); Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, false)); var activator = Activator.CreateInstance(null, System.Reflection.BindingFlags.CreateInstance, null, null, Thread.CurrentThread.CurrentUICulture); Console.WriteLine(activator); } }"); } [Fact] public void CA1305_StringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Function SpecifyIFormatProvider1() As String Return String.Format(""Foo {0}"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider2() As String Return String.Format(""Foo {0} {1}"", ""bar"", ""foo"") End Function Public Shared Function SpecifyIFormatProvider3() As String Return String.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider4() As String Return String.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """") End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(11, 16, "String.Format(String, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(15, 16, "String.Format(String, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(19, 16, "String.Format(String, Object, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(23, 16, "String.Format(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "String.Format(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider() IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function LeadingIFormatProviderReturningString(format As String) As String Return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format) End Function Public Shared Function LeadingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String) As String Return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function UserDefinedParamsMatchMethodOverload(format As String, ParamArray objects As Object()) As String Return Nothing End Function Public Shared Function UserDefinedParamsMatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, String)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningNoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider6() IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar"") End Sub Public Shared Sub SpecifyIFormatProvider7() IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderAsDerivedTypeOverload(format As String) As String Return Nothing End Function Public Shared Function IFormatProviderAsDerivedTypeOverload(provider As DerivedClass, format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class Public Class DerivedClass Implements IFormatProvider Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat Throw New NotImplementedException() End Function End Class"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim x As Integer = Convert.ToInt32(""1"") Dim y As Long = Convert.ToInt64(""1"") IFormatProviderOverloads.LeadingIFormatProvider(""1"") IFormatProviderOverloads.TrailingIFormatProvider(""1"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub LeadingIFormatProvider(format As String) LeadingIFormatProvider(CultureInfo.CurrentCulture, format) End Sub Public Shared Sub LeadingIFormatProvider(provider As IFormatProvider, format As String) Console.WriteLine(String.Format(provider, format)) End Sub Public Shared Sub TrailingIFormatProvider(format As String) TrailingIFormatProvider(format, CultureInfo.CurrentCulture) End Sub Public Shared Sub TrailingIFormatProvider(format As String, provider As IFormatProvider) Console.WriteLine(String.Format(provider, format)) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 28, "Convert.ToInt32(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 25, "Convert.ToInt64(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.LeadingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, String)"), GetIFormatProviderAlternateRuleBasicResultAt(13, 9, "IFormatProviderOverloads.TrailingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(String, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return Nothing End Function Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningComputerInfoInstalledUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Imports Microsoft.VisualBasic.Devices Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim computerInfo As New Microsoft.VisualBasic.Devices.ComputerInfo() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", computerInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub End Class", GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "ComputerInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)")); } [Fact] public void CA1305_RuleException_NoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TrailingThreadCurrentUICulture() Dim s = New System.Resources.ResourceManager(Nothing) Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, False, False)) Dim activator__1 = Activator.CreateInstance(Nothing, System.Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Thread.CurrentThread.CurrentUICulture) Console.WriteLine(activator__1) End Sub End Class"); } private DiagnosticResult GetIFormatProviderAlternateStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Security; using System.Runtime.CompilerServices; namespace System.Runtime.Serialization { #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #else internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #endif { private ISerializationSurrogateProvider _serializationSurrogateProvider; private SerializationMode _mode; internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { _mode = SerializationMode.SharedContract; this.preserveObjectReferences = serializer.PreserveObjectReferences; _serializationSurrogateProvider = serializer.SerializationSurrogateProvider; } internal XmlObjectSerializerWriteContextComplex(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal override SerializationMode Mode { get { return _mode; } } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } #if NET_NATIVE public override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #else internal override void WriteAnyType(XmlWriterDelegator xmlWriter, object value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteAnyType(value); } #if NET_NATIVE public override void WriteString(XmlWriterDelegator xmlWriter, string value) #else internal override void WriteString(XmlWriterDelegator xmlWriter, string value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); } #if NET_NATIVE public override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #else internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); } #if NET_NATIVE public override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #else internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); } #if NET_NATIVE public override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } #if NET_NATIVE public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #else internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) #endif { if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); } #if NET_NATIVE public override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #else internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) #endif { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); if (!OnHandleReference(xmlWriter, value, false /*canContainCyclicReference*/)) xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal override void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (_serializationSurrogateProvider == null) { base.InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } else { InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); } } internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) { bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); if (isNew) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, objectId); else { xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, objectId); xmlWriter.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true); } return !isNew; } return base.OnHandleReference(xmlWriter, obj, canContainCyclicReference); } internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (preserveObjectReferences && !this.IsGetOnlyCollection) return; base.OnEndHandleReference(xmlWriter, obj, canContainCyclicReference); } internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTypeSerializable) { if (_serializationSurrogateProvider != null) { while (memberType.IsArray) memberType = memberType.GetElementType(); memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType))); return; } base.CheckIfTypeSerializable(memberType, isMemberTypeSerializable); } internal override Type GetSurrogatedType(Type type) { if (_serializationSurrogateProvider == null) { return base.GetSurrogatedType(type); } else { type = DataContract.UnwrapNullableType(type); Type surrogateType = DataContractSerializer.GetSurrogatedType(_serializationSurrogateProvider, type); if (this.IsGetOnlyCollection && surrogateType != type) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.SurrogatesWithGetOnlyCollectionsNotSupportedSerDeser, DataContract.GetClrTypeFullName(type)))); } else { return surrogateType; } } } private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { RuntimeTypeHandle objTypeHandle = isDeclaredType ? declaredTypeHandle : obj.GetType().TypeHandle; object oldObj = obj; int objOldId = 0; Type objType = Type.GetTypeFromHandle(objTypeHandle); Type declaredType = GetSurrogatedType(Type.GetTypeFromHandle(declaredTypeHandle)); declaredTypeHandle = declaredType.TypeHandle; obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider, obj, declaredType, ref objType); objTypeHandle = objType.TypeHandle; if (oldObj != obj) objOldId = SerializedObjects.ReassignId(0, oldObj, obj); if (writeXsiType) { declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredType.TypeHandle, declaredType); } else if (declaredTypeHandle.Equals(objTypeHandle)) { DataContract contract = GetDataContract(objTypeHandle, objType); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, objType, -1, declaredTypeHandle, declaredType); } if (oldObj != obj) SerializedObjects.ReassignId(objOldId, obj, oldObj); } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { if (preserveObjectReferences && size > -1) xmlWriter.WriteAttributeInt(Globals.SerPrefix, DictionaryGlobals.ArraySizeLocalName, DictionaryGlobals.SerializationNamespace, size); } } }
#region Using directives using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Xml.Serialization; using System.Xml; using System.IO; using System.Web.Services.Protocols; using System.Text; using log4net; using Commanigy.Iquomi.Api; //using Commanigy.Iquomi.Api.Services; using Commanigy.Iquomi.Client.IqProfileRef; //using Commanigy.Iquomi.Services.IqProfile; #endregion namespace Commanigy.Iquomi.Client { /// <summary> /// Summary description for FrmPreferences. /// </summary> public class FrmPreferences : System.Windows.Forms.Form { private static readonly ILog log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); private IqProfileType profile; private IqProfile iqProfileService; /// <summary> /// Property IqProfileService (Services.Service) /// </summary> public IqProfile IqProfileService { get { return this.iqProfileService; } set { this.iqProfileService = value; } } private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnApply; private TabControl tcPreferences; private TabPage tpGeneral; private CheckBox cbAutoSync; private Commanigy.Controls.LabelLine lblSynchronization; private PictureBox pbSync; private CheckBox cbAutoSignIn; private PictureBox pbSignIn; private CheckBox cbAutoStart; private Commanigy.Controls.LabelLine lblSignIn; private TabPage tpProfile; private Label label2; private Label label1; private Label label3; private TextBox tbxSurName; private TextBox tbxMiddleName; private TextBox tbxGivenName; private Commanigy.Controls.LabelLine llNameDetails; private Commanigy.Controls.SyncPictureBox pbxProfile; private Label lblFullName; private TextBox tbFullName; private Button btnFullName; private Label lblEmail; private TextBox tbEmail; private Button button3; private Button button1; private Button button2; private TabPage tpAlerts; private Label label5; private PictureBox pictureBox5; private Commanigy.Controls.LabelLine labelLine3; private TabPage tpConnection; private Commanigy.Controls.LabelLine labelLine2; private PictureBox pictureBox4; private Label label4; private TabPage tpPresence; private IContainer components; public FrmPreferences() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmPreferences)); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnApply = new System.Windows.Forms.Button(); this.tcPreferences = new System.Windows.Forms.TabControl(); this.tpGeneral = new System.Windows.Forms.TabPage(); this.cbAutoSync = new System.Windows.Forms.CheckBox(); this.lblSynchronization = new Commanigy.Controls.LabelLine(); this.pbSync = new System.Windows.Forms.PictureBox(); this.cbAutoSignIn = new System.Windows.Forms.CheckBox(); this.pbSignIn = new System.Windows.Forms.PictureBox(); this.cbAutoStart = new System.Windows.Forms.CheckBox(); this.lblSignIn = new Commanigy.Controls.LabelLine(); this.tpProfile = new System.Windows.Forms.TabPage(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.tbxSurName = new System.Windows.Forms.TextBox(); this.tbxMiddleName = new System.Windows.Forms.TextBox(); this.tbxGivenName = new System.Windows.Forms.TextBox(); this.llNameDetails = new Commanigy.Controls.LabelLine(); this.pbxProfile = new Commanigy.Controls.SyncPictureBox(); this.lblFullName = new System.Windows.Forms.Label(); this.tbFullName = new System.Windows.Forms.TextBox(); this.btnFullName = new System.Windows.Forms.Button(); this.lblEmail = new System.Windows.Forms.Label(); this.tbEmail = new System.Windows.Forms.TextBox(); this.button3 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.tpAlerts = new System.Windows.Forms.TabPage(); this.label5 = new System.Windows.Forms.Label(); this.pictureBox5 = new System.Windows.Forms.PictureBox(); this.labelLine3 = new Commanigy.Controls.LabelLine(); this.tpConnection = new System.Windows.Forms.TabPage(); this.labelLine2 = new Commanigy.Controls.LabelLine(); this.pictureBox4 = new System.Windows.Forms.PictureBox(); this.label4 = new System.Windows.Forms.Label(); this.tpPresence = new System.Windows.Forms.TabPage(); this.tcPreferences.SuspendLayout(); this.tpGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbSync)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pbSignIn)).BeginInit(); this.tpProfile.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbxProfile)).BeginInit(); this.tpAlerts.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit(); this.tpConnection.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit(); this.SuspendLayout(); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Name = "btnOk"; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnApply // resources.ApplyResources(this.btnApply, "btnApply"); this.btnApply.Name = "btnApply"; // // tcPreferences // resources.ApplyResources(this.tcPreferences, "tcPreferences"); this.tcPreferences.Controls.Add(this.tpGeneral); this.tcPreferences.Controls.Add(this.tpProfile); this.tcPreferences.Controls.Add(this.tpAlerts); this.tcPreferences.Controls.Add(this.tpConnection); this.tcPreferences.Controls.Add(this.tpPresence); this.tcPreferences.Name = "tcPreferences"; this.tcPreferences.SelectedIndex = 0; // // tpGeneral // this.tpGeneral.Controls.Add(this.cbAutoSync); this.tpGeneral.Controls.Add(this.lblSynchronization); this.tpGeneral.Controls.Add(this.pbSync); this.tpGeneral.Controls.Add(this.cbAutoSignIn); this.tpGeneral.Controls.Add(this.pbSignIn); this.tpGeneral.Controls.Add(this.cbAutoStart); this.tpGeneral.Controls.Add(this.lblSignIn); resources.ApplyResources(this.tpGeneral, "tpGeneral"); this.tpGeneral.Name = "tpGeneral"; this.tpGeneral.UseVisualStyleBackColor = true; // // cbAutoSync // this.cbAutoSync.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.cbAutoSync, "cbAutoSync"); this.cbAutoSync.Name = "cbAutoSync"; this.cbAutoSync.UseVisualStyleBackColor = false; // // lblSynchronization // resources.ApplyResources(this.lblSynchronization, "lblSynchronization"); this.lblSynchronization.BackColor = System.Drawing.Color.Transparent; this.lblSynchronization.Name = "lblSynchronization"; // // pbSync // this.pbSync.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pbSync, "pbSync"); this.pbSync.Name = "pbSync"; this.pbSync.TabStop = false; // // cbAutoSignIn // this.cbAutoSignIn.BackColor = System.Drawing.Color.Transparent; this.cbAutoSignIn.Checked = true; this.cbAutoSignIn.CheckState = System.Windows.Forms.CheckState.Checked; resources.ApplyResources(this.cbAutoSignIn, "cbAutoSignIn"); this.cbAutoSignIn.Name = "cbAutoSignIn"; this.cbAutoSignIn.UseVisualStyleBackColor = false; // // pbSignIn // this.pbSignIn.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pbSignIn, "pbSignIn"); this.pbSignIn.Name = "pbSignIn"; this.pbSignIn.TabStop = false; // // cbAutoStart // this.cbAutoStart.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.cbAutoStart, "cbAutoStart"); this.cbAutoStart.Name = "cbAutoStart"; this.cbAutoStart.UseVisualStyleBackColor = false; // // lblSignIn // resources.ApplyResources(this.lblSignIn, "lblSignIn"); this.lblSignIn.BackColor = System.Drawing.Color.Transparent; this.lblSignIn.Name = "lblSignIn"; // // tpProfile // resources.ApplyResources(this.tpProfile, "tpProfile"); this.tpProfile.Controls.Add(this.label2); this.tpProfile.Controls.Add(this.label1); this.tpProfile.Controls.Add(this.label3); this.tpProfile.Controls.Add(this.tbxSurName); this.tpProfile.Controls.Add(this.tbxMiddleName); this.tpProfile.Controls.Add(this.tbxGivenName); this.tpProfile.Controls.Add(this.llNameDetails); this.tpProfile.Controls.Add(this.pbxProfile); this.tpProfile.Controls.Add(this.lblFullName); this.tpProfile.Controls.Add(this.tbFullName); this.tpProfile.Controls.Add(this.btnFullName); this.tpProfile.Controls.Add(this.lblEmail); this.tpProfile.Controls.Add(this.tbEmail); this.tpProfile.Controls.Add(this.button3); this.tpProfile.Controls.Add(this.button1); this.tpProfile.Controls.Add(this.button2); this.tpProfile.Name = "tpProfile"; this.tpProfile.UseVisualStyleBackColor = true; // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label1 // this.label1.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label3 // this.label3.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // tbxSurName // resources.ApplyResources(this.tbxSurName, "tbxSurName"); this.tbxSurName.Name = "tbxSurName"; // // tbxMiddleName // resources.ApplyResources(this.tbxMiddleName, "tbxMiddleName"); this.tbxMiddleName.Name = "tbxMiddleName"; // // tbxGivenName // resources.ApplyResources(this.tbxGivenName, "tbxGivenName"); this.tbxGivenName.Name = "tbxGivenName"; // // llNameDetails // resources.ApplyResources(this.llNameDetails, "llNameDetails"); this.llNameDetails.BackColor = System.Drawing.Color.Transparent; this.llNameDetails.Name = "llNameDetails"; // // pbxProfile // this.pbxProfile.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pbxProfile, "pbxProfile"); this.pbxProfile.Name = "pbxProfile"; this.pbxProfile.Synchronizing = false; this.pbxProfile.TabStop = false; this.pbxProfile.Click += new System.EventHandler(this.pbxProfile_Click); // // lblFullName // this.lblFullName.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.lblFullName, "lblFullName"); this.lblFullName.Name = "lblFullName"; // // tbFullName // resources.ApplyResources(this.tbFullName, "tbFullName"); this.tbFullName.Name = "tbFullName"; // // btnFullName // resources.ApplyResources(this.btnFullName, "btnFullName"); this.btnFullName.Name = "btnFullName"; this.btnFullName.Click += new System.EventHandler(this.btnFullName_Click); // // lblEmail // this.lblEmail.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.lblEmail, "lblEmail"); this.lblEmail.Name = "lblEmail"; // // tbEmail // resources.ApplyResources(this.tbEmail, "tbEmail"); this.tbEmail.Name = "tbEmail"; // // button3 // resources.ApplyResources(this.button3, "button3"); this.button3.Name = "button3"; this.button3.Click += new System.EventHandler(this.button3_Click); // // button1 // resources.ApplyResources(this.button1, "button1"); this.button1.Name = "button1"; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // resources.ApplyResources(this.button2, "button2"); this.button2.Name = "button2"; this.button2.Click += new System.EventHandler(this.button2_Click); // // tpAlerts // this.tpAlerts.Controls.Add(this.label5); this.tpAlerts.Controls.Add(this.pictureBox5); this.tpAlerts.Controls.Add(this.labelLine3); resources.ApplyResources(this.tpAlerts, "tpAlerts"); this.tpAlerts.Name = "tpAlerts"; this.tpAlerts.UseVisualStyleBackColor = true; // // label5 // this.label5.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // pictureBox5 // this.pictureBox5.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pictureBox5, "pictureBox5"); this.pictureBox5.Name = "pictureBox5"; this.pictureBox5.TabStop = false; // // labelLine3 // resources.ApplyResources(this.labelLine3, "labelLine3"); this.labelLine3.BackColor = System.Drawing.Color.Transparent; this.labelLine3.Name = "labelLine3"; // // tpConnection // this.tpConnection.Controls.Add(this.labelLine2); this.tpConnection.Controls.Add(this.pictureBox4); this.tpConnection.Controls.Add(this.label4); resources.ApplyResources(this.tpConnection, "tpConnection"); this.tpConnection.Name = "tpConnection"; this.tpConnection.UseVisualStyleBackColor = true; // // labelLine2 // resources.ApplyResources(this.labelLine2, "labelLine2"); this.labelLine2.BackColor = System.Drawing.Color.Transparent; this.labelLine2.Name = "labelLine2"; // // pictureBox4 // this.pictureBox4.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.pictureBox4, "pictureBox4"); this.pictureBox4.Name = "pictureBox4"; this.pictureBox4.TabStop = false; // // label4 // this.label4.BackColor = System.Drawing.Color.Transparent; resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // tpPresence // resources.ApplyResources(this.tpPresence, "tpPresence"); this.tpPresence.Name = "tpPresence"; this.tpPresence.UseVisualStyleBackColor = true; // // FrmPreferences // this.AcceptButton = this.btnOk; resources.ApplyResources(this, "$this"); this.BackColor = System.Drawing.SystemColors.Control; this.CancelButton = this.btnCancel; this.Controls.Add(this.tcPreferences); this.Controls.Add(this.btnOk); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnApply); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FrmPreferences"; this.ShowInTaskbar = false; this.tcPreferences.ResumeLayout(false); this.tpGeneral.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pbSync)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pbSignIn)).EndInit(); this.tpProfile.ResumeLayout(false); this.tpProfile.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pbxProfile)).EndInit(); this.tpAlerts.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit(); this.tpConnection.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, System.EventArgs e) { QueryProfile(); } /// <summary> /// /// </summary> private void QueryProfile() { pbxProfile.Synchronizing = true; QueryRequestType req = new QueryRequestType(); XpQueryType qt = new XpQueryType(); qt.Select = "/m:IqProfile"; req.XpQuery = new XpQueryType[] { qt }; iqProfileService.BeginQuery(req, new AsyncCallback(OnProfileQueryResponse), iqProfileService); } /// <summary> /// /// </summary> /// <param name="result"></param> private void OnProfileQueryResponse(IAsyncResult result) { IqProfile iqProfile = (IqProfile)result.AsyncState; try { QueryResponseType res = iqProfile.EndQuery(result); pbxProfile.BeginInvoke((MethodInvoker)delegate() { pbxProfile.Synchronizing = false; }); if (res != null && res.XpQueryResponse.Length == 1 && res.XpQueryResponse[0].Status == ResponseStatus.Success) { profile = (IqProfileType)ServiceUtils.GetObject(typeof(IqProfileType), res.XpQueryResponse[0].Any[0]); log.Debug("Profile ChangeNumber: " + profile.ChangeNumber); this.BeginInvoke( (MethodInvoker)delegate() { SetProfile(profile); } ); } } catch (System.Web.Services.Protocols.SoapException se) { log.Error("Failed to query profile", se); MessageBox.Show(se.Message); } } private void SetProfile(IqProfileType profile) { this.tbxGivenName.Text = ""; this.tbxMiddleName.Text = ""; this.tbxSurName.Text = ""; this.tbEmail.Text = ""; if (profile == null) { return; } if (profile.Name != null && profile.Name.Length > 0) { this.tbxGivenName.Text = profile.Name[0].GivenName.Value; this.tbxMiddleName.Text = profile.Name[0].MiddleName.Value; this.tbxSurName.Text = profile.Name[0].SurName.Value; } if (profile.EmailAddress != null && profile.EmailAddress.Length > 0) { this.tbEmail.Text = profile.EmailAddress[0].Email; } } /// <summary> /// Creates a single string concatenating full name details such as /// first-, middle- and surname and title. /// </summary> /// <param name="v"></param> /// <returns></returns> private string MakeFullName(NameType v) { if (v == null) { return ""; } StringBuilder sb = new StringBuilder(); if (v.Title != null) { sb.Append(v.Title.Value + " "); } if (v.GivenName != null) { sb.Append(v.GivenName.Value + " "); } if (v.MiddleName != null) { sb.Append(v.MiddleName.Value + " "); } if (v.SurName != null) { sb.Append(v.SurName.Value + " "); } if (v.Suffix != null) { sb.Append(v.Suffix.Value + " "); } return sb.ToString().Trim(); } private LocalizableString MyLocalizableString(string v) { LocalizableString s = new LocalizableString(); s.lang = "en-US"; s.Value = v; return s; } private void button2_Click(object sender, System.EventArgs e) { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "/m:IqProfile"; req.MinOccurs = 1; req.MaxOccurs = 1; // update internal structure before updating remotely NameType name = null; if (profile.Name == null) { profile.Name = new NameType[1]; name = new NameType(); } else { name = profile.Name[0]; } //name.Title = MyLocalizableString("x"); name.GivenName = MyLocalizableString(tbxGivenName.Text); name.MiddleName = MyLocalizableString(tbxMiddleName.Text); name.SurName = MyLocalizableString(tbxSurName.Text); //name.Suffix = MyLocalizableString("x"); profile.Name[0] = name; EmailAddressBlueType email = null; if (profile.EmailAddress == null) { profile.EmailAddress = new EmailAddressBlueType[1]; email = new EmailAddressBlueType(); } else { email = profile.EmailAddress[0]; } email.Name = MyLocalizableString("Personal E-mail"); email.Email = tbEmail.Text; profile.EmailAddress[0] = email; req.Any = new XmlElement[] { ServiceUtils.SetObject( profile, "IqProfile" ) }; iqProfileService.BeginReplace(req, new AsyncCallback(OnProfileReplaceResponse), iqProfileService); } private void OnProfileReplaceResponse(IAsyncResult result) { IqProfile iqProfile = (IqProfile)result.AsyncState; try { ReplaceResponseType res = iqProfile.EndReplace(result); if (res != null && res.Status == ResponseStatus.Success) { MessageBox.Show("Updated"); profile.ChangeNumber = res.NewChangeNumber; } else { MessageBox.Show("Failed to update"); } } catch (System.Web.Services.Protocols.SoapException se) { MessageBox.Show(se.Message); } } private void button3_Click(object sender, System.EventArgs e) { InsertRequestType req = new InsertRequestType(); req.Select = "/m:IqProfile"; req.MinOccurs = 1; req.MinOccursSpecified = true; profile.EmailAddress = new EmailAddressBlueType[1]; profile.EmailAddress[0] = new EmailAddressBlueType(); profile.EmailAddress[0].Email = "peter@theill.com"; profile.EmailAddress[0].Name = new LocalizableString(); profile.EmailAddress[0].Name.lang = "en-US"; profile.EmailAddress[0].Name.Value = "Personal E-mail"; //req.Any = new XmlElement[] { ServiceUtils.SetObject(typeof(emailAddressType), profile.emailAddress[0], "emailAddress") }; req.Any = new XmlElement[] { ServiceUtils.SetObject(profile.EmailAddress[0], "EmailAddress") }; InsertResponseType ires = iqProfileService.Insert(req); MessageBox.Show(ires.Status.ToString()); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnFullName_Click(object sender, System.EventArgs e) { // open "Name" section of IqProfile FrmProfileName a = new FrmProfileName(); a.ProfileName = profile.Name[0]; if (a.ShowDialog() == DialogResult.OK) { profile.Name[0] = a.ProfileName; tbFullName.Text = a.ProfileName.GivenName.Value + " " + a.ProfileName.SurName.Value; } } private void pbxProfile_Click(object sender, System.EventArgs e) { } private void btnOk_Click(object sender, EventArgs e) { this.Dispose(); } private void btnCancel_Click(object sender, EventArgs e) { this.Dispose(); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.MessagingSystem; namespace ASC.AuditTrail.Mappers { internal class DocumentsActionMapper { public static Dictionary<MessageAction, MessageMaps> GetMaps() { return new Dictionary<MessageAction, MessageMaps> { { MessageAction.FileCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileRenamed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileRenamed", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.UserFileUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "UserFileUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCreatedVersion, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileCreatedVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDeletedVersion, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FileDeletedVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileRestoreVersion, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileRestoreVersion", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdatedRevisionComment, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUpdatedRevisionComment", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileLocked, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileLocked", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUnlocked, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FileUnlocked", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUpdatedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "FileUpdatedAccess", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDownloaded, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "FileDownloaded", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDownloadedAs, new MessageMaps { ActionTypeTextResourceName = "DownloadActionType", ActionTextResourceName = "FileDownloadedAs", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileUploaded, new MessageMaps { ActionTypeTextResourceName = "UploadActionType", ActionTextResourceName = "FileUploaded", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileImported, new MessageMaps { ActionTypeTextResourceName = "ImportActionType", ActionTextResourceName = "FileImported", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCopied, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FileCopied", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileCopiedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FileCopiedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMoved, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMoved", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMovedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMovedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileMovedToTrash, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FileMovedToTrash", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FileDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FolderCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FolderCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderRenamed, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "FolderRenamed", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderUpdatedAccess, new MessageMaps { ActionTypeTextResourceName = "UpdateAccessActionType", ActionTextResourceName = "FolderUpdatedAccess", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderCopied, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FolderCopied", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderCopiedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "CopyActionType", ActionTextResourceName = "FolderCopiedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMoved, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMoved", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMovedWithOverwriting, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMovedWithOverwriting", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderMovedToTrash, new MessageMaps { ActionTypeTextResourceName = "MoveActionType", ActionTextResourceName = "FolderMovedToTrash", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.FolderDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "FolderDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FoldersModule" } }, { MessageAction.ThirdPartyCreated, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "ThirdPartyCreated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.ThirdPartyUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "ThirdPartyUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.ThirdPartyDeleted, new MessageMaps { ActionTypeTextResourceName = "DeleteActionType", ActionTextResourceName = "ThirdPartyDeleted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsThirdPartySettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsThirdPartySettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsOverwritingSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsOverwritingSettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsForcesave, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsForcesave", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsStoreForcesave, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsStoreForcesave", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.DocumentsUploadingFormatsSettingsUpdated, new MessageMaps { ActionTypeTextResourceName = "UpdateActionType", ActionTextResourceName = "DocumentsUploadingFormatsSettingsUpdated", ProductResourceName = "DocumentsProduct", ModuleResourceName = "DocumentsSettingsModule" } }, { MessageAction.FileConverted, new MessageMaps { ActionTypeTextResourceName = "CreateActionType", ActionTextResourceName = "FileConverted", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileSendAccessLink, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FileSendAccessLink", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.FileChangeOwner, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FileChangeOwner", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.DocumentSignComplete, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FilesDocumentSigned", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, { MessageAction.DocumentSendToSign, new MessageMaps { ActionTypeTextResourceName = "SendActionType", ActionTextResourceName = "FilesRequestSign", ProductResourceName = "DocumentsProduct", ModuleResourceName = "FilesModule" } }, }; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TestRepository.cs" company="KlusterKite"> // All rights reserved // </copyright> // <summary> // The test nuget repository // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace KlusterKite.NodeManager.Tests.Mock { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using JetBrains.Annotations; using KlusterKite.NodeManager.Launcher.Utils; #if CORECLR using Microsoft.Extensions.DependencyModel; #endif using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Protocol.Core.Types; using NuGet.Versioning; /// <summary> /// The test nuget repository /// </summary> internal class TestRepository : IPackageRepository { /// <inheritdoc /> public TestRepository(params TestPackage[] packages) { this.Packages = packages?.ToList() ?? new List<TestPackage>(); } /// <summary> /// Gets the list of defined packages packages. /// </summary> [UsedImplicitly] public List<TestPackage> Packages { get; } /// <summary> /// Creates the test repository /// </summary> /// <returns>The test repository</returns> public static IPackageRepository CreateRepositoryFromLoadedAssemblies() { var loadedAssemblies = GetLoadedAssemblies() #if APPDOMAIN .Where(a => !a.GlobalAssemblyCache && !a.IsDynamic) #elif CORECLR .Where(a => !a.IsDynamic) #endif .ToList(); var ignoredAssemblies = loadedAssemblies.SelectMany(a => a.GetReferencedAssemblies()) .Where(r => loadedAssemblies.All(a => a.FullName != r.FullName)).Select(r => r.FullName).ToList(); var assemblies = loadedAssemblies.ToArray(); var packages = assemblies.Where(a => !ignoredAssemblies.Contains(a.FullName)) .Select(p => CreateTestPackage(p, assemblies)).GroupBy(a => a.Identity.Id) .Select(g => g.OrderByDescending(a => a.Identity.Id).First()).ToArray(); return new TestRepository(packages); } /// <inheritdoc /> public Task<IEnumerable<string>> ExtractPackage( IPackageSearchMetadata package, string frameworkName, string executionDir, string tmpDir) { var testPackage = package as TestPackage; if (testPackage == null) { throw new InvalidOperationException(); } return Task.FromResult(testPackage.Extract(frameworkName, executionDir, tmpDir)); } /// <inheritdoc /> public async Task<Dictionary<PackageIdentity, IEnumerable<string>>> ExtractPackage( IEnumerable<PackageIdentity> packages, string runtime, string frameworkName, string executionDir, string tmpDir, Action<string> logAction = null) { var packagesToExtract = packages.Select(p => this.Packages.First(m => m.Identity.Equals(p))); var tasks = packagesToExtract.ToDictionary( p => p.Identity, async p => await this.ExtractPackage(p, frameworkName, executionDir, tmpDir)); await Task.WhenAll(tasks.Values); return tasks.ToDictionary(p => p.Key, p => p.Value.Result); } /// <inheritdoc /> public Task<IPackageSearchMetadata> GetAsync(string id) { return Task.FromResult<IPackageSearchMetadata>( this.Packages.Where(p => p.Identity.Id == id).OrderByDescending(p => p.Identity.Version) .FirstOrDefault()); } /// <inheritdoc /> public Task<IPackageSearchMetadata> GetAsync(string id, NuGetVersion version) { return Task.FromResult<IPackageSearchMetadata>( this.Packages.FirstOrDefault(p => p.Identity.Id == id && p.Identity.Version == version)); } /// <inheritdoc /> public Task<IEnumerable<IPackageSearchMetadata>> SearchAsync(string terms, bool includePreRelease) { return Task.FromResult( this.Packages.Where(p => p.Identity.Id.ToLowerInvariant().Contains(terms.ToLowerInvariant())) .Cast<IPackageSearchMetadata>()); } /// <summary> /// Creates test package from assembly /// </summary> /// <param name="assembly">The source assembly</param> /// <param name="allAssemblies">The list of all defined assemblies</param> /// <returns>The test package</returns> private static TestPackage CreateTestPackage(Assembly assembly, Assembly[] allAssemblies) { var dependencies = assembly.GetReferencedAssemblies().Select( d => { var dependentAssembly = allAssemblies.FirstOrDefault(a => a.GetName().Name == d.Name); return dependentAssembly != null && !dependentAssembly.IsDynamic #if APPDOMAIN && !dependentAssembly.GlobalAssemblyCache #endif ? dependentAssembly : null; }).Where(d => d != null).Select( d => new PackageDependency( d.GetName().Name, new VersionRange(NuGetVersion.Parse(d.GetName().Version.ToString())))).ToList(); var standardDependencies = new PackageDependencyGroup( NuGetFramework.ParseFrameworkName( ConfigurationCheckTestsBase.NetCore, DefaultFrameworkNameProvider.Instance), dependencies); var net46Dependencies = new PackageDependencyGroup( NuGetFramework.ParseFrameworkName( ConfigurationCheckTestsBase.Net46, DefaultFrameworkNameProvider.Instance), dependencies); Func<string, string, string, IEnumerable<string>> extaction = (framework, destination, temp) => { if (string.IsNullOrWhiteSpace(assembly.Location)) { throw new InvalidOperationException("Assembly has no location"); } var fileName = Path.GetFileName(assembly.Location); File.Copy(assembly.Location, Path.Combine(destination, fileName)); return new[] { fileName }; }; return new TestPackage(assembly.GetName().Name, assembly.GetName().Version.ToString()) { DependencySets = new[] { standardDependencies, net46Dependencies }, Extract = extaction }; } /// <summary> /// Gets the list of loaded assemblies /// </summary> /// <returns>The list of loaded assemblies</returns> private static IEnumerable<Assembly> GetLoadedAssemblies() { #if APPDOMAIN var assemblies = new List<Assembly>(); var currentDirectory = Path.GetFullPath("."); foreach (var file in Directory.GetFiles(currentDirectory, "*.dll")) { try { assemblies.Add(Assembly.ReflectionOnlyLoadFrom(file)); } catch { // ignore } } foreach (var file in Directory.GetFiles(currentDirectory, "*.exe")) { try { assemblies.Add(Assembly.ReflectionOnlyLoadFrom(file)); } catch { // ignore } } return assemblies; #elif CORECLR var assemblies = new List<Assembly>(); var dependencies = DependencyContext.Default.RuntimeLibraries; foreach (var library in dependencies) { try { var assembly = Assembly.Load(new AssemblyName(library.Name)); assemblies.Add(assembly); } catch { // do nothing can't if can't load assembly } } return assemblies; #endif } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Exception information provided through /// a call to one of the Logger.*Exception() methods. /// </summary> [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer { private string format; private string innerFormat = string.Empty; private ExceptionDataTarget[] exceptionDataTargets; private ExceptionDataTarget[] innerExceptionDataTargets; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class. /// </summary> public ExceptionLayoutRenderer() { this.Format = "message"; this.Separator = " "; this.InnerExceptionSeparator = EnvironmentHelper.NewLine; this.MaxInnerExceptionLevel = 0; } private delegate void ExceptionDataTarget(StringBuilder sb, Exception ex); /// <summary> /// Gets or sets the format of the output. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultParameter] public string Format { get { return this.format; } set { this.format = value; this.exceptionDataTargets = CompileFormat(value); } } /// <summary> /// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerFormat { get { return this.innerFormat; } set { this.innerFormat = value; this.innerExceptionDataTargets = CompileFormat(value); } } /// <summary> /// Gets or sets the separator used to concatenate parts specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(" ")] public string Separator { get; set; } /// <summary> /// Gets or sets the maximum number of inner exceptions to include in the output. /// By default inner exceptions are not enabled for compatibility with NLog 1.0. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(0)] public int MaxInnerExceptionLevel { get; set; } /// <summary> /// Gets or sets the separator between inner exceptions. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerExceptionSeparator { get; set; } /// <summary> /// Renders the specified exception information and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (logEvent.Exception != null) { var sb2 = new StringBuilder(128); string separator = string.Empty; foreach (ExceptionDataTarget targetRenderFunc in this.exceptionDataTargets) { sb2.Append(separator); targetRenderFunc(sb2, logEvent.Exception); separator = this.Separator; } Exception currentException = logEvent.Exception.InnerException; int currentLevel = 0; while (currentException != null && currentLevel < this.MaxInnerExceptionLevel) { // separate inner exceptions sb2.Append(this.InnerExceptionSeparator); separator = string.Empty; foreach (ExceptionDataTarget targetRenderFunc in this.innerExceptionDataTargets ?? this.exceptionDataTargets) { sb2.Append(separator); targetRenderFunc(sb2, currentException); separator = this.Separator; } currentException = currentException.InnerException; currentLevel++; } builder.Append(sb2.ToString()); } } /// <summary> /// Appends the Message of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The exception containing the Message to append.</param> protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception exception) { var message = string.Format("Exception in {0}.AppendMessage(): {1}.", typeof(ExceptionLayoutRenderer).FullName, exception.GetType().FullName); sb.Append("NLog message:" + message); if (InternalLogger.IsWarnEnabled) { InternalLogger.Warn(message); } } } /// <summary> /// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose method name should be appended.</param> protected virtual void AppendMethod(StringBuilder sb, Exception ex) { #if SILVERLIGHT sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace)); #else if (ex.TargetSite != null) { sb.Append(ex.TargetSite.ToString()); } #endif } /// <summary> /// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose stack trace should be appended.</param> protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { sb.Append(ex.StackTrace); } /// <summary> /// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose call to ToString() should be appended.</param> protected virtual void AppendToString(StringBuilder sb, Exception ex) { sb.Append(ex.ToString()); } /// <summary> /// Appends the type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose type should be appended.</param> protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().FullName); } /// <summary> /// Appends the short type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose short type should be appended.</param> protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } /// <summary> /// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose Data property elements should be appended.</param> protected virtual void AppendData(StringBuilder sb, Exception ex) { string separator = string.Empty; foreach (var key in ex.Data.Keys) { sb.Append(separator); sb.AppendFormat("{0}: {1}", key, ex.Data[key]); separator = ";"; } } private ExceptionDataTarget[] CompileFormat(string formatSpecifier) { string[] parts = formatSpecifier.Replace(" ", string.Empty).Split(','); var dataTargets = new List<ExceptionDataTarget>(); foreach (string s in parts) { switch (s.ToUpper(CultureInfo.InvariantCulture)) { case "MESSAGE": dataTargets.Add(AppendMessage); break; case "TYPE": dataTargets.Add(AppendType); break; case "SHORTTYPE": dataTargets.Add(AppendShortType); break; case "TOSTRING": dataTargets.Add(AppendToString); break; case "METHOD": dataTargets.Add(AppendMethod); break; case "STACKTRACE": dataTargets.Add(AppendStackTrace); break; case "DATA": dataTargets.Add(AppendData); break; default: InternalLogger.Warn("Unknown exception data target: {0}", s); break; } } return dataTargets.ToArray(); } #if SILVERLIGHT protected static string ParseMethodNameFromStackTrace(string stackTrace) { // get the first line of the stack trace string stackFrameLine; int p = stackTrace.IndexOfAny(new[] { '\r', '\n' }); if (p >= 0) { stackFrameLine = stackTrace.Substring(0, p); } else { stackFrameLine = stackTrace; } // stack trace is composed of lines which look like this // // at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something) // // "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis int lastSpace = -1; int startPos = 0; int endPos = stackFrameLine.Length; for (int i = 0; i < stackFrameLine.Length; ++i) { switch (stackFrameLine[i]) { case ' ': lastSpace = i; break; case '(': startPos = lastSpace + 1; break; case ')': endPos = i + 1; // end the loop i = stackFrameLine.Length; break; } } return stackTrace.Substring(startPos, endPos - startPos); } #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class DateExtensions { /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetNull(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetNullAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetInvalidDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetInvalidDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetInvalidDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetInvalidDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetOverflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetOverflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetOverflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetOverflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetUnderflowDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetUnderflowDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow date value /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetUnderflowDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetUnderflowDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMaxDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMaxDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMaxDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMaxDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMaxDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMaxDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMaxDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetMaxDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> public static void PutMinDate(this IDate operations, DateTime? dateBody) { Task.Factory.StartNew(s => ((IDate)s).PutMinDateAsync(dateBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dateBody'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutMinDateAsync( this IDate operations, DateTime? dateBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMinDateWithHttpMessagesAsync(dateBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateTime? GetMinDate(this IDate operations) { return Task.Factory.StartNew(s => ((IDate)s).GetMinDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateTime?> GetMinDateAsync( this IDate operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateTime?> result = await operations.GetMinDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
/* * Magix - A Web Application Framework for Humans * Copyright 2010 - 2014 - thomas@magixilluminate.com * Magix is licensed as MITx11, see enclosed License.txt File for Details. */ using System; using System.IO; using System.Collections.Generic; using sys = System.Security.Cryptography.X509Certificates; using sys2 = System.Security.Cryptography; using MimeKit; using MimeKit.Cryptography; using Org.BouncyCastle.X509; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto; using Magix.Core; using Org.BouncyCastle.Math; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Prng; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Crypto.Parameters; namespace Magix.cryptography { /* * signs emails */ internal class CryptographyHelper { /* * returns true if email address can sign email */ public static bool CanSign(string email) { try { MailboxAddress signer = new MailboxAddress("", email); TextPart entity = new TextPart("text"); using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity); return true; } } catch { return false; } } /* * returns true if email can be encrypted */ public static string CanEncrypt(Node emails) { if (emails.Count == 0) return "there are no recipients"; try { List<MailboxAddress> list = new List<MailboxAddress>(); foreach (Node idx in emails) list.Add(new MailboxAddress("", idx.Get<string>())); TextPart entity = new TextPart("text"); using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { ApplicationPkcs7Mime.Encrypt(ctx, list, entity); } return null; } catch(Exception err) { return err.Message; } } /* * tries to sign a MimeEntity */ public static MimeEntity SignEntity(MimeEntity entity, MailboxAddress signer) { using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { return MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity); } } /* * tries to encrypt a MimeEntity */ public static MimeEntity EncryptEntity(MimeEntity entity, IEnumerable<MailboxAddress> list) { using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { return ApplicationPkcs7Mime.Encrypt(ctx, list, entity); } } /* * tries to sign and encrypt a MimeEntity */ public static MimeEntity SignAndEncryptEntity(MimeEntity entity, MailboxAddress signer, IEnumerable<MailboxAddress> list) { using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { return ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, DigestAlgorithm.Sha1, list, entity); } } /* * imports the given certificate file into certificate database */ public static void ImportCertificate(string certificateFile, string password) { Node getBase = new Node(); ActiveEvents.Instance.RaiseActiveEvent( typeof(CryptographyHelper), "magix.file.get-base-path", getBase); string basePath = getBase["path"].Get<string>(); using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser)) { using (FileStream stream = File.OpenRead(basePath + certificateFile)) { if (!string.IsNullOrEmpty(password)) ctx.Import(stream, password); else ctx.Import(stream); } } } /* * removes all certificates matching subjectName from database */ internal static void RemoveCertificates(string subjectName) { foreach (sys.StoreLocation idxStore in new sys.StoreLocation[] { sys.StoreLocation.CurrentUser }) { sys.X509Store store = new sys.X509Store(idxStore); store.Open(sys.OpenFlags.ReadOnly); try { sys.X509Certificate2Collection coll = store.Certificates.Find(sys.X509FindType.FindBySubjectName, subjectName, false); if (coll.Count > 0) store.RemoveRange(coll); } finally { store.Close(); } } } /* * creates a certificate and a private key and installs into windows registry */ public static void CreateCertificateKey( string subjectName, string issuerName, string signatureAlgorithm, int strength, DateTime begin, DateTime end, string subjectCountryCode, string subjectOrganization, string subjectTitle, string issuerCountryCode, string issuerOrganization, string issuerTitle, string subjectCommonName, string issuerCommonName) { RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(new CryptoApiRandomGenerator()); keyPairGenerator.Init(new KeyGenerationParameters(secureRandom, strength)); AsymmetricCipherKeyPair asCipherKeyPair = keyPairGenerator.GenerateKeyPair(); AsymmetricKeyParameter publicKey = asCipherKeyPair.Public; RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)asCipherKeyPair.Private; X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), secureRandom); certificateGenerator.SetSerialNumber(serialNumber); string subjectNameString = "E=" + subjectName; if (subjectCommonName != null) subjectNameString += ", CN=" + subjectCommonName; if (subjectCountryCode != null) subjectNameString += ", C=" + subjectCountryCode; if (subjectOrganization != null) subjectNameString += ", O=" + subjectOrganization; if (subjectTitle != null) subjectNameString += ", T=" + subjectTitle; certificateGenerator.SetSubjectDN(new X509Name(subjectNameString)); string issuerNameString = "E=" + issuerName; if (issuerCommonName != null) issuerNameString += ", CN=" + issuerCommonName; if (issuerCountryCode != null) issuerNameString += ", C=" + issuerCountryCode; if (issuerOrganization != null) issuerNameString += ", O=" + issuerOrganization; if (issuerTitle != null) issuerNameString += ", T=" + issuerTitle; certificateGenerator.SetIssuerDN(new X509Name(issuerNameString)); certificateGenerator.SetNotBefore(begin); certificateGenerator.SetNotAfter(end); certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm); certificateGenerator.SetPublicKey(publicKey); X509Certificate certificate = certificateGenerator.Generate(privateKey); sys.X509Certificate2 windowsCertificate = new sys.X509Certificate2(DotNetUtilities.ToX509Certificate(certificate)); windowsCertificate.PrivateKey = ConvertToSystemKey(privateKey); InstallIntoRegistry(windowsCertificate); } /* * converts a bouncy castle private key to a windows private key */ private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey) { sys2.CspParameters cspPars = new sys2.CspParameters { KeyContainerName = Guid.NewGuid().ToString(), KeyNumber = (int)sys2.KeyNumber.Exchange }; sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars); sys2.RSAParameters rsaParameters = new sys2.RSAParameters { Modulus = privateKey.Modulus.ToByteArrayUnsigned(), P = privateKey.P.ToByteArrayUnsigned(), Q = privateKey.Q.ToByteArrayUnsigned(), DP = privateKey.DP.ToByteArrayUnsigned(), DQ = privateKey.DQ.ToByteArrayUnsigned(), InverseQ = privateKey.QInv.ToByteArrayUnsigned(), D = privateKey.Exponent.ToByteArrayUnsigned(), Exponent = privateKey.PublicExponent.ToByteArrayUnsigned() }; rsaCryptoProvider.ImportParameters(rsaParameters); return rsaCryptoProvider; } /* * installs certificate and key into windows registry */ private static void InstallIntoRegistry(sys.X509Certificate2 windowsCertificate) { sys.X509Store store = new sys.X509Store(); store.Open(sys.OpenFlags.ReadWrite); try { store.Add(windowsCertificate); } finally { store.Close(); } } } }
// // Author: // AKIHIRO Uehara (u-akihiro@reinforce-lab.com) // // Copyright 2010 Reinforce Lab. // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Runtime.InteropServices; using MonoMac.AudioToolbox; namespace MonoMac.AudioUnitWrapper { [Obsolete ("Use AudioConverter")] public class _AudioConverter : IDisposable { #region Variables readonly GCHandle _handle; IntPtr _audioConverter; #endregion #region Properties public event EventHandler<_AudioConverterEventArgs> EncoderCallback; public Byte[] DecompressionMagicCookie { set { byte[] data = value; if (null != data) { AudioConverterSetProperty(_audioConverter, AudioConverterPropertyIDType.kAudioConverterDecompressionMagicCookie, (uint)data.Length, data); } } } #endregion #region Constructor private _AudioConverter() { _handle = GCHandle.Alloc(this); _audioConverter = new IntPtr(); } #endregion #region Private methods [MonoMac.MonoPInvokeCallback(typeof(AudioConverterComplexInputDataProc))] static int complexInputDataProc( IntPtr inAudioConverrter, ref uint ioNumberDataPackets, AudioBufferList ioData, ref AudioStreamPacketDescription[] outDataPacketDescription, //AudioStreamPacketDescription** IntPtr inUserData ) { // getting audiounit instance var handler = GCHandle.FromIntPtr(inUserData); var inst = (_AudioConverter)handler.Target; // evoke event handler with an argument if (inst.EncoderCallback != null) { var args = new _AudioConverterEventArgs( ioNumberDataPackets, ioData, outDataPacketDescription); inst.EncoderCallback(inst, args); } return 0; // noerror } #endregion #region Public methods public static _AudioConverter CreateInstance(AudioStreamBasicDescription srcFormat, AudioStreamBasicDescription destFormat) { _AudioConverter inst = new _AudioConverter(); int err_code; unsafe{ IntPtr ptr = inst._audioConverter; IntPtr pptr =(IntPtr)(&ptr); err_code = AudioConverterNew(ref srcFormat, ref destFormat, pptr); } if (err_code != 0) { throw new ArgumentException(String.Format("Error code:{0}", err_code)); } return inst; } public void FillBuffer(AudioBufferList data, uint numberFrames, AudioStreamPacketDescription[] packetDescs) { uint numPackets = numberFrames; int err =AudioConverterFillComplexBuffer( _audioConverter, complexInputDataProc, GCHandle.ToIntPtr(_handle), ref numPackets, data, packetDescs); if(err != 0 || numPackets == 0) { throw new InvalidOperationException(String.Format("Error code:{0}", err)); } } #endregion #region IDisposable public void Dispose() { _handle.Free(); } #endregion #region Interop delegate int AudioConverterComplexInputDataProc( IntPtr inAudioConverrter, ref uint ioNumberDataPackets, AudioBufferList ioData, ref AudioStreamPacketDescription[] outDataPacketDescription, IntPtr inUserData ); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "AudioConverterNew")] static extern int AudioConverterFillComplexBuffer( IntPtr inAudioConverter, AudioConverterComplexInputDataProc inInputDataProc, IntPtr inInputDataProcUserData, ref uint ioOutputDataPacketSize, AudioBufferList outOutputData, AudioStreamPacketDescription[] outPacketDescription); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "AudioConverterNew")] static extern int AudioConverterNew( ref MonoMac.AudioToolbox.AudioStreamBasicDescription inSourceFormat, ref MonoMac.AudioToolbox.AudioStreamBasicDescription inDestinationFormat, IntPtr outAudioConverter); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "AudioConverterSetProperty")] static extern int AudioConverterSetProperty(IntPtr inAudioConverter, [MarshalAs(UnmanagedType.U4)] AudioConverterPropertyIDType inID, uint inDataSize, IntPtr inPrppertyData ); [DllImport(MonoMac.Constants.AudioToolboxLibrary, EntryPoint = "AudioConverterSetProperty")] static extern int AudioConverterSetProperty(IntPtr inAudioConverter, [MarshalAs(UnmanagedType.U4)] AudioConverterPropertyIDType inID, uint inDataSize, byte[] inPrppertyData ); enum AudioConverterPropertyIDType // typedef UInt32 AudioConverterPropertyID { //kAudioConverterPropertyMinimumInputBufferSize = 'mibs', //kAudioConverterPropertyMinimumOutputBufferSize = 'mobs', //kAudioConverterPropertyMaximumInputBufferSize = 'xibs', //kAudioConverterPropertyMaximumInputPacketSize = 'xips', //kAudioConverterPropertyMaximumOutputPacketSize = 'xops', //kAudioConverterPropertyCalculateInputBufferSize = 'cibs', //kAudioConverterPropertyCalculateOutputBufferSize = 'cobs', //kAudioConverterPropertyInputCodecParameters = 'icdp', //kAudioConverterPropertyOutputCodecParameters = 'ocdp', //kAudioConverterSampleRateConverterAlgorithm = 'srci', //kAudioConverterSampleRateConverterComplexity = 'srca', //kAudioConverterSampleRateConverterQuality = 'srcq', //kAudioConverterSampleRateConverterInitialPhase = 'srcp', //kAudioConverterCodecQuality = 'cdqu', //kAudioConverterPrimeMethod = 'prmm', //kAudioConverterPrimeInfo = 'prim', //kAudioConverterChannelMap = 'chmp', kAudioConverterDecompressionMagicCookie = 0x646d6763, //'dmgc', //kAudioConverterCompressionMagicCookie = 'cmgc', //kAudioConverterEncodeBitRate = 'brat', //kAudioConverterEncodeAdjustableSampleRate = 'ajsr', //kAudioConverterInputChannelLayout = 'icl ', //kAudioConverterOutputChannelLayout = 'ocl ', //kAudioConverterApplicableEncodeBitRates = 'aebr', //kAudioConverterAvailableEncodeBitRates = 'vebr', //kAudioConverterApplicableEncodeSampleRates = 'aesr', //kAudioConverterAvailableEncodeSampleRates = 'vesr', //kAudioConverterAvailableEncodeChannelLayoutTags = 'aecl', //kAudioConverterCurrentOutputStreamDescription = 'acod', //kAudioConverterCurrentInputStreamDescription = 'acid', //kAudioConverterPropertySettings = 'acps', //kAudioConverterPropertyBitDepthHint = 'acbd', //kAudioConverterPropertyFormatList = 'flst' }; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #region Fast Binary format /* .----------.--------------. .----------.---------. struct hierarchy | struct | BT_STOP_BASE |...| struct | BT_STOP | '----------'--------------' '----------'---------' .----------.----------. .----------. struct | field | field |...| field | '----------'----------' '----------' .------.----.----------. field | type | id | value | '------'----'----------' .---.---.---.---.---.---.---.---. i - id bits type | 0 | 0 | 0 | t | t | t | t | t | t - type bits '---'---'---'---'---'---'---'---' v - value bits 4 0 id .---. .---.---. .---. | i |...| i | i |...| i | '---' '---'---' '---' 7 0 15 8 .---.---.---.---.---.---.---.---. value bool | | | | | | | | v | '---'---'---'---'---'---'---'---' 0 integer, little endian float, double .-------.------------. string, wstring | count | characters | '-------'------------' count variable uint32 count of 1-byte or 2-byte characters characters 1-byte or 2-byte characters .-------.-------.-------. blob, list, set, | type | count | items | vector, nullable '-------'-------'-------' .---.---.---.---.---.---.---.---. type | | | | t | t | t | t | t | '---'---'---'---'---'---'---'---' 4 0 count variable uint32 count of items items each item encoded according to its type .----------.------------.-------.-----.-------. map | key type | value type | count | key | value | '----------'------------'-------'-----'-------' .---.---.---.---.---.---.---.---. key type, | | | | t | t | t | t | t | value type '---'---'---'---'---'---'---'---' 4 0 count variable encoded uint32 count of {key,mapped} pairs key, mapped each item encoded according to its type variable uint32 .---.---. .---..---.---. .---..---.---. .---..---.---. .---..---.---.---.---. .---. | 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 0 | 0 | 0 | v |...| v | '---'---' '---''---'---' '---''---'---' '---''---'---' '---''---'---'---'---' '---' 6 0 13 7 20 14 27 21 31 28 1 to 5 bytes, high bit of every byte indicates if there is another byte */ #endregion namespace Bond.Protocols { using System; using System.IO; using System.Runtime.CompilerServices; using System.Text; using Bond.IO; /// <summary> /// Writer for the Fast Binary tagged protocol /// </summary> /// <typeparam name="O">Implementation of IOutputStream interface</typeparam> [Reader(typeof(FastBinaryReader<>))] public struct FastBinaryWriter<O> : IProtocolWriter where O : IOutputStream { const ushort Magic = (ushort)ProtocolType.FAST_PROTOCOL; readonly O output; readonly ushort version; /// <summary> /// Create an instance of FastBinaryWriter /// </summary> /// <param name="output">Serialized payload output</param> /// <param name="version">Protocol version</param> public FastBinaryWriter(O output, ushort version = 1) { this.output = output; this.version = version; } /// <summary> /// Write protocol magic number and version /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteVersion() { output.WriteUInt16(Magic); output.WriteUInt16(version); } #region Complex types /// <summary> /// Start writing a struct /// </summary> /// <param name="metadata">Schema metadata</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteStructBegin(Metadata metadata) {} /// <summary> /// Start writing a base struct /// </summary> /// <param name="metadata">Base schema metadata</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteBaseBegin(Metadata metadata) {} /// <summary> /// End writing a struct /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteStructEnd() { output.WriteUInt8((Byte)BondDataType.BT_STOP); } /// <summary> /// End writing a base struct /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteBaseEnd() { output.WriteUInt8((Byte)BondDataType.BT_STOP_BASE); } /// <summary> /// Start writing a field /// </summary> /// <param name="type">Type of the field</param> /// <param name="id">Identifier of the field</param> /// <param name="metadata">Metadata of the field</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata) { output.WriteUInt8((byte) type); output.WriteUInt16(id); } /// <summary> /// Indicate that field was omitted because it was set to its default value /// </summary> /// <param name="dataType">Type of the field</param> /// <param name="id">Identifier of the field</param> /// <param name="metadata">Metadata of the field</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata) {} /// <summary> /// End writing a field /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteFieldEnd() {} /// <summary> /// Start writing a list or set container /// </summary> /// <param name="count">Number of elements in the container</param> /// <param name="elementType">Type of the elements</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteContainerBegin(int count, BondDataType elementType) { output.WriteUInt8((byte)elementType); output.WriteVarUInt32((uint)count); } /// <summary> /// Start writing a map container /// </summary> /// <param name="count">Number of elements in the container</param> /// <param name="keyType">Type of the keys</param> /// /// <param name="valueType">Type of the values</param> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType) { output.WriteUInt8((byte)keyType); output.WriteUInt8((byte)valueType); output.WriteVarUInt32((uint)count); } /// <summary> /// End writing a container /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteContainerEnd() {} /// <summary> /// Write array of bytes verbatim /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteBytes(ArraySegment<byte> data) { output.WriteBytes(data); } #endregion #region Primitive types /// <summary> /// Write an UInt8 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteUInt8(Byte value) { output.WriteUInt8(value); } /// <summary> /// Write an UInt16 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteUInt16(UInt16 value) { output.WriteUInt16(value); } /// <summary> /// Write an UInt16 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteUInt32(UInt32 value) { output.WriteUInt32(value); } /// <summary> /// Write an UInt64 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteUInt64(UInt64 value) { output.WriteUInt64(value); } /// <summary> /// Write an Int8 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteInt8(SByte value) { output.WriteUInt8((Byte)value); } /// <summary> /// Write an Int16 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteInt16(Int16 value) { output.WriteUInt16((ushort)value); } /// <summary> /// Write an Int32 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteInt32(Int32 value) { output.WriteUInt32((uint)value); } /// <summary> /// Write an Int64 /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteInt64(Int64 value) { output.WriteUInt64((ulong)value); } /// <summary> /// Write a float /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteFloat(float value) { output.WriteFloat(value); } /// <summary> /// Write a double /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteDouble(double value) { output.WriteDouble(value); } /// <summary> /// Write a bool /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteBool(bool value) { output.WriteUInt8((byte)(value ? 1 : 0)); } /// <summary> /// Write a UTF-8 string /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteString(string value) { if (value.Length == 0) { output.WriteVarUInt32(0); } else { var size = Encoding.UTF8.GetByteCount(value); output.WriteVarUInt32((UInt32)size); output.WriteString(Encoding.UTF8, value, size); } } /// <summary> /// Write a UTF-16 string /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void WriteWString(string value) { if (value.Length == 0) { output.WriteVarUInt32(0); } else { output.WriteVarUInt32((UInt32)value.Length); output.WriteString(Encoding.Unicode, value, value.Length << 1); } } #endregion } /// <summary> /// Reader for the Fast Binary tagged protocol /// </summary> /// <typeparam name="I">Implementation of IInputStream interface</typeparam> public struct FastBinaryReader<I> : IClonableTaggedProtocolReader, ICloneable<FastBinaryReader<I>> where I : IInputStream, ICloneable<I> { readonly I input; /// <summary> /// Create an instance of FastBinaryReader /// </summary> /// <param name="input">Input payload</param> /// <param name="version">Protocol version</param> public FastBinaryReader(I input, ushort version = 1) { this.input = input; } /// <summary> /// Clone the reader /// </summary> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif FastBinaryReader<I> ICloneable<FastBinaryReader<I>>.Clone() { return new FastBinaryReader<I>(input.Clone()); } #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif IClonableTaggedProtocolReader ICloneable<IClonableTaggedProtocolReader>.Clone() { return (this as ICloneable<FastBinaryReader<I>>).Clone(); } #region Complex types /// <summary> /// Start reading a struct /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadStructBegin() { } /// <summary> /// Start reading a base of a struct /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadBaseBegin() { } /// <summary> /// End reading a struct /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadStructEnd() { } /// <summary> /// End reading a base of a struct /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadBaseEnd() { } /// <summary> /// Start reading a field /// </summary> /// <param name="type">An out parameter set to the field type /// or BT_STOP/BT_STOP_BASE if there is no more fields in current struct/base</param> /// <param name="id">Out parameter set to the field identifier</param> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadFieldBegin(out BondDataType type, out ushort id) { type = (BondDataType)input.ReadUInt8(); if (type != BondDataType.BT_STOP && type != BondDataType.BT_STOP_BASE) id = input.ReadUInt16(); else id = 0; } /// <summary> /// End reading a field /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadFieldEnd() { } /// <summary> /// Start reading a list or set container /// </summary> /// <param name="count">An out parameter set to number of items in the container</param> /// <param name="elementType">An out parameter set to type of container elements</param> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadContainerBegin(out int count, out BondDataType elementType) { elementType = (BondDataType)input.ReadUInt8(); count = (int)input.ReadVarUInt32(); } /// <summary> /// Start reading a map container /// </summary> /// <param name="count">An out parameter set to number of items in the container</param> /// <param name="keyType">An out parameter set to the type of map keys</param> /// <param name="valueType">An out parameter set to the type of map values</param> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadContainerBegin(out int count, out BondDataType keyType, out BondDataType valueType) { keyType = (BondDataType)input.ReadUInt8(); valueType = (BondDataType)input.ReadUInt8(); count = (int)input.ReadVarUInt32(); } /// <summary> /// End reading a container /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void ReadContainerEnd() { } #endregion #region Primitive types /// <summary> /// Read an UInt8 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public byte ReadUInt8() { return input.ReadUInt8(); } /// <summary> /// Read an UInt16 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public ushort ReadUInt16() { return input.ReadUInt16(); } /// <summary> /// Read an UInt32 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public uint ReadUInt32() { return input.ReadUInt32(); } /// <summary> /// Read an UInt64 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public UInt64 ReadUInt64() { return input.ReadUInt64(); } /// <summary> /// Read an Int8 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public sbyte ReadInt8() { return (sbyte)input.ReadUInt8(); } /// <summary> /// Read an Int16 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public short ReadInt16() { return (short)input.ReadUInt16(); } /// <summary> /// Read an Int32 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public int ReadInt32() { return (int)input.ReadUInt32(); } /// <summary> /// Read an Int64 /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public long ReadInt64() { return (long)input.ReadUInt64(); } /// <summary> /// Read a bool /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public bool ReadBool() { return input.ReadUInt8() != 0; } /// <summary> /// Read a float /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public float ReadFloat() { return input.ReadFloat(); } /// <summary> /// Read a double /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public double ReadDouble() { return input.ReadDouble(); } /// <summary> /// Read a UTF-8 string /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public String ReadString() { var length = (int)input.ReadVarUInt32(); return length == 0 ? string.Empty : input.ReadString(Encoding.UTF8, length); } /// <summary> /// Read a UTF-16 string /// </summary> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public string ReadWString() { var length = (int)input.ReadVarUInt32(); return length == 0 ? string.Empty : input.ReadString(Encoding.Unicode, length << 1); } /// <summary> /// Read an array of bytes verbatim /// </summary> /// <param name="count">Number of bytes to read</param> /// <exception cref="EndOfStreamException"/> #if NET45 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public ArraySegment<byte> ReadBytes(int count) { return input.ReadBytes(count); } #endregion #region Skip /// <summary> /// Skip a value of specified type /// </summary> /// <param name="type">Type of the value to skip</param> /// <exception cref="EndOfStreamException"/> public void Skip(BondDataType type) { switch (type) { case (BondDataType.BT_BOOL): case (BondDataType.BT_UINT8): case (BondDataType.BT_INT8): input.SkipBytes(sizeof(byte)); break; case (BondDataType.BT_UINT16): case (BondDataType.BT_INT16): input.SkipBytes(sizeof(ushort)); break; case (BondDataType.BT_UINT32): case (BondDataType.BT_INT32): input.SkipBytes(sizeof(uint)); break; case (BondDataType.BT_FLOAT): input.SkipBytes(sizeof(float)); break; case (BondDataType.BT_DOUBLE): input.SkipBytes(sizeof(double)); break; case (BondDataType.BT_UINT64): case (BondDataType.BT_INT64): input.SkipBytes(sizeof(ulong)); break; case (BondDataType.BT_STRING): input.SkipBytes((int)input.ReadVarUInt32()); break; case (BondDataType.BT_WSTRING): input.SkipBytes((int)(input.ReadVarUInt32() << 1)); break; case BondDataType.BT_LIST: case BondDataType.BT_SET: SkipContainer(); break; case BondDataType.BT_MAP: SkipMap(); break; case BondDataType.BT_STRUCT: SkipStruct(); break; default: Throw.InvalidBondDataType(type); break; } } void SkipContainer() { BondDataType elementType; int count; ReadContainerBegin(out count, out elementType); switch (elementType) { case BondDataType.BT_BOOL: case BondDataType.BT_INT8: case BondDataType.BT_UINT8: input.SkipBytes(count); break; case (BondDataType.BT_UINT16): case (BondDataType.BT_INT16): input.SkipBytes(count * sizeof(ushort)); break; case (BondDataType.BT_UINT32): case (BondDataType.BT_INT32): input.SkipBytes(count * sizeof(uint)); break; case (BondDataType.BT_UINT64): case (BondDataType.BT_INT64): input.SkipBytes(count * sizeof(ulong)); break; case BondDataType.BT_FLOAT: input.SkipBytes(count * sizeof(float)); break; case BondDataType.BT_DOUBLE: input.SkipBytes(count * sizeof(double)); break; default: while (0 <= --count) { Skip(elementType); } break; } } void SkipMap() { BondDataType keyType; BondDataType valueType; int count; ReadContainerBegin(out count, out keyType, out valueType); while (0 <= --count) { Skip(keyType); Skip(valueType); } } void SkipStruct() { while (true) { BondDataType type; ushort id; ReadFieldBegin(out type, out id); if (type == BondDataType.BT_STOP_BASE) continue; if (type == BondDataType.BT_STOP) break; Skip(type); } } #endregion } }
/* Matrix.cs -- Matrix class. Copyright (c) 2012 by Rajitha Wimalasooriya */ using System; using System.Text; /// <summary> /// Represents a general purpose matrix class /// </summary> public class Matrix { #region Variables // Holds the number of rows in the current matrix private int m_rows; // Holds the number of columns in the current matrix private int m_columns; // Holds all elements in the current matrix private float[,] m_matrix; #endregion #region Indexers /// <summary> /// The row and column indexer /// </summary> /// <param name="row">The row number</param> /// <param name="column">The column number</param> /// <returns>The element at the provided row and column</returns> public float this[int row, int column] { get { return m_matrix[row,column]; } set { m_matrix[row,column] = value; } } #endregion #region Properties /// <summary> /// Number of rows in the matrix /// </summary> public int Rows { get { return m_rows; } } /// <summary> /// Number of columns in the matrix /// </summary> public int Columns { get { return m_columns; } } #endregion #region Constructors /// <summary> /// Constructs a matrix with the provided number of rows and columns /// </summary> /// <param name="rows">Number of rows</param> /// <param name="columns">Number of columns</param> public Matrix(int rows, int columns) { m_rows = rows; m_columns = columns; m_matrix = new float[rows, columns]; } #endregion #region Overrides /// <summary> /// Returns a string that represents the current matrix /// </summary> /// <returns>A string that represents the current matrix</returns> public override string ToString() { int maxSpace = 0; // Find the string length of the longest number in the matrix for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_columns; j++) { int currentLen = this[i,j].ToString().Length; if(maxSpace < currentLen) { maxSpace = currentLen; } } } // Max space needed is one char more than the longest number maxSpace++; // Calculate an approximate value for the string builder length StringBuilder sb = new StringBuilder(maxSpace + (m_rows * m_columns)); for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_columns; j++) { string currentEle = this[i,j].ToString(); sb.Append(' ', maxSpace - currentEle.Length); sb.Append(currentEle); } sb.Append("\n"); } return sb.ToString(); } /// <summary> /// Serves the hash function for the matrix /// </summary> /// <returns>A hash code for the current matrix.</returns> public override int GetHashCode() { float result = 0; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_columns; j++) { result += this[i,j]; } } return (int)result; } /// <summary> /// Determines whether the provided Object is equal to the current matrix /// </summary> /// <param name="obj">The object to compare with the current matrix</param> /// <returns>True if the provided Object is equal to the current matrix, otherwise false.</returns> public override bool Equals(Object obj) { Matrix mtx = (Matrix)obj; if(this.Rows != mtx.Rows || this.Columns != mtx.Columns) return false; for(int i = 0; i < this.Rows; i++) { for(int j = 0; j < this.Columns; j++) { if(this[i,j] != mtx[i,j]) return false; } } return true; } #endregion #region Operators /// <summary> /// Eqality operator overload /// </summary> /// <param name="lmtx">Left hand side matrix</param> /// <param name="rmtx">Right hand side matrix</param> /// <returns>True if matrixes are equal, otherwise false.</returns> public static bool operator == (Matrix lmtx, Matrix rmtx) { return Equals(lmtx, rmtx); } /// <summary> /// Inequality operator overload /// </summary> /// <param name="lmtx">Left hand side matrix</param> /// <param name="rmtx">Right hand side matrix</param> /// <returns>True if matrixes are not equal, otherwise false.</returns> public static bool operator != (Matrix lmtx, Matrix rmtx) { return !(lmtx == rmtx); } /// <summary> /// Multiplication operator overload (Multiplication by matrix) /// </summary> /// <param name="lmtx">Left hand side matrix</param> /// <param name="rmtx">Right hand side matrix</param> /// <returns>The multiplication result martix</returns> public static Matrix operator * (Matrix lmtx, Matrix rmtx) { if(lmtx.Columns != rmtx.Rows) throw new MatrixException("Attempt to multiply matrices with unmatching row and column indexes"); //return null; Matrix result = new Matrix(lmtx.Rows,rmtx.Columns); for(int i = 0; i < lmtx.Rows; i++) { for(int j = 0; j < rmtx.Columns; j++) { for(int k = 0; k < rmtx.Rows; k++) { result[i,j] += lmtx[i,k] * rmtx[k,j]; } } } return result; } /// <summary> /// Multiplication operator overload (Post multiplication by a constant) /// </summary> /// <param name="mtx">Left hand side matrix</param> /// <param name="val">Constant value to be multiplied by</param> /// <returns>The multiplication result martix</returns> public static Matrix operator * (Matrix mtx, float val) { Matrix result = new Matrix(mtx.Rows,mtx.Columns); for(int i = 0; i < mtx.Rows; i++) { for(int j = 0; j < mtx.Columns; j++) { result[i,j] = mtx[i,j] * val; } } return result; } /// <summary> /// Multiplication operator overload (Pre multiplication by a constant) /// </summary> /// <param name="val">Constant value to be multiplied by</param> /// <param name="mtx">Right hand side matrix</param> /// <returns>The multiplication result martix</returns> public static Matrix operator * (float val, Matrix mtx) { return mtx * val; } /// <summary> /// Devision operator overload (Devision by a constant) /// </summary> /// <param name="mtx">Left hand side matrix</param> /// <param name="val">Constant value to be devided by</param> /// <returns>The devision result martix</returns> public static Matrix operator / (Matrix mtx, float val) { if(val == 0) throw new MatrixException("Attempt to devide the matrix by zero"); //return null; Matrix result = new Matrix(mtx.Rows,mtx.Columns); for(int i = 0; i < mtx.Rows; i++) { for(int j = 0; j < mtx.Columns; j++) { result[i,j] = mtx[i,j] / val; } } return result; } /// <summary> /// N th power operator /// </summary> /// <param name="mtx">The matrix to find the N th power</param> /// <param name="val">The power</param> /// <returns>Result matrix to the power of N</returns> public static Matrix operator ^ (Matrix mtx, float val) { if(mtx.Rows != mtx.Columns) throw new MatrixException("Attempt to find the power of a non square matrix"); //return null; Matrix result = mtx; for(int i = 0; i < val; i++) { result = result * mtx; } return result; } /// <summary> /// Addition operator overload /// </summary> /// <param name="lmtx">Left hand side matrix</param> /// <param name="rmtx">Right hand side matrix</param> /// <returns>The addition result martix</returns> public static Matrix operator + (Matrix lmtx, Matrix rmtx) { if(lmtx.Rows != rmtx.Rows || lmtx.Columns != rmtx.Columns) throw new MatrixException("Attempt to add matrixes of different sizes"); //return null; Matrix result = new Matrix(lmtx.Rows,lmtx.Columns); for(int i = 0; i < lmtx.Rows; i++) { for(int j = 0; j < lmtx.Columns; j++) { result[i,j] = lmtx[i,j] + rmtx[i,j]; } } return result; } /// <summary> /// Subtraction operator overload /// </summary> /// <param name="lmtx">Left hand side matrix</param> /// <param name="rmtx">Right hand side matrix</param> /// <returns>The subtraction result martix</returns> public static Matrix operator - (Matrix lmtx, Matrix rmtx) { if(lmtx.Rows != rmtx.Rows || lmtx.Columns != rmtx.Columns) throw new MatrixException("Attempt to subtract matrixes of different sizes"); //return null; Matrix result = new Matrix(lmtx.Rows,lmtx.Columns); for(int i = 0; i < lmtx.Rows; i++) { for(int j = 0; j < lmtx.Columns; j++) { result[i,j] = lmtx[i,j] - rmtx[i,j]; } } return result; } /// <summary> /// Transpose operator /// </summary> /// <param name="mtx">The matrix to find the transpose</param> /// <returns>The transpose result matrix</returns> public static Matrix operator ~ (Matrix mtx) { Matrix result = new Matrix(mtx.Columns,mtx.Rows); for(int i = 0; i < mtx.Rows; i++) { for(int j = 0; j < mtx.Columns; j++) { result[j,i] = mtx[i,j]; } } return result; } /// <summary> /// Inverse operator /// </summary> /// <param name="mtx">The matrix to find the inverse</param> /// <returns>The inverse result matrix</returns> public static Matrix operator ! (Matrix mtx) { if(mtx.Determinant() == 0) throw new MatrixException("Attempt to invert a singular matrix"); //return null; // Inverse of a 2x2 matrix if(mtx.Rows == 2 && mtx.Columns == 2) { Matrix tempMtx = new Matrix(2,2); tempMtx[0,0] = mtx[1,1]; tempMtx[0,1] = -mtx[0,1]; tempMtx[1,0] = -mtx[1,0]; tempMtx[1,1] = mtx[0,0]; return tempMtx / mtx.Determinant(); } return mtx.Adjoint()/mtx.Determinant(); } #endregion #region Methods /// <summary> /// Returns the determinant of the current matrix /// </summary> /// <returns>The determinant of the current matrix</returns> public float Determinant() { float determinent = 0; if(this.Rows != this.Columns) throw new MatrixException("Attempt to find the determinent of a non square matrix"); //return 0; // Get the determinent of a 2x2 matrix if(this.Rows == 2 && this.Columns == 2) { determinent = (this[0,0] * this[1,1]) - (this[0,1] * this[1,0]); return determinent; } Matrix tempMtx = new Matrix(this.Rows - 1, this.Columns - 1); // Find the determinent with respect to the first row for(int j = 0; j < this.Columns; j++) { tempMtx = this.Minor(0, j); // Recursively add the determinents determinent += (int)Math.Pow(-1, j) * this[0,j] * tempMtx.Determinant(); } return determinent; } /// <summary> /// Returns the adjoint matrix of the current matrix /// </summary> /// <returns>The adjoint matrix of the current matrix</returns> public Matrix Adjoint() { if(this.Rows < 2 || this.Columns < 2) throw new MatrixException("Adjoint matrix not available"); Matrix tempMtx = new Matrix(this.Rows-1 , this.Columns-1); Matrix adjMtx = new Matrix (this.Columns , this.Rows); for(int i = 0; i < this.Rows; i++) { for(int j = 0; j < this.Columns;j++) { tempMtx = this.Minor(i, j); // Put the determinent of the minor in the transposed position adjMtx[j, i] = (int)Math.Pow(-1, i + j) * tempMtx.Determinant(); } } return adjMtx; } /// <summary> /// Returns a minor of a matrix with respect to an element /// </summary> /// <param name="row">Row number of the element</param> /// <param name="column">Column number of the element</param> /// <returns>The minor matrix</returns> public Matrix Minor(int row, int column) { if(this.Rows < 2 || this.Columns < 2) throw new MatrixException("Minor not available"); int i, j = 0; Matrix minorMtx = new Matrix(this.Rows - 1, this.Columns - 1); // Find the minor with respect to the first element for(int k = 0; k < minorMtx.Rows; k++) { if(k >= row) i = k + 1; else i = k; for(int l = 0; l < minorMtx.Columns; l++) { if(l >= column) j = l + 1; else j = l; minorMtx[k,l] = this[i,j]; } } return minorMtx; } /// <summary> /// Returns weather the matrix is an identity matrix /// </summary> /// <returns>True if the matrix is identity, otherwise false</returns> public bool IsIdentity() { if(Rows != Columns) return false; for(int i = 0; i < Rows; i++) { for(int j = 0; j < Columns; j++) { if(i == j) { if(this[i,j] != 1.0f) return false; } else { if(this[i,j] != 0.0f) return false; } } } return true; } /// <summary> /// Returns weather the matrix is invertible /// </summary> /// <returns>True if the matrix is non singular, otherwise false</returns> public bool IsInvertible() { try { if (this.Determinant() == 0) { return false; } } catch (MatrixException) { return false; } return true; } /// <summary> /// Makes the matrix an identity matrix /// </summary> public void Reset() { if(this.Rows != this.Columns) throw new MatrixException("Attempt to make non square matrix identity"); for(int j = 0; j < this.Columns; j++) { for(int i = 0; i < this.Rows; i++) { if(i == j) { this[i,j] = 1.0f; } else { this[i,j] = 0.0f; } } } } /// <summary> /// Makes the matrix a zero matrix /// </summary> public void Clear() { for(int j = 0; j < this.Columns; j++) { for(int i = 0; i < this.Rows; i++) { this[i,j] = 0.0f; } } } /// <summary> /// Rounds the elements of the matrix to the given percision /// </summary> /// <param name="precision">Percision to be used when rounding</param> public void Round(int precision) { for (int i = 0; i < this.Rows; i++) { for (int j = 0; j < this.Columns; j++) { this[i, j] = (float)Math.Round(this[i, j], precision); } } } #endregion } /// <summary> /// Represents a matrix exception /// </summary> public class MatrixException : Exception { public MatrixException(string message) : base(message) { } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace SliceEm { /// <summary> /// Summary description for AllSlices. /// </summary> public class AllSlices : System.Windows.Forms.Control { /// <summary> /// Required designer variable. /// </summary> private Pen _SlicePenPlane = new Pen(Color.Black, 2); private Pen _SlicePenPlaneSelected = new Pen(Color.Red, 2); private Pen _GridPenCursor = new Pen(Color.Red , 1); private Pen _GridPenCenter = new Pen(Color.Red , 1); private Pen _GridPenMajor = new Pen(Color.DarkGray , 1); private Pen _GridPenMinor = new Pen(Color.BlanchedAlmond, 1); private Font _GridFontMajor = new Font("Arial", 8); private Font _GridFontMinor = new Font("Arial", 6); private Brush _Black = new SolidBrush(Color.Black); private System.ComponentModel.Container components = null; private SliceEmFile _data; private SliceEditor _SliceEditor; private FileUpdateNotify FUN; private float originY = -39; private float orig_originY; private int start_y; private bool ldown; private bool rdown; private bool moving; private float scale = 0.5f; private bool dragging; private Bitmap offScreenBmp = null; private Graphics offScreenDC = null; private SlicePlane _SelectedPlane; private float cursorV = 0; public float VCursor { get { return cursorV; } } public SlicePlane CurSelectedPlane { get { return _SelectedPlane; } } public FileUpdateNotify FUNotify { set { FUN = value; } } public AllSlices(SliceEmFile data, SliceEditor SEditor) { _SliceEditor = SEditor; _data = data; InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if( components != null ) components.Dispose(); } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // AllSlices // this.Resize += new System.EventHandler(this.AllSlices_Resize); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.AllSlices_MouseUp); this.DoubleClick += new System.EventHandler(this.AllSlices_DoubleClick); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.AllSlices_MouseMove); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.AllSlices_MouseDown); } #endregion public void SetScale(float s) { if(s > 0) { scale = s; Refresh(); } } public int tranlsateGridY2PixelY(float y) { return (int)((y - originY) / (0.1f / scale)); } public float translatePixelY2GridY(int y) { return y * 0.1f / scale + originY; } protected void DrawSlices(Graphics g) { for(int i = 0; i < _data._SlicePlanes.Count ;i++) { SlicePlane SP = (SlicePlane) _data._SlicePlanes[i]; int vy = tranlsateGridY2PixelY(-SP.PlanarValue); if(SP == _SelectedPlane) { g.DrawLine(_SlicePenPlaneSelected, 0,vy,Size.Width,vy); } else { g.DrawLine(_SlicePenPlane, 0,vy,Size.Width,vy); } } } protected void DrawGrid(Graphics g) { float dymin = translatePixelY2GridY(0); float dymax = translatePixelY2GridY(Height); _data._miny = -dymin; _data._maxy = -dymax; FUN.Notify(); for(float dy = ((int)(dymin)); dy <= dymax+1; dy++) { int vy = tranlsateGridY2PixelY(dy); if(0 <= vy && vy <= Size.Height) { if(vy%10!=0) { g.DrawLine(_GridPenMinor, 0,vy,Size.Width,vy); } } } for(float dy = ((int)(dymin/10) * 10); dy <= dymax+1; dy+=10) { int vy = tranlsateGridY2PixelY(dy); if(0 <= vy && vy <= Size.Height) { g.DrawLine(_GridPenMajor, 0,vy,Size.Width,vy); g.DrawString(""+(-dy), _GridFontMajor, _Black, 0, vy); } } int cy = tranlsateGridY2PixelY(0); if(0 <= cy && cy <= Size.Height) { g.DrawLine(_GridPenCenter, 0,cy,Size.Width,cy); } cy = tranlsateGridY2PixelY(cursorV); if(0 <= cy && cy <= Size.Height) { g.DrawLine(_GridPenCursor, 0,cy,Size.Width,cy); g.DrawString(""+(-cursorV), _GridFontMajor, _Black, 0, cy); } } protected override void OnPaint(PaintEventArgs pe) { // TODO: Add custom paint code here if(offScreenBmp==null) { offScreenBmp = new Bitmap(this.Width, this.Height); offScreenDC = Graphics.FromImage(offScreenBmp); } else if(offScreenBmp.Width != this.Width || offScreenBmp.Height != this.Height) { offScreenBmp = new Bitmap(this.Width, this.Height); offScreenDC = Graphics.FromImage(offScreenBmp); } offScreenDC.Clear(Color.GhostWhite); DrawGrid(offScreenDC); DrawSlices(offScreenDC); pe.Graphics.DrawImage(offScreenBmp, 0, 0); } private void AllSlices_Resize(object sender, System.EventArgs e) { Invalidate(); } protected override void OnPaintBackground(PaintEventArgs pe) { } private void AllSlices_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button == MouseButtons.Left) { ldown = true; cursorV = translatePixelY2GridY(e.Y); SelectPlane(); } if(e.Button == MouseButtons.Right) { rdown = true; if(!ldown) { if(_SelectedPlane != null) { dragging = true; } } } if(ldown && rdown) { moving = true; start_y = e.Y; orig_originY = originY; } Refresh(); } private void AllSlices_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if(moving) { originY = orig_originY - (e.Y - start_y) * .1f / scale; Refresh(); } if(dragging) { if(_SelectedPlane != null) { _SelectedPlane.PlanarValue = -translatePixelY2GridY(e.Y); Refresh(); } } } private void AllSlices_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button == MouseButtons.Left) { ldown = false; moving = false; } if(e.Button == MouseButtons.Right) { rdown = false; moving = false; dragging = false; } } private void AllSlices_DoubleClick(object sender, System.EventArgs e) { _data.AddPlane(new SlicePlane(-cursorV)); SelectPlane(); Refresh(); } public void SelectPlane() { _SelectedPlane = _data.getClosest(-cursorV); _SliceEditor.SelectSlicePlane(_SelectedPlane); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Data; using System.Text; using System.Windows.Forms; namespace Factotum { // A custom control that acts as a graphic design element. It represents an // arrow that is selectable, draggable and whose start and endpoints can be dragged. // The user can specify physical characteristics like the shaft width, the barb offset, // the tip length, as well as design properties like the stroke color and width, // the fill color, the text color and the text public partial class Arrow : DrawingControl { //******************************************************* // Private fields //******************************************************* private PointF startPoint; private PointF endPoint; private float shaftWidth; // the nominal shaft width. The stroke also affects the actual width private float halfWidth; // half the nominal shaft width, more convenient to work with. private float barb; // The barb offset private float tip; // The tip length // These are set in MouseDown, reset in MouseUp and used in MouseMove private bool isMoving = false; private bool isStartChanging = false; private bool isEndChanging = false; // The rectangles used to draw the handles and detect mouse clicks // when the control is selected private Rectangle startAdornment; private Rectangle endAdornment; // This is used by the mouse move logic. // For the case of dragging the move adornment, it is simply set // when the mouse button is pressed. // For the case of dragging the start or end adornments, it is recalculated // each time the mouse moves to maintain its same relative position in the new // frame of reference. private Point lastDown; private PointF gStartPoint; private PointF gEndPoint; private int headCount; //******************************************************* // Public Properties //******************************************************* // Physical attributes public float ShaftWidth { get { return shaftWidth; } set { if (shaftWidth != value) { shaftWidth = value; halfWidth = shaftWidth / 2; } } } public float Barb { get { return barb; } set { if (barb != value) { barb = value; } } } public float Tip { get { return tip; } set { if (tip != value) { tip = value; } } } public PointF GStartPoint { get { return gStartPoint; } set { if (gStartPoint != value) { gStartPoint = value; if (!gEndPoint.IsEmpty && !gStartPoint.IsEmpty) { SetDimensionsFromGlobalStartAndEndPoints(); } } } } public PointF GEndPoint { get { return gEndPoint; } set { if (gEndPoint != value) { gEndPoint = value; if (!gEndPoint.IsEmpty && !gStartPoint.IsEmpty) { SetDimensionsFromGlobalStartAndEndPoints(); } } } } public override bool HasTransparentBackground { get { return (!HasFill); } set { HasFill = !value; } } public int HeadCount { get { return headCount; } set { headCount = value; } } //******************************************************* // Constructors //******************************************************* // Creates a default arrow with its start point at 100,100 in the // parent container reference frame. public Arrow() : this(new PointF(100, 100)) { } // Creates a default arrow at the specified start point in the // parent container reference frame. public Arrow(PointF gStartPoint) : this(gStartPoint,1, 12F, 6F, 20F, 2F, "FLOW", true, Color.Yellow, Color.Red, Color.Black, false, DefaultFont){ } // Creates an arrow with the specified attributes with its start point // specified in the parent container reference frame. // New arrows will generally be added to the container in two steps. // In the first step, the user clicks the form and an arrow with default length // is created with its start point at the coordinates the user specified. // In the second step, the user drags the endpoint of the arrow as desired. public Arrow(PointF gStartPoint, int headCount, float shaftWidth, float barb, float tip, float stroke, string text, bool hasText, Color fillColor, Color textColor, Color strokeColor, bool hasTransparentBackground, Font font) : this(gStartPoint, new PointF(gStartPoint.X + 100, gStartPoint.Y), headCount, shaftWidth, barb, tip, stroke, text, hasText, fillColor, textColor, strokeColor, hasTransparentBackground, font) { } // Creates an arrow with the specified attributes with both start and end points // specified in the parent container reference frame. public Arrow(PointF gStartPoint, PointF gEndPoint, int headCount, float shaftWidth, float barb, float tip, float stroke, string text, bool hasText, Color fillColor, Color textColor, Color strokeColor, bool hasTransparentBackground, Font font) { // OptimizedDoubleBuffer doesn't seem to help this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Selectable, true); BackColor = Color.Transparent; HeadCount = headCount; ShaftWidth = shaftWidth; Barb = barb; Tip = tip; Stroke = stroke; Text = text; HasText = hasText; HasTransparentBackground = hasTransparentBackground; HasStroke = true; StrokeColor = strokeColor; FillColor = fillColor; TextColor = textColor; Font = font; GStartPoint = gStartPoint; GEndPoint = gEndPoint; SetDimensionsFromGlobalStartAndEndPoints(); try { string path; path = Application.StartupPath + "\\move.cur"; MoveCursor = new Cursor(path); path = Application.StartupPath + "\\stretch.cur"; StretchCursor = new Cursor(path); } catch (Exception ex) { throw new Exception("Unable to set custom cursors", ex); } } // If gStartPoint and gEndPoint are defined, we can calculate // all the other dimensions of the control private void SetDimensionsFromGlobalStartAndEndPoints() { float delta = getDelta(); float minx = (int)Math.Min(gStartPoint.X, gEndPoint.X); float miny = (int)Math.Min(gStartPoint.Y, gEndPoint.Y); Top = (int)(miny - delta); Left = (int)(minx - delta); startPoint = new PointF(gStartPoint.X - minx + delta, gStartPoint.Y - miny + delta); endPoint = new PointF(gEndPoint.X - minx + delta, gEndPoint.Y - miny + delta); Width = (int)(Math.Abs(gStartPoint.X - gEndPoint.X) + 2 * delta); Height = (int)(Math.Abs(gStartPoint.Y - gEndPoint.Y) + 2 * delta); } // This can be called either by the Paint event of the control or by an external // function. If it's called externally we need to specify the location where we // want the painting performed. public override void PaintGraphics(Graphics g, float scaleFactor) { // Note: antialiasing only applies to paths, not region fills, so the path must // be drawn last. g.SmoothingMode = SmoothingMode.AntiAlias; // The distance from the startpoint to the endpoint (where the barb begins) float length = getDistance(startPoint, endPoint); // The absolute angle of the vector from startPoint to endPoint float angle = getAngle(startPoint, endPoint); GraphicsPath gp = new GraphicsPath(); // Translate and rotate to put the startPoint at the origin and the endpoint on // the positive x axis g.TranslateTransform(startPoint.X, startPoint.Y); g.RotateTransform(angle); float halfStroke = HasStroke ? Stroke / 2 : 0; switch (headCount) { case 0: // Add the arrow boundary points // In this simple case it's really just a rectangle... gp.AddPolygon(new PointF[] { new PointF(halfStroke,halfStroke), new PointF(halfStroke,halfWidth-halfStroke), new PointF(length,halfWidth-halfStroke), new PointF(length, -(halfWidth-halfStroke)), new PointF(halfStroke,-(halfWidth-halfStroke)) }); break; case 1: // Add the arrow boundary points gp.AddPolygon(new PointF[] { new PointF(halfStroke,halfStroke), new PointF(halfStroke,halfWidth-halfStroke), new PointF(length,halfWidth-halfStroke), new PointF(length,halfWidth+barb-halfStroke), new PointF(length+tip-halfStroke,0), new PointF(length,-(halfWidth+barb-halfStroke)), new PointF(length, -(halfWidth-halfStroke)), new PointF(halfStroke,-(halfWidth-halfStroke)) }); break; case 2: // Add the arrow boundary points gp.AddPolygon(new PointF[] { new PointF(0,halfWidth-halfStroke), new PointF(length,halfWidth-halfStroke), new PointF(length,halfWidth+barb-halfStroke), new PointF(length+tip-halfStroke,0), new PointF(length,-(halfWidth+barb-halfStroke)), new PointF(length, -(halfWidth-halfStroke)), new PointF(0,-(halfWidth-halfStroke)), new PointF(0,-(halfWidth+barb-halfStroke)), new PointF(-(tip-halfStroke),0), new PointF(0,halfWidth+barb-halfStroke) }); break; default: throw new Exception("An arrow must have zero, one or two heads."); } if (HasFill) { // Fill the interior g.FillRegion(new SolidBrush(FillColor), new Region(gp)); } if (HasStroke) { // Draw the stroke g.DrawPath(new Pen(new SolidBrush(StrokeColor), Stroke), gp); } gp.Dispose(); // If we have some text to draw if (HasText && Text.Length > 0) { float topPadding = 2; Font fnt = new Font(Font.FontFamily, 2 * halfWidth - Stroke - topPadding, Font.Style, GraphicsUnit.Pixel); SizeF fntSize = g.MeasureString(Text, fnt); PointF txtLocation; // Draw the text. If the angle is pointing to the left, rotate 180 degrees first // so the text isn't upside down. if (angle <= 90 && angle >= -90) { txtLocation = new PointF((length - fntSize.Width) / 2, (-fntSize.Height / 2) + topPadding); g.DrawString(Text, fnt, new SolidBrush(TextColor), txtLocation); } else { g.RotateTransform(180); txtLocation = new PointF((-length - fntSize.Width) / 2, (-fntSize.Height / 2) + topPadding); g.DrawString(Text, fnt, new SolidBrush(TextColor), txtLocation); g.RotateTransform(-180); } fnt.Dispose(); } g.RotateTransform(-angle); g.TranslateTransform(-startPoint.X, -startPoint.Y); if (IsSelected) { // Reset the transforms because we're using absolute coords now. CalcAdornments(); ControlPaint.DrawGrabHandle(g, startAdornment, true, true); ControlPaint.DrawGrabHandle(g, endAdornment, true, true); } } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; PaintGraphics(g,1.0F); // Set the control's Region property to include the painted region plus a little. ShapeControl(); } // See the geometry notes for these two functions // Get the additional distance to the tip for a given "stroke half-width" s private float getTipOffset(float s) { return (float)(s * Math.Sqrt(1 + Math.Pow(tip / (halfWidth + barb), 2))); } // Get the additional distance to the outer edge of the barb // for a given tipOffset and "stroke half-width" s private float getBarbOffset(float tipOffset, float s) { float dy = barb + halfWidth; return dy * ((s + tipOffset + tip) / tip - 1); } // Shape the control, by creating the region that bounds it and setting the // Region property of the control to it. private void ShapeControl() { GraphicsPath gp = new GraphicsPath(); float length = getDistance(startPoint, endPoint); // may want to add an extra pixel to the half-stroke width for better smoothing. float s = Stroke / 2; float tipOffset = getTipOffset(s); float barbOffset = getBarbOffset(tipOffset,s); // Add the boundary points switch (headCount) { case 0: // Add the arrow boundary points // In this simple case it's really just a rectangle... gp.AddPolygon(new PointF[] { new PointF(-s,halfWidth+s), new PointF(length-s,halfWidth+s), new PointF(length-s,-halfWidth-s), new PointF(-s,-halfWidth-s)}); break; case 1: // Add the arrow boundary points gp.AddPolygon(new PointF[] { new PointF(-s,0), new PointF(-s,halfWidth+s), new PointF(length-s,halfWidth+s), new PointF(length-s,halfWidth+barb+barbOffset), new PointF(length+tip+tipOffset,0), new PointF(length-s,-halfWidth-barb-barbOffset), new PointF(length-s,-halfWidth-s), new PointF(-s,-halfWidth-s)}); break; case 2: // Add the arrow boundary points gp.AddPolygon(new PointF[] { new PointF(s,halfWidth+s), new PointF(length-s,halfWidth+s), new PointF(length-s,halfWidth+barb+barbOffset), new PointF(length+tip+tipOffset,0), new PointF(length-s,-halfWidth-barb-barbOffset), new PointF(length-s,-halfWidth-s), new PointF(s,-halfWidth-s), new PointF(s,-halfWidth-barb-barbOffset), new PointF(-tip-tipOffset,0), new PointF(s,halfWidth+barb+barbOffset) }); break; default: throw new Exception("An arrow must have zero, one or two heads."); } // We're not painting anything, so we don't need a graphics. // Use a matrix to transform. Matrix mat = new Matrix(); mat.Translate(startPoint.X, startPoint.Y); mat.Rotate(getAngle(startPoint, endPoint)); gp.Transform(mat); Region rgn = new Region(gp); // If the control is selected, we need to union in the handles if (IsSelected) { rgn.Union(startAdornment); rgn.Union(endAdornment); } // Set the control's region property this.Region = rgn; } // Calculate the three adornments (grab handle) rectangles for the control private void CalcAdornments() { startAdornment = CalcAdornment(startPoint); endAdornment = CalcAdornment(endPoint); } // Calculate an adornment (grab handle) rectangle, centered on the given point private Rectangle CalcAdornment(PointF pt) { return new Rectangle((int)(pt.X - adornmentSize / 2), (int)(pt.Y - adornmentSize / 2), adornmentSize, adornmentSize); } // If the control was clicked, make it selected by setting its property // and repainting to show the handles. protected override void OnClick(EventArgs e) { base.OnClick(e); Focus(); // Set the focus even if it was already selected. if (!IsSelected) { IsSelected = true; Invalidate(); } } protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); if (IsSelected) Cursor = MoveCursor; } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); Cursor = DefaultCursor; } // If the control was selected, check for mouse down inside one of the // drag handles. protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (IsSelected) { if (startAdornment.Contains(e.Location)) isStartChanging = true; else if (endAdornment.Contains(e.Location)) isEndChanging = true; else isMoving = true; lastDown = new Point(e.X, e.Y); } } #if true // This handles moving the control and changing its endpoints. protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (IsSelected) { if (startAdornment.Contains(e.Location) || endAdornment.Contains(e.Location)) { Cursor = StretchCursor; } else { Cursor = MoveCursor; } } if (e.Button == MouseButtons.Left) { if (isMoving) { gStartPoint = new PointF(gStartPoint.X + e.X - lastDown.X, gStartPoint.Y + e.Y - lastDown.Y); GEndPoint = new PointF(gEndPoint.X + e.X - lastDown.X, gEndPoint.Y + e.Y - lastDown.Y); //Left += e.X - lastDown.X; //Top += e.Y - lastDown.Y; } else if (isStartChanging || isEndChanging) { // "errors" from center of target point float xe; float ye; // This is tricky because as we drag a start or end point, the position and // size of the control change. // Also, the relative positions of the start and end point can change. For // example the endpoint may be above and to the right of the startpoint before // the move, but end up to the left and below it. if (isStartChanging) { xe = lastDown.X - startPoint.X; ye = lastDown.Y - startPoint.Y; // Setting this property automatically updates all the other dimensions. GStartPoint = new PointF(gStartPoint.X + e.X - lastDown.X, gStartPoint.Y + e.Y - lastDown.Y); // Update lastDown because the frame of reference may have changed lastDown = new Point((int)(startPoint.X + xe),(int)(startPoint.Y+ye)); } else // endpoint must be changing { xe = lastDown.X - endPoint.X; ye = lastDown.Y - endPoint.Y; // Setting this property automatically updates all the other dimensions. GEndPoint = new PointF(gEndPoint.X + e.X - lastDown.X, gEndPoint.Y + e.Y - lastDown.Y); // Update lastDown because the frame of reference may have changed lastDown = new Point((int)(endPoint.X + xe),(int)(endPoint.Y+ye)); } Invalidate(); } } } #endif #if false // This handles moving the control and changing its endpoints. protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (IsSelected) { if (startAdornment.Contains(e.Location) || endAdornment.Contains(e.Location)) { Cursor = StretchCursor; } else { Cursor = MoveCursor; } } if (e.Button == MouseButtons.Left) { if (isMoving) { System.Diagnostics.Debug.Print((e.X - lastDown.X) + " " + (e.Y - lastDown.Y)); Left += e.X - lastDown.X; Top += e.Y - lastDown.Y; } else if (isStartChanging || isEndChanging) { // This is tricky because as we drag a start or end point, the position and // size of the control change. // Also, the relative positions of the start and end point can change. For // example the endpoint may be above and to the right of the startpoint before // the move, but end up to the left and below it. float p1xp, p1yp; // New start point coords in the OLD coord system float p2xp, p2yp; // New end point coords in the OLD coord system float p1xdp, p1ydp; // New start point coords in the NEW coord system float p2xdp, p2ydp; // New end point coords in the NEW coord system // The control area consists of the rectangle formed by the start and end points // offset by delta. This tries to ensure that the control area will // always be large enough to contain the arrow head, barbs, and adornments. float delta = getDelta(); float widthp, leftp; // New width and horizontal position of the control float heightp, topp; // New height and vertical position of the control if (isStartChanging) { p1xp = startPoint.X + e.X - lastDown.X; p1yp = startPoint.Y + e.Y - lastDown.Y; p2xp = endPoint.X; p2yp = endPoint.Y; } else { p2xp = endPoint.X + e.X - lastDown.X; p2yp = endPoint.Y + e.Y - lastDown.Y; p1xp = startPoint.X; p1yp = startPoint.Y; } // Get new X-related coords if (p1xp < p2xp) { p1xdp = delta; p2xdp = delta + p2xp - p1xp; widthp = 2 * delta + p2xp - p1xp; if (startPoint.X < endPoint.X) leftp = Left + p1xp - startPoint.X; else leftp = Left + p1xp - endPoint.X; } else { p2xdp = delta; p1xdp = delta + p1xp - p2xp; widthp = 2 * delta + p1xp - p2xp; if (endPoint.X < startPoint.X) leftp = Left + p2xp - endPoint.X; else leftp = Left + p2xp - startPoint.X; } // Get new Y-related coords if (p1yp < p2yp) { p1ydp = delta; p2ydp = delta + p2yp - p1yp; heightp = 2 * delta + p2yp - p1yp; if (startPoint.Y < endPoint.Y) topp = Top + p1yp - startPoint.Y; else topp = Top + p1yp - endPoint.Y; } else { p2ydp = delta; p1ydp = delta + p1yp - p2yp; heightp = 2 * delta + p1yp - p2yp; if (endPoint.Y < startPoint.Y) topp = Top + p2yp - endPoint.Y; else topp = Top + p2yp - startPoint.Y; } // Since the coordinate system may have changed, // recalculate the "last down" point. if (isStartChanging) { lastDown.X = (int)(p1xdp + lastDown.X - startPoint.X); lastDown.Y = (int)(p1ydp + lastDown.Y - startPoint.Y); } else { lastDown.X = (int)(p2xdp + lastDown.X - endPoint.X); lastDown.Y = (int)(p2ydp + lastDown.Y - endPoint.Y); } // Define the new start and end points startPoint = new PointF(p1xdp, p1ydp); endPoint = new PointF(p2xdp,p2ydp); Top = (int)topp; Left = (int)leftp; Width = (int)widthp; Height = (int)heightp; Invalidate(); } } } #endif // Reset all drag state flags protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); isMoving = false; isStartChanging = false; isEndChanging = false; } // The control area consists of the rectangle formed by the start and end points // offset by delta. This tries to ensure that the control area will // always be large enough to contain the arrow head, barbs, and adornments. private float getDelta() { return Math.Max(Math.Max(Tip, halfWidth + Barb) + Stroke, adornmentSize); } // Calculate the absolute angle of a vector from pStart to pEnd // Angles returned should be in the range from -90 to +269.999 // If the start and endpoint are the same, the angle is arbitrarily set to zero. private float getAngle(PointF pStart, PointF pEnd) { const float eps = float.Epsilon; float dx = pEnd.X - pStart.X; float dy = pEnd.Y - pStart.Y; float adx = Math.Abs(dx); float ady = Math.Abs(dy); if (adx <= eps) { if (ady <= eps) return 0; // arbitrarily set to zero else if (dy > eps) return 90; else return -90; } else if (dx > eps) { // Main branch of the arctangent function (-90 to 90) if (ady <= eps) return 0; else return (float)(180 / Math.PI * Math.Atan(dy / dx)); } else // (dx < eps) { if (ady <= eps) return 180; // Second branch of the arctangent function (add PI to Main branch result) else return (float)(180 / Math.PI * (Math.Atan(dy / dx) + Math.PI)); } } // Return the distance between two points. private float getDistance(PointF p1, PointF p2) { return (float)Math.Sqrt( (p2.X - p1.X) * (p2.X - p1.X) + (p2.Y - p1.Y) * (p2.Y - p1.Y)); } // Return the midpoint between two given points private PointF getMidpoint(PointF p1, PointF p2) { return new PointF((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.PythonTools.Analysis; namespace Microsoft.PythonTools.Interpreter.Default { class CPythonType : IPythonType, ILocatedMember { private readonly string _typeName, _doc; private readonly bool _includeInModule; private readonly BuiltinTypeId _typeId; private readonly CPythonModule _module; private readonly List<IPythonType> _bases; private readonly IPythonType[] _mro; private readonly bool _isBuiltin; private readonly Dictionary<string, IMember> _members = new Dictionary<string, IMember>(); private readonly bool _hasLocation; private readonly int _line, _column; public CPythonType(IMemberContainer parent, ITypeDatabaseReader typeDb, string typeName, Dictionary<string, object> typeTable, BuiltinTypeId typeId) { Debug.Assert(parent is CPythonType || parent is CPythonModule); Debug.Assert(!typeId.IsVirtualId()); _typeName = typeName; _typeId = typeId; _module = GetDeclaringModule(parent); object value; if (typeTable.TryGetValue("is_hidden", out value)) { _includeInModule = !Convert.ToBoolean(value); } else { _includeInModule = true; } if (typeTable.TryGetValue("doc", out value)) { _doc = value as string; } if (typeTable.TryGetValue("builtin", out value)) { _isBuiltin = Convert.ToBoolean(value); } else { _isBuiltin = true; } if (typeTable.TryGetValue("bases", out value)) { var basesList = (List<object>)value; if (basesList != null) { _bases = new List<IPythonType>(); foreach (var baseType in basesList) { typeDb.LookupType(baseType, StoreBase); } } } if (typeTable.TryGetValue("mro", out value)) { var mroList = (List<object>)value; if (mroList != null && mroList.Count >= 1) { _mro = new IPythonType[mroList.Count]; // Many scraped types have invalid MRO entries because they // report their own module/name incorrectly. Since the first // item in the MRO is always self, we set it now. If the MRO // has a resolvable entry it will replace this one. _mro[0] = this; for (int i = 0; i < mroList.Count; ++i) { var capturedI = i; typeDb.LookupType(mroList[i], t => _mro[capturedI] = t); } } } if (typeTable.TryGetValue("members", out value)) { var membersTable = (Dictionary<string, object>)value; if (membersTable != null) { LoadMembers(typeDb, membersTable); } } _hasLocation = PythonTypeDatabase.TryGetLocation(typeTable, ref _line, ref _column); } private CPythonModule GetDeclaringModule(IMemberContainer parent) { return parent as CPythonModule ?? (CPythonModule)((CPythonType)parent).DeclaringModule; } private void StoreBase(IPythonType type) { if (type != null && _bases != null) { _bases.Add(type); } } private void LoadMembers(ITypeDatabaseReader typeDb, Dictionary<string, object> membersTable) { foreach (var memberEntry in membersTable) { var memberName = memberEntry.Key; var memberValue = memberEntry.Value as Dictionary<string, object>; if (memberValue != null) { _members[memberName] = null; typeDb.ReadMember(memberName, memberValue, StoreMember, this); } } } private void StoreMember(string memberName, IMember value) { _members[memberName] = value; } public bool IncludeInModule { get { return _includeInModule; } } #region IPythonType Members public IMember GetMember(IModuleContext context, string name) { IMember res; if (_members.TryGetValue(name, out res)) { return res; } if (_mro != null) { foreach (var mroType in _mro.OfType<CPythonType>()) { if (mroType._members.TryGetValue(name, out res)) { return res; } } } else if (_bases != null) { foreach (var baseType in _bases) { res = baseType.GetMember(context, name); if (res != null) { return res; } } } return null; } public IPythonFunction GetConstructors() { IMember member; if (_members.TryGetValue("__new__", out member) && member is IPythonFunction && ((IPythonFunction)member).Overloads.Count > 0) { return member as IPythonFunction; } else if (TypeId != BuiltinTypeId.Object && _members.TryGetValue("__init__", out member)) { if (member is CPythonMethodDescriptor) { return ((CPythonMethodDescriptor)member).Function; } return member as IPythonFunction; } return null; } public IList<IPythonType> Mro { get { return _mro; } } public string Name { get { if (TypeId != BuiltinTypeId.Unknown) { return _module.TypeDb.GetBuiltinTypeName(TypeId); } return _typeName; } } public string Documentation { get { return _doc ?? ""; } } public BuiltinTypeId TypeId { get { return _typeId; } } public IPythonModule DeclaringModule { get { return _module; } } public bool IsBuiltin { get { return _isBuiltin; } } #endregion #region IMemberContainer Members public IEnumerable<string> GetMemberNames(IModuleContext moduleContext) { var seen = new HashSet<string>(); foreach (var key in _members.Keys) { if (seen.Add(key)) { yield return key; } } if (_mro != null) { foreach (var type in _mro.OfType<CPythonType>()) { foreach (var key in type._members.Keys) { if (seen.Add(key)) { yield return key; } } } } else if (_bases != null) { foreach (var type in _bases) { foreach (var key in type.GetMemberNames(moduleContext)) { if (seen.Add(key)) { yield return key; } } } } } #endregion #region IMember Members public PythonMemberType MemberType { get { return PythonMemberType.Class; } } #endregion public override string ToString() { return String.Format("CPythonType('{0}')", Name); } #region ILocatedMember Members public IEnumerable<LocationInfo> Locations { get { if (_hasLocation) { yield return new LocationInfo(_module.FilePath, _line, _column); } } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Example.API.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Stores; namespace Nop.Services.Stores { /// <summary> /// Store mapping service /// </summary> public partial class StoreMappingService : IStoreMappingService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : entity ID /// {1} : entity name /// </remarks> private const string STOREMAPPING_BY_ENTITYID_NAME_KEY = "Nop.storemapping.entityid-name-{0}-{1}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string STOREMAPPING_PATTERN_KEY = "Nop.storemapping."; #endregion #region Fields private readonly IRepository<StoreMapping> _storeMappingRepository; private readonly IStoreContext _storeContext; private readonly ICacheManager _cacheManager; private readonly CatalogSettings _catalogSettings; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="storeContext">Store context</param> /// <param name="storeMappingRepository">Store mapping repository</param> /// <param name="catalogSettings">Catalog settings</param> public StoreMappingService(ICacheManager cacheManager, IStoreContext storeContext, IRepository<StoreMapping> storeMappingRepository, CatalogSettings catalogSettings) { this._cacheManager = cacheManager; this._storeContext = storeContext; this._storeMappingRepository = storeMappingRepository; this._catalogSettings = catalogSettings; } #endregion #region Methods /// <summary> /// Deletes a store mapping record /// </summary> /// <param name="storeMapping">Store mapping record</param> public virtual void DeleteStoreMapping(StoreMapping storeMapping) { if (storeMapping == null) throw new ArgumentNullException("storeMapping"); _storeMappingRepository.Delete(storeMapping); //cache _cacheManager.RemoveByPattern(STOREMAPPING_PATTERN_KEY); } /// <summary> /// Gets a store mapping record /// </summary> /// <param name="storeMappingId">Store mapping record identifier</param> /// <returns>Store mapping record</returns> public virtual StoreMapping GetStoreMappingById(int storeMappingId) { if (storeMappingId == 0) return null; return _storeMappingRepository.GetById(storeMappingId); } /// <summary> /// Gets store mapping records /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="entity">Entity</param> /// <returns>Store mapping records</returns> public virtual IList<StoreMapping> GetStoreMappings<T>(T entity) where T : BaseEntity, IStoreMappingSupported { if (entity == null) throw new ArgumentNullException("entity"); int entityId = entity.Id; string entityName = typeof(T).Name; var query = from sm in _storeMappingRepository.Table where sm.EntityId == entityId && sm.EntityName == entityName select sm; var storeMappings = query.ToList(); return storeMappings; } /// <summary> /// Inserts a store mapping record /// </summary> /// <param name="storeMapping">Store mapping</param> public virtual void InsertStoreMapping(StoreMapping storeMapping) { if (storeMapping == null) throw new ArgumentNullException("storeMapping"); _storeMappingRepository.Insert(storeMapping); //cache _cacheManager.RemoveByPattern(STOREMAPPING_PATTERN_KEY); } /// <summary> /// Inserts a store mapping record /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="storeId">Store id</param> /// <param name="entity">Entity</param> public virtual void InsertStoreMapping<T>(T entity, int storeId) where T : BaseEntity, IStoreMappingSupported { if (entity == null) throw new ArgumentNullException("entity"); if (storeId == 0) throw new ArgumentOutOfRangeException("storeId"); int entityId = entity.Id; string entityName = typeof(T).Name; var storeMapping = new StoreMapping() { EntityId = entityId, EntityName = entityName, StoreId = storeId }; InsertStoreMapping(storeMapping); } /// <summary> /// Updates the store mapping record /// </summary> /// <param name="storeMapping">Store mapping</param> public virtual void UpdateStoreMapping(StoreMapping storeMapping) { if (storeMapping == null) throw new ArgumentNullException("storeMapping"); _storeMappingRepository.Update(storeMapping); //cache _cacheManager.RemoveByPattern(STOREMAPPING_PATTERN_KEY); } /// <summary> /// Find store identifiers with granted access (mapped to the entity) /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="entity">Wntity</param> /// <returns>Store identifiers</returns> public virtual int[] GetStoresIdsWithAccess<T>(T entity) where T : BaseEntity, IStoreMappingSupported { if (entity == null) throw new ArgumentNullException("entity"); int entityId = entity.Id; string entityName = typeof(T).Name; string key = string.Format(STOREMAPPING_BY_ENTITYID_NAME_KEY, entityId, entityName); return _cacheManager.Get(key, () => { var query = from sm in _storeMappingRepository.Table where sm.EntityId == entityId && sm.EntityName == entityName select sm.StoreId; var result = query.ToArray(); //little hack here. nulls aren't cacheable so set it to "" if (result == null) result = new int[0]; return result; }); } /// <summary> /// Authorize whether entity could be accessed in the current store (mapped to this store) /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="entity">Wntity</param> /// <returns>true - authorized; otherwise, false</returns> public virtual bool Authorize<T>(T entity) where T : BaseEntity, IStoreMappingSupported { return Authorize(entity, _storeContext.CurrentStore.Id); } /// <summary> /// Authorize whether entity could be accessed in a store (mapped to this store) /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="entity">Entity</param> /// <param name="storeId">Store identifier</param> /// <returns>true - authorized; otherwise, false</returns> public virtual bool Authorize<T>(T entity, int storeId) where T : BaseEntity, IStoreMappingSupported { if (entity == null) return false; if (storeId == 0) //return true if no store specified/found return true; if (_catalogSettings.IgnoreStoreLimitations) return true; if (!entity.LimitedToStores) return true; foreach (var storeIdWithAccess in GetStoresIdsWithAccess(entity)) if (storeId == storeIdWithAccess) //yes, we have such permission return true; //no permission found return false; } #endregion } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * 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.Linq; using System.Text; using System.Xml; using System.IO; using System.Collections.Generic; using System.Drawing.Imaging; using System.Drawing; namespace Trisoft.ISHRemote.HelperClasses { /// <summary> /// This class can be used to obfuscate a file. /// </summary> public static class IshObfuscator { #region Private fields /// <summary> /// To replace words up to 20 characters with a fixed replacement word /// </summary> private static string[] _shortWordSubstitutions = { "", "a", "be", "the", "easy", "would", "summer", "healthy", "zucchini", "breakfast", "chimpanzee", "alternative", "professional", "extraordinary", "representative", "confidentiality", "extraterrestrial", "telecommunication", "bioinstrumentation", "psychophysiological", "internationalization" }; /// <summary> /// To replace words > 20 chars .. a part of this very long word can be taken /// </summary> private static string _longWordSubstitution = string.Concat(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", 100000)); #endregion #region Public xml obfuscation methods /// <summary> /// Obfuscates the given xml file. /// When the obfuscation succeeds a file is created at the location given in outputFileLocation /// </summary> /// <param name="inputFileLocation">The location of the input file</param> /// <param name="outputFileLocation">The location for the output file</param> /// <param name="attributesToObfuscate">Attributes to obfuscate</param> public static void ObfuscateXml(string inputFileLocation, string outputFileLocation, List<string> attributesToObfuscate) { Encoding outputEncoding = Encoding.Unicode; using (var inputStream = new FileStream(inputFileLocation, FileMode.Open, FileAccess.Read, FileShare.None)) { MemoryStream resultStream = new MemoryStream((int)inputStream.Length); // As the XmlTextReader closes the input stream, we use a wrapper class so the original stream does not get closed using (var reader = new XmlTextReader(inputStream)) { reader.Namespaces = false; reader.WhitespaceHandling = WhitespaceHandling.All; reader.EntityHandling = EntityHandling.ExpandCharEntities; reader.Normalization = false; reader.DtdProcessing = DtdProcessing.Parse; reader.XmlResolver = null; using (var resultStreamNonClosing = new NonClosingStreamWrapper(resultStream)) { using (var writer = new XmlTextWriter(resultStreamNonClosing, outputEncoding)) { writer.Namespaces = false; reader.Read(); while (!reader.EOF) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: WriteXmlDeclaration(outputEncoding, reader, writer); reader.Read(); break; case XmlNodeType.DocumentType: writer.WriteNode(reader, false); break; case XmlNodeType.ProcessingInstruction: if (reader.Name != "ish") { writer.WriteProcessingInstruction(reader.Name, ObfuscateWords(reader.Value)); reader.Read(); } else { writer.WriteNode(reader, false); } break; case XmlNodeType.Element: bool isEmptyElement = reader.IsEmptyElement; string elementValue = reader.Value; writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); for (int attInd = 0; attInd < reader.AttributeCount; attInd++) { reader.MoveToAttribute(attInd); var attributeValue = reader.Value; if (attributesToObfuscate != null && attributesToObfuscate.Contains(reader.Name)) { attributeValue = ObfuscateWords(reader.Value); } writer.WriteAttributeString(reader.Prefix, reader.LocalName, reader.NamespaceURI, attributeValue); } if (!String.IsNullOrEmpty(elementValue)) { writer.WriteString(ObfuscateWords(elementValue)); } if (isEmptyElement) { writer.WriteEndElement(); } reader.Read(); break; case XmlNodeType.Comment: writer.WriteComment(ObfuscateWords(reader.Value)); reader.Read(); break; case XmlNodeType.Text: writer.WriteString(ObfuscateWords(reader.Value)); reader.Read(); break; default: writer.WriteNode(reader, false); break; } } } using (var outputStream = new FileStream(outputFileLocation, FileMode.Create, FileAccess.Write, FileShare.None)) { resultStream.Position = 0; resultStream.CopyTo(outputStream); } } } } } /// <summary> /// Obfuscates the given image file. /// For that, a new image is created with the same format, width and height and a yellow background (and the filename in text in the image if it is wide enough to put it there). /// When the obfuscation succeeds a file is created at the location given in outputFileLocation /// </summary> /// <param name="inputFileLocation">The location of the input file</param> /// <param name="outputFileLocation">The location for the output file</param> public static void ObfuscateImage(string inputFileLocation, string outputFileLocation) { int width; int height; ImageFormat format; PixelFormat pixelFormat; var fileInfo = new FileInfo(inputFileLocation); using (Stream stream = File.OpenRead(inputFileLocation)) { using (Image sourceImage = Image.FromStream(stream, false, false)) { width = sourceImage.Width; height = sourceImage.Height; format = sourceImage.RawFormat; pixelFormat = sourceImage.PixelFormat; } } // Creating the image with the pixelformat gives an error, so not passing it to CreateImageWithText, which means color depth will be different var newImage = CreateImageWithText(fileInfo.Name, width, height); newImage.Save(outputFileLocation, format); } #endregion #region Private methods /// <summary> /// Writes an xml declaration with the correct encoding /// </summary> /// <param name="encoding">Encoding</param> /// <param name="xmlReader">XmlReader positioned on a XmlDeclaration</param> /// <param name="xmlWriter">XmlWriter</param> private static void WriteXmlDeclaration(Encoding encoding, XmlReader xmlReader, XmlWriter xmlWriter) { string[] attributes = xmlReader.Value.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < attributes.Length; i++) { string attribute = attributes[i]; if (attribute.ToLower().StartsWith("encoding")) { string preFix = attribute.Substring(0, 10); string value; if (encoding == Encoding.Unicode || encoding == Encoding.BigEndianUnicode) { value = "UTF-16"; } else if (encoding == Encoding.UTF8) { value = "UTF-8"; } else { throw new NotSupportedException("Encoding '" + encoding.EncodingName + "' is not supported. Only UTF-16 and UTF-8 encodings are supported."); } string postFix = attribute.Substring(attribute.Length - 1); attributes[i] = preFix + value + postFix; } } xmlWriter.WriteProcessingInstruction(xmlReader.Name, String.Join(" ", attributes)); } /// <summary> /// Substitutes the words in a phrase or paragraph with other (hardcoded) words /// </summary> /// <param name="text">Text to obfuscate</param> /// <returns> /// Obfuscated text /// </returns> private static string ObfuscateWords(string text) { string word = String.Empty; StringBuilder result = new StringBuilder(text.Length); for (var i = 0; i < text.Length; i++) { var character = text[i]; if (Char.IsWhiteSpace(character) || Char.IsPunctuation(character) || Char.IsSeparator(character) || Char.IsNumber(character) || character == '=') { result.Append(ObfuscateWord(word)); result.Append(character); word = String.Empty; } else { word += character; } } if (word.Length > 0) { result.Append(ObfuscateWord(word)); } return result.ToString(); } /// <summary> /// Substitutes one word by another hardcoded word /// </summary> /// <param name="word">Word to obfuscate</param> /// <returns> /// Obfuscated word /// </returns> private static string ObfuscateWord(string word) { if (word == String.Empty) { return String.Empty; } string replace; if (word.Length > 20) { replace = _longWordSubstitution.Substring(0, word.Length); } else { replace = _shortWordSubstitutions[word.Length]; } if (char.IsUpper(word[0])) { return char.ToUpper(replace[0]) + replace.Substring(1); } else { return replace; } } /// <summary> /// Creates an image with the given width and height and having the given text /// </summary> /// <param name="text">Text to include in the image</param> /// <param name="width">Image width</param> /// <param name="height">Image height</param> /// <returns></returns> private static Image CreateImageWithText(String text, int width, int height) { Font font = new Font("Arial", 8, FontStyle.Regular); Color textColor = Color.Red; Color backColor = Color.Yellow; //first, create a dummy bitmap just to get a graphics object Image img = new Bitmap(1, 1); Graphics drawing = Graphics.FromImage(img); //measure the string to see how big the image needs to be SizeF textSize = drawing.MeasureString(text, font); //free up the dummy image and old graphics object img.Dispose(); drawing.Dispose(); //create a new image of the right size img = new Bitmap(width, height); drawing = Graphics.FromImage(img); //paint the background drawing.Clear(backColor); if (textSize.Width < width && textSize.Height < height) { //create a brush for the text Brush textBrush = new SolidBrush(textColor); drawing.DrawString(text, font, textBrush, 0, 0); textBrush.Dispose(); } drawing.Save(); drawing.Dispose(); return img; } #endregion } }
/* * RegistryPermission.cs - Implementation of the * "System.Security.Permissions.RegistryPermission" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Permissions { #if CONFIG_PERMISSIONS && !ECMA_COMPAT using System; using System.IO; using System.Collections; using System.Security; public sealed class RegistryPermission : CodeAccessPermission, IUnrestrictedPermission { // Internal state. private PermissionState state; private String[] readList; private String[] writeList; private String[] createList; // Constructors. public RegistryPermission(PermissionState state) { if(state != PermissionState.Unrestricted && state != PermissionState.None) { throw new ArgumentException(_("Arg_PermissionState")); } this.state = state; } public RegistryPermission(RegistryPermissionAccess flag, String pathList) { if(pathList == null) { throw new ArgumentNullException("pathList"); } if((flag & ~(RegistryPermissionAccess.AllAccess)) != 0) { throw new ArgumentException(_("Arg_RegistryAccess")); } this.state = PermissionState.None; String[] split = EnvironmentPermission.SplitPath(pathList); if((flag & RegistryPermissionAccess.Read) != 0) { readList = split; } if((flag & RegistryPermissionAccess.Write) != 0) { writeList = split; } if((flag & RegistryPermissionAccess.Create) != 0) { createList = split; } } internal RegistryPermission(PermissionState state, String[] readList, String[] writeList, String[] createList) { this.state = state; this.readList = readList; this.writeList = writeList; this.createList = createList; } // Convert an XML value into a permissions value. public override void FromXml(SecurityElement esd) { String value; if(esd == null) { throw new ArgumentNullException("esd"); } if(esd.Attribute("version") != "1") { throw new ArgumentException(_("Arg_PermissionVersion")); } value = esd.Attribute("Unrestricted"); if(value != null && Boolean.Parse(value)) { state = PermissionState.Unrestricted; } else { state = PermissionState.None; } if(state != PermissionState.Unrestricted) { readList = EnvironmentPermission.SplitPath (esd.Attribute("Read"), ';'); writeList = EnvironmentPermission.SplitPath (esd.Attribute("Write"), ';'); createList = EnvironmentPermission.SplitPath (esd.Attribute("Create"), ';'); } } // Convert this permissions object into an XML value. public override SecurityElement ToXml() { SecurityElement element; element = new SecurityElement("IPermission"); element.AddAttribute ("class", SecurityElement.Escape(typeof(RegistryPermission). AssemblyQualifiedName)); element.AddAttribute("version", "1"); if(state == PermissionState.Unrestricted) { element.AddAttribute("Unrestricted", "true"); } else { // Always use ";" as the separator so that we can // guarantee a fixed external form, regardless of // whatever PathSeparator is set to. if(readList != null) { element.AddAttribute ("Read", SecurityElement.Escape (String.Join(";", readList))); } if(writeList != null) { element.AddAttribute ("Write", SecurityElement.Escape (String.Join(";", writeList))); } if(createList != null) { element.AddAttribute ("Create", SecurityElement.Escape (String.Join(";", createList))); } } return element; } // Implement the IPermission interface. public override IPermission Copy() { return new RegistryPermission (state, readList, writeList, createList); } public override IPermission Intersect(IPermission target) { // Handle the easy cases first. if(target == null) { return target; } else if(!(target is RegistryPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if(((RegistryPermission)target).IsUnrestricted()) { return Copy(); } else if(IsUnrestricted()) { return target.Copy(); } // Create a new object and intersect the lists. return new RegistryPermission (PermissionState.None, EnvironmentPermission.Intersect(readList, ((RegistryPermission)target).readList), EnvironmentPermission.Intersect(writeList, ((RegistryPermission)target).writeList), EnvironmentPermission.Intersect(createList, ((RegistryPermission)target).createList)); } public override bool IsSubsetOf(IPermission target) { if(target == null) { return (state == PermissionState.None && readList == null && writeList == null && createList == null); } else if(!(target is RegistryPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if(((RegistryPermission)target).IsUnrestricted()) { return true; } else if(IsUnrestricted()) { return false; } else { return EnvironmentPermission.IsSubsetOf (readList, ((RegistryPermission)target).readList) && EnvironmentPermission.IsSubsetOf (writeList, ((RegistryPermission)target).writeList) && EnvironmentPermission.IsSubsetOf (createList, ((RegistryPermission)target).createList); } } public override IPermission Union(IPermission target) { if(target == null) { return Copy(); } else if(!(target is RegistryPermission)) { throw new ArgumentException(_("Arg_PermissionMismatch")); } else if(IsUnrestricted() || ((RegistryPermission)target).IsUnrestricted()) { return new RegistryPermission (PermissionState.Unrestricted); } else { return new RegistryPermission (PermissionState.None, EnvironmentPermission.Union(readList, ((RegistryPermission)target).readList, false), EnvironmentPermission.Union(writeList, ((RegistryPermission)target).writeList, false), EnvironmentPermission.Union(createList, ((RegistryPermission)target).createList, false)); } } // Determine if this object has unrestricted permissions. public bool IsUnrestricted() { return (state == PermissionState.Unrestricted); } // Set the path list information. public void SetPathList(RegistryPermissionAccess flag, String pathList) { if(pathList == null) { throw new ArgumentNullException("pathList"); } if((flag & ~(RegistryPermissionAccess.AllAccess)) != 0) { throw new ArgumentException(_("Arg_RegistryAccess")); } if((flag & RegistryPermissionAccess.Read) != 0) { readList = EnvironmentPermission.SplitPath (pathList, Path.PathSeparator); } if((flag & RegistryPermissionAccess.Write) != 0) { writeList = EnvironmentPermission.SplitPath (pathList, Path.PathSeparator); } if((flag & RegistryPermissionAccess.Create) != 0) { createList = EnvironmentPermission.SplitPath (pathList, Path.PathSeparator); } } // Add to the path list information. public void AddPathList(RegistryPermissionAccess flag, String pathList) { if(pathList == null) { throw new ArgumentNullException("pathList"); } if((flag & ~(RegistryPermissionAccess.AllAccess)) != 0) { throw new ArgumentException(_("Arg_RegistryAccess")); } if((flag & RegistryPermissionAccess.Read) != 0) { readList = EnvironmentPermission.Union(readList, EnvironmentPermission.SplitPath (pathList, Path.PathSeparator), false); } if((flag & RegistryPermissionAccess.Write) != 0) { writeList = EnvironmentPermission.Union(writeList, EnvironmentPermission.SplitPath (pathList, Path.PathSeparator), false); } if((flag & RegistryPermissionAccess.Create) != 0) { createList = EnvironmentPermission.Union(createList, EnvironmentPermission.SplitPath (pathList, Path.PathSeparator), false); } } // Get a specific path list. public String GetPathList(RegistryPermissionAccess flag) { switch(flag) { case RegistryPermissionAccess.Read: { if(readList != null) { return String.Join (Path.PathSeparator.ToString(), readList); } else { return String.Empty; } } // Not reached. case RegistryPermissionAccess.Write: { if(writeList != null) { return String.Join (Path.PathSeparator.ToString(), writeList); } else { return String.Empty; } } // Not reached. case RegistryPermissionAccess.Create: { if(createList != null) { return String.Join (Path.PathSeparator.ToString(), createList); } else { return String.Empty; } } // Not reached. default: { throw new ArgumentException(_("Arg_RegistryAccess")); } // Not reached. } } }; // class RegistryPermission #endif // CONFIG_PERMISSIONS && !ECMA_COMPAT }; // namespace System.Security.Permissions
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.ComponentModel; using System.Linq; using System.Text; using NakedObjects; using NakedObjects.Services; namespace AdventureWorksModel { public enum ProductLineEnum { R, M, T, S } public enum ProductClassEnum { H, M, L } [DisplayName("Products")] public class ProductRepository : AbstractFactoryAndRepository { #region FindProductByName [FinderAction] [TableView(true, "ProductNumber", "ProductSubcategory", "ListPrice")] [MemberOrder(1)] public IQueryable<Product> FindProductByName(string searchString) => from obj in Instances<Product>() where obj.Name.ToUpper().Contains(searchString.ToUpper()) orderby obj.Name select obj; #endregion #region FindProductByNumber [FinderAction] [QueryOnly] [MemberOrder(2)] public Product FindProductByNumber(string number) { var query = from obj in Instances<Product>() where obj.ProductNumber == number select obj; return SingleObjectWarnIfNoMatch(query); } #endregion #region RandomProduct [FinderAction] [QueryOnly] [MemberOrder(10)] public Product RandomProduct() => Random<Product>(); #endregion #region NewProduct [FinderAction] [MemberOrder(9)] public virtual Product NewProduct() => Container.NewTransientInstance<Product>(); #endregion [FinderAction] [QueryOnly] [MemberOrder(11)] public Product FindProductByKey(string key) => Container.FindByKey<Product>(int.Parse(key)); #region Inventory /// <summary> /// Action is intended to test the returing of a scalar (large multi-line string). /// </summary> /// <returns></returns> public string StockReport() { var inventories = Container.Instances<ProductInventory>().Select(pi => new InventoryLine {ProductName = pi.Product.Name, Quantity = pi.Quantity}); var sb = new StringBuilder(); sb.AppendLine(@"<h1 id=""report"">Stock Report</h1>"); sb.AppendLine("<table>"); sb.AppendLine("<tr><th>Product</th><th>Quantity</th></tr>"); foreach (var i in inventories) { sb.AppendLine("<tr><td>" + i.ProductName + "</td><td>" + i.Quantity + "</td></tr>"); } sb.AppendLine("</table>"); return sb.ToString(); } #endregion public IQueryable<ProductPhoto> AllProductPhotos() => Container.Instances<ProductPhoto>(); private class InventoryLine { public string ProductName { get; set; } public int Quantity { get; set; } } #region FindProduct [FinderAction] [QueryOnly] [MemberOrder(7)] public Product FindProduct(Product product) => product; public Product Default0FindProduct() => Instances<Product>().First(); public virtual IQueryable<Product> AutoComplete0FindProduct(string name) => from obj in Instances<Product>() where obj.Name.ToUpper().Contains(name.ToUpper()) orderby obj.Name select obj; #endregion #region ListProductsBySubCategory [FinderAction] [TableView(true, "ProductNumber", "ListPrice")] [MemberOrder(3)] public IQueryable<Product> ListProductsBySubCategory([ContributedAction("Products")] ProductSubcategory subCategory) => from obj in Instances<Product>() where obj.ProductSubcategory.ProductSubcategoryID == subCategory.ProductSubcategoryID orderby obj.Name select obj; public virtual ProductSubcategory Default0ListProductsBySubCategory() => Instances<ProductSubcategory>().First(); #endregion #region ListProducts [FinderAction] [TableView(true, "ProductNumber", "ListPrice")] [MemberOrder(3)] public IQueryable<Product> ListProducts(ProductCategory category, ProductSubcategory subCategory) => from obj in Instances<Product>() where obj.ProductSubcategory.ProductSubcategoryID == subCategory.ProductSubcategoryID orderby obj.Name select obj; public ProductCategory Default0ListProducts() => Container.Instances<ProductCategory>().First(); public IList<ProductSubcategory> Choices1ListProducts(ProductCategory category) { if (category != null) { return category.ProductSubcategory.ToList(); } return null; } #endregion #region ListProductsBySubcategories [FinderAction] [MemberOrder(4)] [QueryOnly] public IList<Product> ListProductsBySubCategories(IEnumerable<ProductSubcategory> subCategories) => QueryableOfProductsBySubcat(subCategories).ToList(); public virtual IList<ProductSubcategory> Default0ListProductsBySubCategories() { return new List<ProductSubcategory> { Instances<ProductSubcategory>().Single(psc => psc.Name == "Mountain Bikes"), Instances<ProductSubcategory>().Single(psc => psc.Name == "Touring Bikes") }; } private IQueryable<Product> QueryableOfProductsBySubcat(IEnumerable<ProductSubcategory> subCategories) { var subCatIds = subCategories.Select(x => x.ProductSubcategoryID).ToArray(); IQueryable<Product> q = from p in Instances<Product>() //from sc in subCatIds where subCatIds.Contains(p.ProductSubcategory.ProductSubcategoryID) orderby p.Name select p; return q; } public string Validate0ListProductsBySubCategories(IEnumerable<ProductSubcategory> subCategories) { var rb = new ReasonBuilder(); rb.AppendOnCondition(subCategories.Count() > 5, "Max 5 SubCategories may be selected"); return rb.Reason; } #endregion #region FindProductsByCategory [FinderAction] [MemberOrder(8)] public IQueryable<Product> FindProductsByCategory(IEnumerable<ProductCategory> categories, IEnumerable<ProductSubcategory> subcategories) => QueryableOfProductsBySubcat(subcategories); public IQueryable<ProductCategory> Choices0FindProductsByCategory() => Instances<ProductCategory>(); public IQueryable<ProductSubcategory> Choices1FindProductsByCategory(IEnumerable<ProductCategory> categories) { if (categories != null) { var catIds = categories.Select(c => c.ProductCategoryID).ToArray(); return from psc in Instances<ProductSubcategory>() //from cid in catIds where catIds.Contains(psc.ProductCategory.ProductCategoryID) select psc; } return new ProductSubcategory[] { }.AsQueryable(); } public IList<ProductCategory> Default0FindProductsByCategory() => new List<ProductCategory> {Instances<ProductCategory>().First()}; public List<ProductSubcategory> Default1FindProductsByCategory() { var pcs = Default0FindProductsByCategory(); if (pcs != null) { var ids = pcs.Select(c => c.ProductCategoryID).ToArray(); return (from psc in Instances<ProductSubcategory>() //from cid in ids where ids.Contains(psc.ProductCategory.ProductCategoryID) select psc).OrderBy(psc => psc.ProductSubcategoryID).Take(2).ToList(); } return new List<ProductSubcategory>(); } #endregion #region FindByProductLinesAndClasses [FinderAction] [MemberOrder(6)] public IQueryable<Product> FindByProductLinesAndClasses(IEnumerable<ProductLineEnum> productLine, IEnumerable<ProductClassEnum> productClass) { var products = Container.Instances<Product>(); foreach (var pl in productLine) { var pls = Enum.GetName(typeof(ProductLineEnum), pl); products = products.Where(p => p.ProductLine == pls); } foreach (var pc in productClass) { var pcs = Enum.GetName(typeof(ProductClassEnum), pc); products = products.Where(p => p.Class == pcs); } return products; } public virtual IList<ProductLineEnum> Default0FindByProductLinesAndClasses() => new List<ProductLineEnum> {ProductLineEnum.M, ProductLineEnum.S}; public virtual IList<ProductClassEnum> Default1FindByProductLinesAndClasses() => new List<ProductClassEnum> {ProductClassEnum.H}; [FinderAction] [MemberOrder(7)] public IQueryable<Product> FindByOptionalProductLinesAndClasses([Optionally] IEnumerable<ProductLineEnum> productLine, [Optionally] IEnumerable<ProductClassEnum> productClass) { var products = Container.Instances<Product>(); if (productLine != null) { foreach (var pl in productLine) { var pls = Enum.GetName(typeof(ProductLineEnum), pl); products = products.Where(p => p.ProductLine == pls); } } if (productClass != null) { foreach (var pc in productClass) { var pcs = Enum.GetName(typeof(ProductClassEnum), pc); products = products.Where(p => p.Class == pcs); } } return products; } public virtual IList<ProductLineEnum> Default0FindByOptionalProductLinesAndClasses() => new List<ProductLineEnum> {ProductLineEnum.M, ProductLineEnum.S}; public virtual IList<ProductClassEnum> Default1FindByOptionalProductLinesAndClasses() => new List<ProductClassEnum> {ProductClassEnum.H}; #endregion #region FindByProductLineAndClass [FinderAction] [MemberOrder(5)] public IQueryable<Product> FindByProductLineAndClass(ProductLineEnum productLine, ProductClassEnum productClass) { var pls = Enum.GetName(typeof(ProductLineEnum), productLine); var pcs = Enum.GetName(typeof(ProductClassEnum), productClass); return Container.Instances<Product>().Where(p => p.ProductLine == pls && p.Class == pcs); } public virtual ProductLineEnum Default0FindByProductLineAndClass() => ProductLineEnum.M; public virtual ProductClassEnum Default1FindByProductLineAndClass() => ProductClassEnum.H; #endregion } }
namespace Excel.Core.BinaryFormat { internal enum STGTY : byte { STGTY_INVALID = 0, STGTY_STORAGE = 1, STGTY_STREAM = 2, STGTY_LOCKBYTES = 3, STGTY_PROPERTY = 4, STGTY_ROOT = 5 } internal enum DECOLOR : byte { DE_RED = 0, DE_BLACK = 1 } internal enum FATMARKERS : uint { FAT_EndOfChain = 0xFFFFFFFE, FAT_FreeSpace = 0xFFFFFFFF, FAT_FatSector = 0xFFFFFFFD, FAT_DifSector = 0xFFFFFFFC } internal enum BIFFTYPE : ushort { WorkbookGlobals = 0x0005, VBModule = 0x0006, Worksheet = 0x0010, Chart = 0x0020, v4MacroSheet = 0x0040, v4WorkbookGlobals = 0x0100 } internal enum BIFFRECORDTYPE : ushort { INTERFACEHDR = 0x00E1, MMS = 0x00C1, INTERFACEEND = 0x00E2, WRITEACCESS = 0x005C, CODEPAGE = 0x0042, DSF = 0x0161, TABID = 0x013D, FNGROUPCOUNT = 0x009C, WINDOWPROTECT = 0x0019, PROTECT = 0x0012, PASSWORD = 0x0013, PROT4REV = 0x01AF, PROT4REVPASSWORD = 0x01BC, WINDOW1 = 0x003D, BACKUP = 0x0040, HIDEOBJ = 0x008D, RECORD1904 = 0x0022, REFRESHALL = 0x01B7, BOOKBOOL = 0x00DA, FONT = 0x0031, // Font record, BIFF2, 5 and later FONT_V34 = 0x0231, // Font record, BIFF3, 4 FORMAT = 0x041E, // Format record, BIFF4 and later FORMAT_V23 = 0x001E, // Format record, BIFF2, 3 XF = 0x00E0, // Extended format record, BIFF5 and later XF_V4 = 0x0443, // Extended format record, BIFF4 XF_V3 = 0x0243, // Extended format record, BIFF3 XF_V2 = 0x0043, // Extended format record, BIFF2 STYLE = 0x0293, BOUNDSHEET = 0x0085, COUNTRY = 0x008C, SST = 0x00FC, // Global string storage (for BIFF8) CONTINUE = 0x003C, EXTSST = 0x00FF, BOF = 0x0809, // BOF ID for BIFF5 and later BOF_V2 = 0x0009, // BOF ID for BIFF2 BOF_V3 = 0x0209, // BOF ID for BIFF3 BOF_V4 = 0x0409, // BOF ID for BIFF5 EOF = 0x000A, // End of block started with BOF CALCCOUNT = 0x000C, CALCMODE = 0x000D, PRECISION = 0x000E, REFMODE = 0x000F, DELTA = 0x0010, ITERATION = 0x0011, SAVERECALC = 0x005F, PRINTHEADERS = 0x002A, PRINTGRIDLINES = 0x002B, GUTS = 0x0080, WSBOOL = 0x0081, GRIDSET = 0x0082, DEFAULTROWHEIGHT = 0x0225, HEADER = 0x0014, FOOTER = 0x0015, HCENTER = 0x0083, VCENTER = 0x0084, PRINTSETUP = 0x00A1, DFAULTCOLWIDTH = 0x0055, DIMENSIONS = 0x0200, // Size of area used for data ROW = 0x0208, // Row record WINDOW2 = 0x023E, SELECTION = 0x001D, INDEX = 0x020B, // Index record, unsure about signature DBCELL = 0x00D7, // DBCell record, unsure about signature BLANK = 0x0201, // Empty cell BLANK_OLD = 0x0001, // Empty cell, old format MULBLANK = 0x00BE, // Equivalent of up to 256 blank cells INTEGER = 0x0202, // Integer cell (0..65535) INTEGER_OLD = 0x0002, // Integer cell (0..65535), old format NUMBER = 0x0203, // Numeric cell NUMBER_OLD = 0x0003, // Numeric cell, old format LABEL = 0x0204, // String cell (up to 255 symbols) LABEL_OLD = 0x0004, // String cell (up to 255 symbols), old format LABELSST = 0x00FD, // String cell with value from SST (for BIFF8) FORMULA = 0x0406, // Formula cell FORMULA_OLD = 0x0006, // Formula cell, old format BOOLERR = 0x0205, // Boolean or error cell BOOLERR_OLD = 0x0005, // Boolean or error cell, old format ARRAY = 0x0221, // Range of cells for multi-cell formula RK = 0x027E, // RK-format numeric cell MULRK = 0x00BD, // Equivalent of up to 256 RK cells RSTRING = 0x00D6, // Rich-formatted string cell SHRFMLA = 0x04BC, // One more formula optimization element SHRFMLA_OLD = 0x00BC, // One more formula optimization element, old format STRING = 0x0207, // And one more, for string formula results CF = 0x01B1, CODENAME = 0x01BA, CONDFMT = 0x01B0, DCONBIN = 0x01B5, DV = 0x01BE, DVAL = 0x01B2, HLINK = 0x01B8, MSODRAWINGGROUP = 0x00EB, MSODRAWING = 0x00EC, MSODRAWINGSELECTION = 0x00ED, PARAMQRY = 0x00DC, QSI = 0x01AD, SUPBOOK = 0x01AE, SXDB = 0x00C6, SXDBEX = 0x0122, SXFDBTYPE = 0x01BB, SXRULE = 0x00F0, SXEX = 0x00F1, SXFILT = 0x00F2, SXNAME = 0x00F6, SXSELECT = 0x00F7, SXPAIR = 0x00F8, SXFMLA = 0x00F9, SXFORMAT = 0x00FB, SXFORMULA = 0x0103, SXVDEX = 0x0100, TXO = 0x01B6, USERBVIEW = 0x01A9, USERSVIEWBEGIN = 0x01AA, USERSVIEWEND = 0x01AB, USESELFS = 0x0160, XL5MODIFY = 0x0162, OBJ = 0x005D, NOTE = 0x001C, SXEXT = 0x00DC, VERTICALPAGEBREAKS = 0x001A, XCT = 0x0059, /// <summary> /// If present the Calculate Message was in the status bar when Excel saved the file. /// This occurs if the sheet changed, the Manual calculation option was on, and the Recalculate Before Save option was off. /// </summary> UNCALCED = 0x005E, QUICKTIP = 0x0800 } internal enum FORMULAERROR : byte { NULL = 0x00, // #NULL! DIV0 = 0x07, // #DIV/0! VALUE = 0x0F, // #VALUE! REF = 0x17, // #REF! NAME = 0x1D, // #NAME? NUM = 0x24, // #NUM! NA = 0x2A, // #N/A } }
// 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.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Xunit; using Xunit.Sdk; namespace Microsoft.AspNetCore.Razor.Language.Legacy { [IntializeTestFile] public abstract class ParserTestBase { private static readonly AsyncLocal<string> _fileName = new AsyncLocal<string>(); private static readonly AsyncLocal<bool> _isTheory = new AsyncLocal<bool>(); internal ParserTestBase() { TestProjectRoot = TestProject.GetProjectDirectory(GetType()); } /// <summary> /// Set to true to autocorrect the locations of spans to appear in document order with no gaps. /// Use this when spans were not created in document order. /// </summary> protected bool FixupSpans { get; set; } #if GENERATE_BASELINES protected bool GenerateBaselines { get; set; } = true; #else protected bool GenerateBaselines { get; set; } = false; #endif protected string TestProjectRoot { get; } // Used by the test framework to set the 'base' name for test files. public static string FileName { get { return _fileName.Value; } set { _fileName.Value = value; } } public static bool IsTheory { get { return _isTheory.Value; } set { _isTheory.Value = value; } } protected int BaselineTestCount { get; set; } internal virtual void AssertSyntaxTreeNodeMatchesBaseline(RazorSyntaxTree syntaxTree) { var root = syntaxTree.Root; var diagnostics = syntaxTree.Diagnostics; var filePath = syntaxTree.Source.FilePath; if (FileName == null) { var message = $"{nameof(AssertSyntaxTreeNodeMatchesBaseline)} should only be called from a parser test ({nameof(FileName)} is null)."; throw new InvalidOperationException(message); } if (IsTheory) { var message = $"{nameof(AssertSyntaxTreeNodeMatchesBaseline)} should not be called from a [Theory] test."; throw new InvalidOperationException(message); } var fileName = BaselineTestCount > 0 ? FileName + $"_{BaselineTestCount}" : FileName; var baselineFileName = Path.ChangeExtension(fileName, ".stree.txt"); var baselineDiagnosticsFileName = Path.ChangeExtension(fileName, ".diag.txt"); var baselineClassifiedSpansFileName = Path.ChangeExtension(fileName, ".cspans.txt"); var baselineTagHelperSpansFileName = Path.ChangeExtension(fileName, ".tspans.txt"); BaselineTestCount++; if (GenerateBaselines) { // Write syntax tree baseline var baselineFullPath = Path.Combine(TestProjectRoot, baselineFileName); File.WriteAllText(baselineFullPath, SyntaxNodeSerializer.Serialize(root)); // Write diagnostics baseline var baselineDiagnosticsFullPath = Path.Combine(TestProjectRoot, baselineDiagnosticsFileName); var lines = diagnostics.Select(SerializeDiagnostic).ToArray(); if (lines.Any()) { File.WriteAllLines(baselineDiagnosticsFullPath, lines); } else if (File.Exists(baselineDiagnosticsFullPath)) { File.Delete(baselineDiagnosticsFullPath); } // Write classified spans baseline var classifiedSpansBaselineFullPath = Path.Combine(TestProjectRoot, baselineClassifiedSpansFileName); File.WriteAllText(classifiedSpansBaselineFullPath, ClassifiedSpanSerializer.Serialize(syntaxTree)); // Write tag helper spans baseline var tagHelperSpansBaselineFullPath = Path.Combine(TestProjectRoot, baselineTagHelperSpansFileName); var serializedTagHelperSpans = TagHelperSpanSerializer.Serialize(syntaxTree); if (!string.IsNullOrEmpty(serializedTagHelperSpans)) { File.WriteAllText(tagHelperSpansBaselineFullPath, serializedTagHelperSpans); } else if (File.Exists(tagHelperSpansBaselineFullPath)) { File.Delete(tagHelperSpansBaselineFullPath); } return; } // Verify syntax tree var stFile = TestFile.Create(baselineFileName, GetType().GetTypeInfo().Assembly); if (!stFile.Exists()) { throw new XunitException($"The resource {baselineFileName} was not found."); } var baseline = stFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); SyntaxNodeVerifier.Verify(root, baseline); // Verify diagnostics var baselineDiagnostics = string.Empty; var diagnosticsFile = TestFile.Create(baselineDiagnosticsFileName, GetType().GetTypeInfo().Assembly); if (diagnosticsFile.Exists()) { baselineDiagnostics = diagnosticsFile.ReadAllText(); } var actualDiagnostics = string.Concat(diagnostics.Select(d => SerializeDiagnostic(d) + "\r\n")); Assert.Equal(baselineDiagnostics, actualDiagnostics); // Verify classified spans var classifiedSpanFile = TestFile.Create(baselineClassifiedSpansFileName, GetType().GetTypeInfo().Assembly); if (!classifiedSpanFile.Exists()) { throw new XunitException($"The resource {baselineClassifiedSpansFileName} was not found."); } else { var classifiedSpanBaseline = new string[0]; classifiedSpanBaseline = classifiedSpanFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); ClassifiedSpanVerifier.Verify(syntaxTree, classifiedSpanBaseline); } // Verify tag helper spans var tagHelperSpanFile = TestFile.Create(baselineTagHelperSpansFileName, GetType().GetTypeInfo().Assembly); var tagHelperSpanBaseline = new string[0]; if (tagHelperSpanFile.Exists()) { tagHelperSpanBaseline = tagHelperSpanFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); TagHelperSpanVerifier.Verify(syntaxTree, tagHelperSpanBaseline); } } protected static string SerializeDiagnostic(RazorDiagnostic diagnostic) { var content = RazorDiagnosticSerializer.Serialize(diagnostic); var normalized = NormalizeNewLines(content); return normalized; } private static string NormalizeNewLines(string content) { return Regex.Replace(content, "(?<!\r)\n", "\r\n", RegexOptions.None, TimeSpan.FromSeconds(10)); } internal virtual void BaselineTest(RazorSyntaxTree syntaxTree, bool verifySyntaxTree = true, bool ensureFullFidelity = true) { if (verifySyntaxTree) { SyntaxTreeVerifier.Verify(syntaxTree, ensureFullFidelity); } AssertSyntaxTreeNodeMatchesBaseline(syntaxTree); } internal RazorSyntaxTree ParseDocument(string document, bool designTime = false, IEnumerable<DirectiveDescriptor> directives = null, RazorParserFeatureFlags featureFlags = null, string fileKind = null) { return ParseDocument(RazorLanguageVersion.Latest, document, directives, designTime, featureFlags, fileKind); } internal virtual RazorSyntaxTree ParseDocument(RazorLanguageVersion version, string document, IEnumerable<DirectiveDescriptor> directives, bool designTime = false, RazorParserFeatureFlags featureFlags = null, string fileKind = null) { directives = directives ?? Array.Empty<DirectiveDescriptor>(); var source = TestRazorSourceDocument.Create(document, filePath: null, relativePath: null, normalizeNewLines: true); var options = CreateParserOptions(version, directives, designTime, featureFlags, fileKind); var context = new ParserContext(source, options); var codeParser = new CSharpCodeParser(directives, context); var markupParser = new HtmlMarkupParser(context); codeParser.HtmlParser = markupParser; markupParser.CodeParser = codeParser; var root = markupParser.ParseDocument().CreateRed(); var diagnostics = context.ErrorSink.Errors; var codeDocument = RazorCodeDocument.Create(source); var syntaxTree = RazorSyntaxTree.Create(root, source, diagnostics, options); codeDocument.SetSyntaxTree(syntaxTree); var defaultDirectivePass = new DefaultDirectiveSyntaxTreePass(); syntaxTree = defaultDirectivePass.Execute(codeDocument, syntaxTree); return syntaxTree; } internal virtual void ParseDocumentTest(string document) { ParseDocumentTest(document, null, false); } internal virtual void ParseDocumentTest(string document, string fileKind) { ParseDocumentTest(document, null, false, fileKind); } internal virtual void ParseDocumentTest(string document, IEnumerable<DirectiveDescriptor> directives) { ParseDocumentTest(document, directives, false); } internal virtual void ParseDocumentTest(string document, bool designTime) { ParseDocumentTest(document, null, designTime); } internal virtual void ParseDocumentTest(string document, IEnumerable<DirectiveDescriptor> directives, bool designTime, string fileKind = null) { ParseDocumentTest(RazorLanguageVersion.Latest, document, directives, designTime, fileKind); } internal virtual void ParseDocumentTest(RazorLanguageVersion version, string document, IEnumerable<DirectiveDescriptor> directives, bool designTime, string fileKind = null) { var result = ParseDocument(version, document, directives, designTime, fileKind: fileKind); BaselineTest(result); } internal static RazorParserOptions CreateParserOptions( RazorLanguageVersion version, IEnumerable<DirectiveDescriptor> directives, bool designTime, RazorParserFeatureFlags featureFlags = null, string fileKind = null) { return new TestRazorParserOptions( directives.ToArray(), designTime, parseLeadingDirectives: false, version: version, fileKind: fileKind ?? FileKinds.Legacy, featureFlags: featureFlags); } private class TestRazorParserOptions : RazorParserOptions { public TestRazorParserOptions(DirectiveDescriptor[] directives, bool designTime, bool parseLeadingDirectives, RazorLanguageVersion version, string fileKind, RazorParserFeatureFlags featureFlags = null) { if (directives == null) { throw new ArgumentNullException(nameof(directives)); } Directives = directives; DesignTime = designTime; ParseLeadingDirectives = parseLeadingDirectives; Version = version; FileKind = fileKind; FeatureFlags = featureFlags ?? RazorParserFeatureFlags.Create(Version, fileKind); } public override bool DesignTime { get; } internal override string FileKind { get; } public override IReadOnlyCollection<DirectiveDescriptor> Directives { get; } public override bool ParseLeadingDirectives { get; } public override RazorLanguageVersion Version { get; } internal override RazorParserFeatureFlags FeatureFlags { get; } } } }
// Copyright Bastian Eicher // Licensed under the MIT License using System.Globalization; using System.Security.Cryptography; #if NET20 using System.Text; #endif #if !NET20 && !NET40 using System.Runtime.CompilerServices; #endif namespace NanoByte.Common; /// <summary> /// Provides additional or simplified string functions. /// </summary> public static class StringUtils { /// <summary> /// Compares strings using case-insensitive comparison. /// </summary> [Pure] #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool EqualsIgnoreCase(string? s1, string? s2) => string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase); /// <summary> /// Compares chars using case-insensitive comparison. /// </summary> [Pure] #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool EqualsIgnoreCase(char c1, char c2) => char.ToLowerInvariant(c1) == char.ToLowerInvariant(c2); /// <summary> /// Compares strings using case sensitive, invariant culture comparison and considering <c>null</c> and <see cref="string.Empty"/> equal. /// </summary> [Pure] #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool EqualsEmptyNull(string? s1, string? s2) => string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2) || s1 == s2; /// <summary> /// Determines whether a string contains <paramref name="searchFor"/> using case-insensitive comparison. /// </summary> /// <param name="value">The string to search.</param> /// <param name="searchFor">The string to search for in <paramref name="value"/>.</param> [Pure] public static bool ContainsIgnoreCase(this string value, string searchFor) => value.ToUpperInvariant().Contains(searchFor.ToUpperInvariant()); /// <summary> /// Determines whether a string contains any whitespace characters. /// </summary> [Pure] public static bool ContainsWhitespace(this string value) => value.Any(char.IsWhiteSpace); /// <summary> /// Determines whether a string starts with <paramref name="searchFor"/> and, if so, returns the <paramref name="rest"/> that comes after. /// </summary> [Pure] public static bool StartsWith(this string value, string searchFor, [MaybeNullWhen(false)] out string rest) { if (value.StartsWith(searchFor)) { rest = value[searchFor.Length..]; return true; } else { rest = null; return false; } } /// <summary> /// Determines whether a string starts with <paramref name="searchFor"/> and, if so, returns the <paramref name="rest"/> that comes before. /// </summary> [Pure] public static bool EndsWith(this string value, string searchFor, [MaybeNullWhen(false)] out string rest) { if (value.EndsWith(searchFor)) { rest = value[..^searchFor.Length]; return true; } else { rest = null; return false; } } /// <summary> /// Determines whether a string starts with <paramref name="searchFor"/> with case-insensitive comparison. /// </summary> [Pure] #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool StartsWithIgnoreCase(this string value, string searchFor) => value.StartsWith(searchFor, StringComparison.OrdinalIgnoreCase); /// <summary> /// Determines whether a string ends with <paramref name="searchFor"/> with case-insensitive comparison. /// </summary> [Pure] #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static bool EndsWithIgnoreCase(this string value, string searchFor) => value.EndsWith(searchFor, StringComparison.OrdinalIgnoreCase); /// <summary> /// Removes all occurrences of a specific set of characters from a string. /// </summary> [Pure] [return: NotNullIfNotNull("value")] public static string? RemoveCharacters(this string? value, [InstantHandle] IEnumerable<char> characters) => value == null ? null : new string(value.Except(characters.Contains).ToArray()); /// <summary> /// Cuts off strings longer than <paramref name="maxLength"/> and replaces the rest with ellipsis (...). /// </summary> #if !NET20 && !NET40 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public static string TrimOverflow(this string value, int maxLength) => (value.Length <= maxLength) ? value : value[..maxLength] + "..."; /// <summary> /// Splits a multiline string to several strings and returns the result as a string array. /// </summary> [Pure] public static string[] SplitMultilineText(this string value) { var result = new List<string>(); string[] split1 = value.Split('\n'); string[] split2 = value.Split('\r'); string[] split = split1.Length >= split2.Length ? split1 : split2; foreach (string line in split) { // Never add any \r or \n to the single lines if (line.EndsWithIgnoreCase("\r") || line.EndsWithIgnoreCase("\n")) result.Add(line[..^1]); else if (line.StartsWithIgnoreCase("\n") || line.StartsWithIgnoreCase("\r")) result.Add(line[1..]); else result.Add(line); } return result.ToArray(); } /// <summary> /// Combines multiple strings into one, placing a <paramref name="separator"/> between the <paramref name="parts"/>. /// </summary> /// <param name="separator">The separator characters to place between the <paramref name="parts"/>.</param> /// <param name="parts">The strings to be combined.</param> [Pure] public static string Join(string separator, [InstantHandle] IEnumerable<string> parts) #if NET20 { var output = new StringBuilder(); bool first = true; foreach (string part in parts) { // No separator before first or after last part if (first) first = false; else output.Append(separator); output.Append(part); } return output.ToString(); } #else => string.Join(separator, parts); #endif /// <summary> /// Get everything to the left of the first occurrence of a character. /// </summary> [Pure] public static string GetLeftPartAtFirstOccurrence(this string value, char searchFor) { int index = value.IndexOf(searchFor); return (index == -1) ? value : value[..index]; } /// <summary> /// Get everything to the right of the first occurrence of a character. /// </summary> [Pure] public static string GetRightPartAtFirstOccurrence(this string value, char searchFor) { int index = value.IndexOf(searchFor); return (index == -1) ? "" : value[(index + 1)..]; } /// <summary> /// Get everything to the left of the last occurrence of a character. /// </summary> [Pure] public static string GetLeftPartAtLastOccurrence(this string value, char searchFor) { int index = value.LastIndexOf(searchFor); return (index == -1) ? value : value[..index]; } /// <summary> /// Get everything to the right of the last occurrence of a character. /// </summary> [Pure] public static string GetRightPartAtLastOccurrence(this string value, char searchFor) { int index = value.LastIndexOf(searchFor); return (index == -1) ? value : value[(index + 1)..]; } /// <summary> /// Get everything to the left of the first occurrence of a string. /// </summary> [Pure] public static string GetLeftPartAtFirstOccurrence(this string value, string searchFor) { int index = value.IndexOf(searchFor, StringComparison.Ordinal); return (index == -1) ? value : value[..index]; } /// <summary> /// Get everything to the right of the first occurrence of a string. /// </summary> [Pure] public static string GetRightPartAtFirstOccurrence(this string value, string searchFor) { int index = value.IndexOf(searchFor, StringComparison.Ordinal); return (index == -1) ? "" : value[(index + searchFor.Length)..]; } /// <summary> /// Get everything to the left of the last occurrence of a string. /// </summary> [Pure] public static string GetLeftPartAtLastOccurrence(this string value, string searchFor) { int index = value.LastIndexOf(searchFor, StringComparison.Ordinal); return (index == -1) ? value : value[..index]; } /// <summary> /// Get everything to the right of the last occurrence of a string. /// </summary> [Pure] public static string GetRightPartAtLastOccurrence(this string value, string searchFor) { int index = value.LastIndexOf(searchFor, StringComparison.Ordinal); return (index == -1) ? "" : value[(index + searchFor.Length)..]; } /// <summary> /// Formats a byte number in human-readable form (KB, MB, GB). /// </summary> /// <param name="value">The value in bytes.</param> /// <param name="provider">Provides culture-specific formatting information.</param> public static string FormatBytes(this long value, IFormatProvider? provider = null) { provider ??= CultureInfo.CurrentCulture; return value switch { >= 1073741824 => string.Format(provider, "{0:0.00}", value / 1073741824f) + " GB", >= 1048576 => string.Format(provider, "{0:0.00}", value / 1048576f) + " MB", >= 1024 => string.Format(provider, "{0:0.00}", value / 1024f) + " KB", _ => value + " Bytes" }; } /// <summary> /// Returns a string filled with random human-readable ASCII characters based on a cryptographic random number generator. /// </summary> /// <param name="length">The length of the string to be generated.</param> [Pure] public static string GeneratePassword(int length) { var generator = RandomNumberGenerator.Create(); byte[] array = new byte[(int)Math.Round(length * 3 / 4f)]; generator.GetBytes(array); // Use base64 encoding without '=' padding and with '-' instead of 'l' return Convert.ToBase64String(array)[..length].Replace('l', '-'); } }
/* ==================================================================== 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 NPOI.SS.Formula; using NPOI.XSSF.UserModel; using System; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.Udf; using System.Collections.Generic; namespace NPOI.XSSF.UserModel { /** * Evaluates formula cells.<p/> * * For performance reasons, this class keeps a cache of all previously calculated intermediate * cell values. Be sure to call {@link #ClearAllCachedResultValues()} if any workbook cells are Changed between * calls to Evaluate~ methods on this class. * * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * @author Josh Micich */ public class XSSFFormulaEvaluator : IFormulaEvaluator, IWorkbookEvaluatorProvider { private WorkbookEvaluator _bookEvaluator; private XSSFWorkbook _book; public XSSFFormulaEvaluator(IWorkbook workbook) : this(workbook as XSSFWorkbook, null, null) { } public XSSFFormulaEvaluator(XSSFWorkbook workbook) : this(workbook, null, null) { } /** * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code> * for the (conservative) assumption that any cell may have its defInition Changed After * Evaluation begins. * @deprecated (Sep 2009) (reduce overloading) use {@link #Create(XSSFWorkbook, NPOI.ss.formula.IStabilityClassifier, NPOI.ss.formula.udf.UDFFinder)} */ public XSSFFormulaEvaluator(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier) { _bookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.Create(workbook), stabilityClassifier, null); _book = workbook; } private XSSFFormulaEvaluator(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { _bookEvaluator = new WorkbookEvaluator(XSSFEvaluationWorkbook.Create(workbook), stabilityClassifier, udfFinder); _book = workbook; } /** * @param stabilityClassifier used to optimise caching performance. Pass <code>null</code> * for the (conservative) assumption that any cell may have its defInition Changed After * Evaluation begins. * @param udfFinder pass <code>null</code> for default (AnalysisToolPak only) */ public static XSSFFormulaEvaluator Create(XSSFWorkbook workbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { return new XSSFFormulaEvaluator(workbook, stabilityClassifier, udfFinder); } /** * Should be called whenever there are major Changes (e.g. moving sheets) to input cells * in the Evaluated workbook. * Failure to call this method After changing cell values will cause incorrect behaviour * of the Evaluate~ methods of this class */ public void ClearAllCachedResultValues() { _bookEvaluator.ClearAllCachedResultValues(); } public void NotifySetFormula(ICell cell) { _bookEvaluator.NotifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); } public void NotifyDeleteCell(ICell cell) { _bookEvaluator.NotifyDeleteCell(new XSSFEvaluationCell((XSSFCell)cell)); } public void NotifyUpdateCell(ICell cell) { _bookEvaluator.NotifyUpdateCell(new XSSFEvaluationCell((XSSFCell)cell)); } /** * If cell Contains a formula, the formula is Evaluated and returned, * else the CellValue simply copies the appropriate cell value from * the cell and also its cell type. This method should be preferred over * EvaluateInCell() when the call should not modify the contents of the * original cell. * @param cell */ public CellValue Evaluate(ICell cell) { if (cell == null) { return null; } switch (cell.CellType) { case CellType.Boolean: return CellValue.ValueOf(cell.BooleanCellValue); case CellType.Error: return CellValue.GetError(cell.ErrorCellValue); case CellType.Formula: return EvaluateFormulaCellValue(cell); case CellType.Numeric: return new CellValue(cell.NumericCellValue); case CellType.String: return new CellValue(cell.RichStringCellValue.String); case CellType.Blank: return null; } throw new InvalidOperationException("Bad cell type (" + cell.CellType + ")"); } /** * If cell Contains formula, it Evaluates the formula, * and saves the result of the formula. The cell * remains as a formula cell. * Else if cell does not contain formula, this method leaves * the cell unChanged. * Note that the type of the formula result is returned, * so you know what kind of value is also stored with * the formula. * <pre> * int EvaluatedCellType = Evaluator.EvaluateFormulaCell(cell); * </pre> * Be aware that your cell will hold both the formula, * and the result. If you want the cell Replaced with * the result of the formula, use {@link #Evaluate(NPOI.ss.usermodel.Cell)} } * @param cell The cell to Evaluate * @return The type of the formula result (the cell's type remains as HSSFCell.CELL_TYPE_FORMULA however) */ public CellType EvaluateFormulaCell(ICell cell) { if (cell == null || cell.CellType != CellType.Formula) { return CellType.Unknown; } CellValue cv = EvaluateFormulaCellValue(cell); // cell remains a formula cell, but the cached value is Changed SetCellValue(cell, cv); return cv.CellType; } /** * If cell Contains formula, it Evaluates the formula, and * Puts the formula result back into the cell, in place * of the old formula. * Else if cell does not contain formula, this method leaves * the cell unChanged. * Note that the same instance of HSSFCell is returned to * allow chained calls like: * <pre> * int EvaluatedCellType = Evaluator.EvaluateInCell(cell).CellType; * </pre> * Be aware that your cell value will be Changed to hold the * result of the formula. If you simply want the formula * value computed for you, use {@link #EvaluateFormulaCell(NPOI.ss.usermodel.Cell)} } * @param cell */ public ICell EvaluateInCell(ICell cell) { if (cell == null) { return null; } XSSFCell result = (XSSFCell)cell; if (cell.CellType == CellType.Formula) { CellValue cv = EvaluateFormulaCellValue(cell); SetCellType(cell, cv); // cell will no longer be a formula cell SetCellValue(cell, cv); } return result; } private static void SetCellType(ICell cell, CellValue cv) { CellType cellType = cv.CellType; switch (cellType) { case CellType.Boolean: case CellType.Error: case CellType.Numeric: case CellType.String: cell.SetCellType(cellType); return; case CellType.Blank: // never happens - blanks eventually Get translated to zero case CellType.Formula: // this will never happen, we have already Evaluated the formula break; } throw new InvalidOperationException("Unexpected cell value type (" + cellType + ")"); } private static void SetCellValue(ICell cell, CellValue cv) { CellType cellType = cv.CellType; switch (cellType) { case CellType.Boolean: cell.SetCellValue(cv.BooleanValue); break; case CellType.Error: cell.SetCellErrorValue((byte)cv.ErrorValue); break; case CellType.Numeric: cell.SetCellValue(cv.NumberValue); break; case CellType.String: cell.SetCellValue(new XSSFRichTextString(cv.StringValue)); break; case CellType.Blank: // never happens - blanks eventually Get translated to zero case CellType.Formula: // this will never happen, we have already Evaluated the formula default: throw new InvalidOperationException("Unexpected cell value type (" + cellType + ")"); } } /** * Loops over all cells in all sheets of the supplied * workbook. * For cells that contain formulas, their formulas are * Evaluated, and the results are saved. These cells * remain as formula cells. * For cells that do not contain formulas, no Changes * are made. * This is a helpful wrapper around looping over all * cells, and calling EvaluateFormulaCell on each one. */ public static void EvaluateAllFormulaCells(IWorkbook wb) { HSSFFormulaEvaluator.EvaluateAllFormulaCells(wb); } /** * Loops over all cells in all sheets of the supplied * workbook. * For cells that contain formulas, their formulas are * Evaluated, and the results are saved. These cells * remain as formula cells. * For cells that do not contain formulas, no Changes * are made. * This is a helpful wrapper around looping over all * cells, and calling EvaluateFormulaCell on each one. */ public void EvaluateAll() { HSSFFormulaEvaluator.EvaluateAllFormulaCells(_book); } /** * Returns a CellValue wrapper around the supplied ValueEval instance. */ private CellValue EvaluateFormulaCellValue(ICell cell) { if (!(cell is XSSFCell)) { throw new ArgumentException("Unexpected type of cell: " + cell.GetType() + "." + " Only XSSFCells can be Evaluated."); } ValueEval eval = _bookEvaluator.Evaluate(new XSSFEvaluationCell((XSSFCell)cell)); if (eval is NumberEval) { NumberEval ne = (NumberEval)eval; return new CellValue(ne.NumberValue); } if (eval is BoolEval) { BoolEval be = (BoolEval)eval; return CellValue.ValueOf(be.BooleanValue); } if (eval is StringEval) { StringEval ne = (StringEval)eval; return new CellValue(ne.StringValue); } if (eval is ErrorEval) { return CellValue.GetError(((ErrorEval)eval).ErrorCode); } throw new Exception("Unexpected eval class (" + eval.GetType().Name + ")"); } public void SetupReferencedWorkbooks(Dictionary<String, IFormulaEvaluator> evaluators) { CollaboratingWorkbooksEnvironment.SetupFormulaEvaluator(evaluators); } public WorkbookEvaluator GetWorkbookEvaluator() { return _bookEvaluator; } public bool IgnoreMissingWorkbooks { get { return _bookEvaluator.IgnoreMissingWorkbooks; } set { _bookEvaluator.IgnoreMissingWorkbooks = value; } } public bool DebugEvaluationOutputForNextEval { get { return _bookEvaluator.DebugEvaluationOutputForNextEval; } set { _bookEvaluator.DebugEvaluationOutputForNextEval = (value); } } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="VC6.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.VisualStudio { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.Build.Framework; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Build</i> (<b>Required: </b> Projects <b>Optional: </b>MSDEVPath, StopOnError)</para> /// <para><b>Remote Execution Support:</b> NA</para> /// <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)"/> /// <ItemGroup> /// <!-- This uses $(Platform) and $(Configuration) for all projects in the .dsp file --> /// <ProjectsToBuild Include="C:\MyVC6Project.dsp"/> /// <!-- Uses supplied platform and configuration for all projects in the .dsp file --> /// <ProjectsToBuild Include="C:\MyVC6Project2.dsp"> /// <Platform>Win32</Platform> /// <Configuration>Debug</Configuration> /// </ProjectsToBuild> /// <!-- Uses $(Platform) and $(Configuration) for just the specified projects in the .dsw file --> /// <ProjectsToBuild Include="C:\MyVC6Project3.dsw"> /// <Projects>Project1;Project2</Projects> /// </ProjectsToBuild> /// </ItemGroup> /// <Target Name="Default"> /// <!-- Build a collection of VC6 projects --> /// <MSBuild.ExtensionPack.VisualStudio.VC6 TaskAction="Build" Projects="@(ProjectsToBuild)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class VC6 : BaseTask { private const string DefaultMSDEVPath = @"\Microsoft Visual Studio\Common\MSDev98\Bin\MSDEV.EXE"; private const string BuildTaskAction = "Build"; private const string CleanTaskAction = "Clean"; private const string RebuildTaskAction = "Rebuild"; private const string ProjectsMetadataName = "Projects"; private const string PlatformMetadataName = "Platform"; private const string ConfigurationMetadataName = "Configuration"; private const char Separator = ';'; /// <summary> /// Sets the MSDEV path. Default is [Program Files]\Microsoft Visual Studio\Common\MSDev98\Bin\MSDEV.EXE /// </summary> public string MSDEVPath { get; set; } /// <summary> /// Set to true to stop processing when a project in the Projects collection fails to compile. Default is false. /// </summary> public bool StopOnError { get; set; } /// <summary> /// Sets the .dsp/.dsw projects to build. /// </summary> /// <remarks> /// An additional Projects metadata item may be specified for each project to indicate which workspace project(s) /// to build. If none is supplied, the special-case 'ALL' project name is used to inform MSDEV to build all /// projects contained within the workspace/project. /// </remarks> [Required] public ITaskItem[] Projects { get; set; } protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } if (string.IsNullOrEmpty(this.MSDEVPath)) { string programFilePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (string.IsNullOrEmpty(programFilePath)) { this.Log.LogError("Failed to find the special folder 'ProgramFiles'"); return; } if (File.Exists(programFilePath + DefaultMSDEVPath)) { this.MSDEVPath = programFilePath + DefaultMSDEVPath; } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "MSDEV.exe was not found in the default location. Use MSDEVPath to specify it. Searched at: {0}", programFilePath + DefaultMSDEVPath)); return; } } switch (this.TaskAction) { case BuildTaskAction: case CleanTaskAction: case RebuildTaskAction: this.Build(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private void Build() { if (this.Projects == null) { this.Log.LogError("The collection passed to Projects is empty"); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Building Projects Collection: {0} projects", this.Projects.Length)); if (this.Projects.Any(project => !this.BuildProject(project) && this.StopOnError)) { this.LogTaskMessage("VC6 Task Execution Failed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]. Stopped by StopOnError set on true"); return; } this.LogTaskMessage("VC6 Task Execution Completed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]"); } private bool BuildProject(ITaskItem project) { string projectNames = project.GetMetadata(ProjectsMetadataName); if (string.IsNullOrEmpty(projectNames)) { this.Log.LogMessage(MessageImportance.Low, "No project names specified. Using 'ALL'."); projectNames = "ALL"; } else { this.Log.LogMessage(MessageImportance.Low, "Project names '{0}'", projectNames); } string platformName = project.GetMetadata(PlatformMetadataName); if (string.IsNullOrEmpty(platformName)) { this.Log.LogMessage(MessageImportance.Low, "No platform name specified. Using 'Win32'."); platformName = "Win32"; } else { this.Log.LogMessage(MessageImportance.Low, "Platform name '{0}'", platformName); } string configurationName = project.GetMetadata(ConfigurationMetadataName); if (string.IsNullOrEmpty(configurationName)) { this.Log.LogMessage(MessageImportance.Low, "No configuration name specified. Using 'Debug'."); configurationName = "Debug"; } else { this.Log.LogMessage(MessageImportance.Low, "Configuration names '{0}'", configurationName); } bool allBuildsSucceeded = true; foreach (string projectName in projectNames.Split(Separator)) { using (Process proc = new Process()) { proc.StartInfo.FileName = this.MSDEVPath; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; StringBuilder argumentsBuilder = new System.Text.StringBuilder(); argumentsBuilder.AppendFormat(CultureInfo.CurrentCulture, "\"{0}\" /OUT \"{0}.log\" /MAKE ", project.ItemSpec); argumentsBuilder.AppendFormat(CultureInfo.CurrentCulture, "\"{0} - {1} {2}\"", projectName, platformName, configurationName); if (this.TaskAction == CleanTaskAction) { argumentsBuilder.Append(" /CLEAN"); } else if (this.TaskAction == RebuildTaskAction) { argumentsBuilder.Append(" /REBUILD"); } proc.StartInfo.Arguments = argumentsBuilder.ToString(); // start the process this.LogTaskMessage("Running " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments); proc.Start(); proc.WaitForExit(); string outputStream = proc.StandardOutput.ReadToEnd(); if (outputStream.Length > 0) { this.LogTaskMessage(outputStream); } string errorStream = proc.StandardError.ReadToEnd(); if (errorStream.Length > 0) { this.Log.LogError(errorStream); } proc.WaitForExit(); if (proc.ExitCode == 0) { continue; } this.Log.LogError("Non-zero exit code from MSDEV.exe: " + proc.ExitCode); try { using (FileStream myStreamFile = new FileStream(project.ItemSpec + ".log", FileMode.Open)) { StreamReader myStream = new System.IO.StreamReader(myStreamFile); string myBuffer = myStream.ReadToEnd(); this.Log.LogError(myBuffer); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Unable to open log file: '{0}'. Exception: {1}", project.ItemSpec + ".log", ex.Message)); } allBuildsSucceeded = false; } } return allBuildsSucceeded; } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Sc.Dynamic; using NUnit.Framework; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Links; namespace Glass.Mapper.Sc.Integration.Dynamic { [TestFixture] public class DynamicItemFixture { private const string TargetPath = "/sitecore/content/Tests/Dynamic/DynamicItem/Target"; Database _db; [SetUp] public void Setup() { _db = global::Sitecore.Configuration.Factory.GetDatabase("master"); global::Sitecore.Context.Site = global::Sitecore.Sites.SiteContext.GetSite("website"); } #region INTERFACE TEST [Test] public void InterfaceTest() { //Assign Item item = _db.GetItem(TargetPath); using (new ItemEditing(item, true)) { item["DateTime"] = "20120204T150015"; item["SingleLineText"] = "some awesome dynamic content"; } dynamic d = new DynamicItem(item); IDynamicItem i = d as IDynamicItem; //Act string result = d.DateTime; string path = i.Path; //Assert Assert.AreEqual("04/02/2012 15:00:15", result); Assert.AreEqual(item.Paths.Path, path); } #endregion #region PROPERTY ContentPath [Test] public void ContentPath_ReturnsContentPath() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.ContentPath; //Assert Assert.AreEqual(item.Paths.ContentPath, result); } #endregion #region PROPERTY DisplayName [Test] public void DisplayName_ReturnsDisplayName() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.DisplayName; //Assert Assert.AreEqual(item["DisplayName"], result); } #endregion #region PROPERTY FullPath [Test] public void FullPath_ReturnsFullPath() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.FullPath; //Assert Assert.AreEqual(item.Paths.FullPath, result); } #endregion #region PROPERTY Key [Test] public void Key_ReturnsKey() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Key; //Assert Assert.AreEqual(item.Key, result); } #endregion #region PROPERTY MediaUrl [Test] public void MediaUrl_ReturnsMediaUrl() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.MediaUrl; //Assert Assert.AreEqual(Sitecore.Resources.Media.MediaManager.GetMediaUrl(new Sitecore.Data.Items.MediaItem(item)), result); } #endregion #region PROPERTY Path [Test] public void Path_ReturnsPath() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Path; //Assert Assert.AreEqual(item.Paths.Path, result); } #endregion #region PROPERTY TemplateId [Test] public void TemplateId_ReturnsTemplateId() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.TemplateId; //Assert Assert.AreEqual(item.TemplateID.Guid, result); } #endregion #region PROPERTY TemplateName [Test] public void TemplateName_ReturnsTemplateName() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.TemplateName; //Assert Assert.AreEqual(item.TemplateName, result); } #endregion #region PROPERTY Url [Test] public void Url_ReturnsUrl() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Url; //Assert Assert.AreEqual(LinkManager.GetItemUrl(item), result); } #endregion #region PROPERTY Version [Test] public void Version_ReturnsVersion() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Version; //Assert Assert.AreEqual(item.Version.Number, result); } #endregion #region PROPERTY Name [Test] public void Name_ReturnsName() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Name; //Assert Assert.AreEqual(item.Name, result); } #endregion #region PROPERTY Language [Test] public void Language_ReturnsLanguage() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Language; //Assert Assert.AreEqual(item.Language, result); } #endregion #region PROPERTY Language [Test] public void Language_ReturnsContentPath() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.Language; //Assert Assert.AreEqual(item.Language, result); } #endregion #region PROPERTY BaseTemplateIds [Test] public void BaseTemplateIds_ReturnsBaseTemplateIds() { //Arrange //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result = d.BaseTemplateIds as IEnumerable<Guid>; //Assert Assert.Greater(result.Count(), 10); } #endregion #region [Test] public void DynamicFields_ReturnsFields() { //Assign Item item = _db.GetItem(TargetPath); using (new ItemEditing(item, true)) { item["DateTime"] = "20120204T150015"; item["SingleLineText"] = "some awesome dynamic content"; } dynamic d = new DynamicItem(item); //Act string dateTime = d.DateTime; string text = d.SingleLineText; //Assert Assert.AreEqual("some awesome dynamic content", text); Assert.AreEqual("04/02/2012 15:00:15", dateTime); } [Test] public void DynamicInfo_ReturnsItemInfo() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act string path = d.Path; string name = d.Name; //Assert Assert.AreEqual(TargetPath, path); Assert.AreEqual("Target", name); } [Test] public void DynamicParent_ReturnsParent() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var parent = d.Parent; string path = parent.Path; //Assert Assert.AreEqual(item.Parent.Paths.FullPath, path); } [Test] public void DynamicParent_ReturnsChildren() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var children = d.Children; //Assert Assert.AreEqual(3, children.Count()); foreach (var child in d.Children) { string path = child.Path; Assert.IsTrue(path.StartsWith(TargetPath)); } } [Test] public void DynamicParent_ReturnsLastChild() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var children = d.Children; //Assert Assert.AreEqual(3, children.Count()); var child = d.Children.Last(); string path = child.Path; Assert.IsTrue(path.StartsWith(TargetPath)); } #endregion } public interface IDynamicTitle : IDynamicItem { string Title { get; set; } } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdManager.Lib; using Google.Api.Ads.AdManager.Util.v202202; using Google.Api.Ads.AdManager.v202202; using System; using System.Collections.Generic; using System.Text; namespace Google.Api.Ads.AdManager.Examples.CSharp.v202202 { /// <summary> /// This code example retrieves a previously created ad units and creates /// a tree. /// </summary> public class GetInventoryTree : SampleBase { /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example retrieves a previously created ad units and creates a tree."; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> public static void Main() { GetInventoryTree codeExample = new GetInventoryTree(); Console.WriteLine(codeExample.Description); codeExample.Run(new AdManagerUser()); } /// <summary> /// Run the code example. /// </summary> public void Run(AdManagerUser user) { try { // Get all ad units. AdUnit[] allAdUnits = GetAllAdUnits(user); // Find the root ad unit. rootAdUnit can also be set to child unit to // only build and display a portion of the tree. // i.e. AdUnit adUnit = // inventoryService.getAdUnit("INSERT_AD_UNIT_HERE") AdUnit rootAdUnit = FindRootAdUnit(user); if (rootAdUnit == null) { Console.WriteLine("Could not build tree. No root ad unit found."); } else { BuildAndDisplayAdUnitTree(rootAdUnit, allAdUnits); } } catch (Exception e) { Console.WriteLine("Failed to get ad unit. Exception says \"{0}\"", e.Message); } } /// <summary> /// Gets all ad units for this user. /// </summary> /// <returns>All ad units for this user.</returns> private static AdUnit[] GetAllAdUnits(AdManagerUser user) { using (InventoryService inventoryService = user.GetService<InventoryService>()) { // Create list to hold all ad units. List<AdUnit> adUnits = new List<AdUnit>(); // Create a statement to get all ad units. StatementBuilder statementBuilder = new StatementBuilder().OrderBy("id ASC") .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT); // Set default for page. AdUnitPage page = new AdUnitPage(); do { // Get ad units by statement. page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); if (page.results != null) { adUnits.AddRange(page.results); } statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.GetOffset() < page.totalResultSetSize); return adUnits.ToArray(); } } /// <summary> /// Finds the root ad unit for the user. /// </summary> /// <returns>The ad unit representing the root ad unit or null if one /// is not found.</returns> private static AdUnit FindRootAdUnit(AdManagerUser user) { using (InventoryService inventoryService = user.GetService<InventoryService>()) { // Create a statement to only select the root ad unit. StatementBuilder statementBuilder = new StatementBuilder() .Where("parentId IS NULL") .OrderBy("id ASC") .Limit(1); // Get ad units by statement. AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.ToStatement()); if (page.results != null) { return page.results[0]; } return null; } } /// <summary> /// Builds and displays an ad unit tree from an array of ad units underneath /// the root ad unit. /// </summary> /// <param name="root">The root ad unit to build the tree under.</param> /// <param name="units">The array of ad units.</param> private static void BuildAndDisplayAdUnitTree(AdUnit root, AdUnit[] units) { Dictionary<String, List<AdUnit>> treeMap = new Dictionary<String, List<AdUnit>>(); foreach (AdUnit unit in units) { if (unit.parentId != null) { if (treeMap.ContainsKey(unit.parentId) == false) { treeMap.Add(unit.parentId, new List<AdUnit>()); } treeMap[unit.parentId].Add(unit); } } if (root != null) { DisplayInventoryTree(root, treeMap); } else { Console.WriteLine("No root unit found."); } } /// <summary> /// Displays the ad unit tree beginning at the root ad unit. /// </summary> /// <param name="root">The root ad unit</param> /// <param name="treeMap">The map of id to list of ad units</param> private static void DisplayInventoryTree(AdUnit root, Dictionary<String, List<AdUnit>> treeMap) { DisplayInventoryTreeHelper(root, treeMap, 0); } /// <summary> /// Helper for displaying inventory units. /// </summary> /// <param name="root">The root inventory unit.</param> /// <param name="treeMap">The map of id to List of inventory units.</param> /// <param name="depth">The depth the tree has reached.</param> private static void DisplayInventoryTreeHelper(AdUnit root, Dictionary<String, List<AdUnit>> treeMap, int depth) { Console.WriteLine(GenerateTab(depth) + root.name + " (" + root.id + ")"); if (treeMap.ContainsKey(root.id)) { foreach (AdUnit child in treeMap[root.id]) { DisplayInventoryTreeHelper(child, treeMap, depth + 1); } } } /// <summary> /// Generates a String of tabs to represent branching to children. /// </summary> /// <param name="depth">A depth from 0 to max(depth).</param> /// <returns>A string to insert in front of the root unit.</returns> private static String GenerateTab(int depth) { StringBuilder builder = new StringBuilder(); if (depth != 0) { builder.Append(" "); } for (int i = 1; i < depth; i++) { builder.Append("| "); } builder.Append("+--"); return builder.ToString(); } } }
using System; using System.IO; using System.Collections.Generic; namespace Monoamp.Common.system.io { public abstract class AByteArray { protected Stream stream; public int Position{ get; private set; } public int PositionBit{ get; private set; } public int Length{ get{ return ( int )stream.Length - start / 8; } } public int LengthBit{ get{ return ( int )stream.Length * 8 - start; } } private int start; public bool AddByteArray( byte[] bytes ) { stream.Seek( Length + start / 8, SeekOrigin.Begin ); stream.Write( bytes, 0, bytes.Length ); stream.Seek( Position + start / 8, SeekOrigin.Begin ); return true; } public void RemoveRange( int range ) { start += range * 8; if( PositionBit > 0 ) { if( PositionBit > range * 8 ) { SubBitPosition( range * 8 ); } else { SetBitPosition( 0 ); } } } protected AByteArray( Stream aStream ) { stream = aStream; start = 0; Position = 0; PositionBit = 0; } public string GetName() { FileStream lFileStream = ( FileStream )stream; return lFileStream.Name; } public void Open() { stream = new FileStream( GetName(), FileMode.Open, FileAccess.Read ); } public void Close() { stream.Close(); } public int GetBitPositionInByte() { return PositionBit - Position * 8; } public void SetPosition( int aPosition ) { Position = aPosition; PositionBit = Position * 8; stream.Seek( Position + start / 8, SeekOrigin.Begin ); } public void AddPosition( int aOffset ) { SetPosition( Position + aOffset ); } public void SubPosition( int aOffset ) { SetPosition( Position - aOffset ); } public void SetBitPosition( int aPositionBit ) { Position = aPositionBit / 8; PositionBit = aPositionBit; stream.Seek( Position + start / 8, SeekOrigin.Begin ); } public void AddBitPosition( int aOffsetBit ) { SetBitPosition( PositionBit + aOffsetBit ); } public void SubBitPosition( int aOffsetBit ) { SetBitPosition( PositionBit - aOffsetBit ); } public Byte ReadByte() { Position++; PositionBit += 8; return ( Byte )stream.ReadByte(); } public Byte ReadByte( int aPosition ) { stream.Seek( aPosition, SeekOrigin.Begin ); return ( Byte )stream.ReadByte(); } public Byte[] ReadBytes( int aLength ) { byte[] lDataArray = new byte[aLength]; stream.Read( lDataArray, 0, aLength ); Position += ( int )aLength; PositionBit = ( int )Position * 8; return lDataArray; } public void ReadBytes( Byte[] aDataArray ) { stream.Read( aDataArray, 0, aDataArray.Length ); Position += ( int )aDataArray.Length; PositionBit = ( int )Position * 8; } public Byte[] ReadBytes( UInt32 aLength ) { return ReadBytes( ( int )aLength ); } public string ReadString( int length ) { string lString = System.Text.Encoding.ASCII.GetString( ReadBytes( length ) ); return lString.Split( '\0' )[0]; } public string ReadShiftJisString( int length ) { return System.Text.Encoding.GetEncoding( "shift_jis" ).GetString( ReadBytes( length ) ); } public Byte ReadUByte() { return ( Byte )ReadByte(); } public abstract UInt16 ReadUInt16(); public abstract UInt32 ReadUInt24(); public abstract UInt32 ReadUInt32(); public abstract UInt64 ReadUInt64(); public SByte ReadSByte() { return ( SByte )ReadByte(); } public abstract Int16 ReadInt16(); public abstract Int32 ReadInt24(); public abstract Int32 ReadInt32(); public abstract Int64 ReadInt64(); public abstract Single ReadSingle(); public abstract Double ReadDouble(); public Double ReadExtendedFloatPoint() { byte[] lDataRead = ReadBytes( 10 ); byte[] lDataArray = new byte[8]; lDataArray[7] = lDataRead[0]; lDataArray[6] = ( byte )( ( ( lDataRead[1] << 4 ) & 0xF0 ) | ( ( lDataRead[2] >> 3 ) & 0x0F ) ); lDataArray[5] = ( byte )( ( ( lDataRead[2] << 5 ) & 0xD0 ) | ( ( lDataRead[3] >> 3 ) & 0x1F ) ); lDataArray[4] = ( byte )( ( ( lDataRead[3] << 5 ) & 0xD0 ) | ( ( lDataRead[4] >> 3 ) & 0x1F ) ); lDataArray[3] = ( byte )( ( ( lDataRead[4] << 5 ) & 0xD0 ) | ( ( lDataRead[5] >> 3 ) & 0x1F ) ); lDataArray[2] = ( byte )( ( ( lDataRead[5] << 5 ) & 0xD0 ) | ( ( lDataRead[6] >> 3 ) & 0x1F ) ); lDataArray[1] = ( byte )( ( ( lDataRead[6] << 5 ) & 0xD0 ) | ( ( lDataRead[7] >> 3 ) & 0x1F ) ); lDataArray[0] = ( byte )( ( ( lDataRead[7] << 5 ) & 0xD0 ) | ( ( lDataRead[8] >> 3 ) & 0x1F ) ); /* lDataArray[0] = lDataRead[0]; lDataArray[1] = ( byte )( ( ( lDataRead[1] << 4 ) & 0xF0 ) | ( ( lDataRead[2] >> 3 ) & 0x0F ) ); lDataArray[2] = ( byte )( ( ( lDataRead[2] << 5 ) & 0xD0 ) | ( ( lDataRead[3] >> 3 ) & 0x1F ) ); lDataArray[3] = ( byte )( ( ( lDataRead[3] << 5 ) & 0xD0 ) | ( ( lDataRead[4] >> 3 ) & 0x1F ) ); lDataArray[4] = ( byte )( ( ( lDataRead[4] << 5 ) & 0xD0 ) | ( ( lDataRead[5] >> 3 ) & 0x1F ) ); lDataArray[5] = ( byte )( ( ( lDataRead[5] << 5 ) & 0xD0 ) | ( ( lDataRead[6] >> 3 ) & 0x1F ) ); lDataArray[6] = ( byte )( ( ( lDataRead[6] << 5 ) & 0xD0 ) | ( ( lDataRead[7] >> 3 ) & 0x1F ) ); lDataArray[7] = ( byte )( ( ( lDataRead[7] << 5 ) & 0xD0 ) | ( ( lDataRead[8] >> 3 ) & 0x1F ) ); */ return BitConverter.ToDouble( lDataArray, 0 ); } public void WriteBytes( Byte[] data ) { for( int i = 0; i < data.Length; i++ ) { WriteUByte( data[i] ); } } public void WriteBytes( AByteArray aByteArray, int aPosition, UInt32 aLength ) { aByteArray.SetPosition( aPosition ); Byte[] lDataArray = aByteArray.ReadBytes( aLength ); for( int i = 0; i < lDataArray.Length; i++ ) { WriteUByte( lDataArray[i] ); } } public void WriteUByte( Byte data ) { //dataArray[Position] = data; stream.Seek( Position, SeekOrigin.Begin ); stream.WriteByte( data ); Position++; PositionBit = Position * 8; } public void WriteUInt16( UInt16 data ) { WriteBytes( BitConverter.GetBytes( data ) ); } public void WriteUInt24( UInt16 data ) { } public void WriteUInt32( UInt32 data ) { WriteBytes( BitConverter.GetBytes( data ) ); } public void WriteString( string data ) { for( int i = 0; i < data.Length; i++ ) { WriteUByte( ( byte )data[i] ); } } public abstract Byte ReadBitsAsByte( int aLength ); public abstract UInt16 ReadBitsAsUInt16( int aLength ); public abstract UInt32 ReadBitsAsUInt32( int aLength ); public UInt16 ReadBitsAsUInt16Little( int aLength ) { return ( UInt16 )System.Net.IPAddress.HostToNetworkOrder( ( Int16 )ReadBitsAsUInt16( aLength ) ); } public UInt32 ReadBitsAsUInt32Little( int aLength ) { return ( ( UInt32 )System.Net.IPAddress.HostToNetworkOrder( ( Int32 )ReadBitsAsUInt32( aLength ) ) >> 8 ); } public int Find( Byte[] aPatternArray ) { for( int i = 0; i < stream.Length - aPatternArray.Length; i++ ) { for( int j = 0; j < aPatternArray.Length; j++ ) { if( ReadByte( ( int )( Position + i + j ) ) != aPatternArray[j] ) { break; } if( j == aPatternArray.Length - 1 ) { return Position + i; } } } return -1; } public int Find( Byte[] aPatternArray, int aCount ) { for( int i = 0; i < stream.Length - aPatternArray.Length && i <= aCount; i++ ) { for( int j = 0; j < aPatternArray.Length; j++ ) { if( ReadByte( ( int )( Position + i + j ) ) != aPatternArray[j] ) { break; } if( j == aPatternArray.Length - 1 ) { return Position + i; } } } return -1; } } }
/* * 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/error_reason.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/error_reason.proto</summary> public static partial class ErrorReasonReflection { #region Descriptor /// <summary>File descriptor for google/api/error_reason.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ErrorReasonReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch1nb29nbGUvYXBpL2Vycm9yX3JlYXNvbi5wcm90bxIKZ29vZ2xlLmFwaSrE", "BAoLRXJyb3JSZWFzb24SHAoYRVJST1JfUkVBU09OX1VOU1BFQ0lGSUVEEAAS", "FAoQU0VSVklDRV9ESVNBQkxFRBABEhQKEEJJTExJTkdfRElTQUJMRUQQAhIT", "Cg9BUElfS0VZX0lOVkFMSUQQAxIbChdBUElfS0VZX1NFUlZJQ0VfQkxPQ0tF", "RBAEEiEKHUFQSV9LRVlfSFRUUF9SRUZFUlJFUl9CTE9DS0VEEAcSHgoaQVBJ", "X0tFWV9JUF9BRERSRVNTX0JMT0NLRUQQCBIfChtBUElfS0VZX0FORFJPSURf", "QVBQX0JMT0NLRUQQCRIbChdBUElfS0VZX0lPU19BUFBfQkxPQ0tFRBANEhcK", "E1JBVEVfTElNSVRfRVhDRUVERUQQBRIbChdSRVNPVVJDRV9RVU9UQV9FWENF", "RURFRBAGEiAKHExPQ0FUSU9OX1RBWF9QT0xJQ1lfVklPTEFURUQQChIXChNV", "U0VSX1BST0pFQ1RfREVOSUVEEAsSFgoSQ09OU1VNRVJfU1VTUEVOREVEEAwS", "FAoQQ09OU1VNRVJfSU5WQUxJRBAOEhwKGFNFQ1VSSVRZX1BPTElDWV9WSU9M", "QVRFRBAPEhgKFEFDQ0VTU19UT0tFTl9FWFBJUkVEEBASIwofQUNDRVNTX1RP", "S0VOX1NDT1BFX0lOU1VGRklDSUVOVBAREhkKFUFDQ09VTlRfU1RBVEVfSU5W", "QUxJRBASEiEKHUFDQ0VTU19UT0tFTl9UWVBFX1VOU1VQUE9SVEVEEBNCcAoO", "Y29tLmdvb2dsZS5hcGlCEEVycm9yUmVhc29uUHJvdG9QAVpDZ29vZ2xlLmdv", "bGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvZXJyb3JfcmVhc29u", "O2Vycm9yX3JlYXNvbqICBEdBUEliBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Api.ErrorReason), }, null, null)); } #endregion } #region Enums /// <summary> /// Defines the supported values for `google.rpc.ErrorInfo.reason` for the /// `googleapis.com` error domain. This error domain is reserved for [Service /// Infrastructure](https://cloud.google.com/service-infrastructure/docs/overview). /// For each error info of this domain, the metadata key "service" refers to the /// logical identifier of an API service, such as "pubsub.googleapis.com". The /// "consumer" refers to the entity that consumes an API Service. It typically is /// a Google project that owns the client application or the server resource, /// such as "projects/123". Other metadata keys are specific to each error /// reason. For more information, see the definition of the specific error /// reason. /// </summary> public enum ErrorReason { /// <summary> /// Do not use this default value. /// </summary> [pbr::OriginalName("ERROR_REASON_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The request is calling a disabled service for a consumer. /// /// Example of an ErrorInfo when the consumer "projects/123" contacting /// "pubsub.googleapis.com" service which is disabled: /// /// { "reason": "SERVICE_DISABLED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "pubsub.googleapis.com" /// } /// } /// /// This response indicates the "pubsub.googleapis.com" has been disabled in /// "projects/123". /// </summary> [pbr::OriginalName("SERVICE_DISABLED")] ServiceDisabled = 1, /// <summary> /// The request whose associated billing account is disabled. /// /// Example of an ErrorInfo when the consumer "projects/123" fails to contact /// "pubsub.googleapis.com" service because the associated billing account is /// disabled: /// /// { "reason": "BILLING_DISABLED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "pubsub.googleapis.com" /// } /// } /// /// This response indicates the billing account associated has been disabled. /// </summary> [pbr::OriginalName("BILLING_DISABLED")] BillingDisabled = 2, /// <summary> /// The request is denied because the provided [API /// key](https://cloud.google.com/docs/authentication/api-keys) is invalid. It /// may be in a bad format, cannot be found, or has been expired). /// /// Example of an ErrorInfo when the request is contacting /// "storage.googleapis.com" service with an invalid API key: /// /// { "reason": "API_KEY_INVALID", /// "domain": "googleapis.com", /// "metadata": { /// "service": "storage.googleapis.com", /// } /// } /// </summary> [pbr::OriginalName("API_KEY_INVALID")] ApiKeyInvalid = 3, /// <summary> /// The request is denied because it violates [API key API /// restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_api_restrictions). /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call the /// "storage.googleapis.com" service because this service is restricted in the /// API key: /// /// { "reason": "API_KEY_SERVICE_BLOCKED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("API_KEY_SERVICE_BLOCKED")] ApiKeyServiceBlocked = 4, /// <summary> /// The request is denied because it violates [API key HTTP /// restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_http_restrictions). /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call /// "storage.googleapis.com" service because the http referrer of the request /// violates API key HTTP restrictions: /// /// { "reason": "API_KEY_HTTP_REFERRER_BLOCKED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com", /// } /// } /// </summary> [pbr::OriginalName("API_KEY_HTTP_REFERRER_BLOCKED")] ApiKeyHttpReferrerBlocked = 7, /// <summary> /// The request is denied because it violates [API key IP address /// restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call /// "storage.googleapis.com" service because the caller IP of the request /// violates API key IP address restrictions: /// /// { "reason": "API_KEY_IP_ADDRESS_BLOCKED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com", /// } /// } /// </summary> [pbr::OriginalName("API_KEY_IP_ADDRESS_BLOCKED")] ApiKeyIpAddressBlocked = 8, /// <summary> /// The request is denied because it violates [API key Android application /// restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call /// "storage.googleapis.com" service because the request from the Android apps /// violates the API key Android application restrictions: /// /// { "reason": "API_KEY_ANDROID_APP_BLOCKED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("API_KEY_ANDROID_APP_BLOCKED")] ApiKeyAndroidAppBlocked = 9, /// <summary> /// The request is denied because it violates [API key iOS application /// restrictions](https://cloud.google.com/docs/authentication/api-keys#adding_application_restrictions). /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call /// "storage.googleapis.com" service because the request from the iOS apps /// violates the API key iOS application restrictions: /// /// { "reason": "API_KEY_IOS_APP_BLOCKED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("API_KEY_IOS_APP_BLOCKED")] ApiKeyIosAppBlocked = 13, /// <summary> /// The request is denied because there is not enough rate quota for the /// consumer. /// /// Example of an ErrorInfo when the consumer "projects/123" fails to contact /// "pubsub.googleapis.com" service because consumer's rate quota usage has /// reached the maximum value set for the quota limit /// "ReadsPerMinutePerProject" on the quota metric /// "pubsub.googleapis.com/read_requests": /// /// { "reason": "RATE_LIMIT_EXCEEDED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "pubsub.googleapis.com", /// "quota_metric": "pubsub.googleapis.com/read_requests", /// "quota_limit": "ReadsPerMinutePerProject" /// } /// } /// /// Example of an ErrorInfo when the consumer "projects/123" checks quota on /// the service "dataflow.googleapis.com" and hits the organization quota /// limit "DefaultRequestsPerMinutePerOrganization" on the metric /// "dataflow.googleapis.com/default_requests". /// /// { "reason": "RATE_LIMIT_EXCEEDED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "dataflow.googleapis.com", /// "quota_metric": "dataflow.googleapis.com/default_requests", /// "quota_limit": "DefaultRequestsPerMinutePerOrganization" /// } /// } /// </summary> [pbr::OriginalName("RATE_LIMIT_EXCEEDED")] RateLimitExceeded = 5, /// <summary> /// The request is denied because there is not enough resource quota for the /// consumer. /// /// Example of an ErrorInfo when the consumer "projects/123" fails to contact /// "compute.googleapis.com" service because consumer's resource quota usage /// has reached the maximum value set for the quota limit "VMsPerProject" /// on the quota metric "compute.googleapis.com/vms": /// /// { "reason": "RESOURCE_QUOTA_EXCEEDED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "compute.googleapis.com", /// "quota_metric": "compute.googleapis.com/vms", /// "quota_limit": "VMsPerProject" /// } /// } /// /// Example of an ErrorInfo when the consumer "projects/123" checks resource /// quota on the service "dataflow.googleapis.com" and hits the organization /// quota limit "jobs-per-organization" on the metric /// "dataflow.googleapis.com/job_count". /// /// { "reason": "RESOURCE_QUOTA_EXCEEDED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "dataflow.googleapis.com", /// "quota_metric": "dataflow.googleapis.com/job_count", /// "quota_limit": "jobs-per-organization" /// } /// } /// </summary> [pbr::OriginalName("RESOURCE_QUOTA_EXCEEDED")] ResourceQuotaExceeded = 6, /// <summary> /// The request whose associated billing account address is in a tax restricted /// location, violates the local tax restrictions when creating resources in /// the restricted region. /// /// Example of an ErrorInfo when creating the Cloud Storage Bucket in the /// container "projects/123" under a tax restricted region /// "locations/asia-northeast3": /// /// { "reason": "LOCATION_TAX_POLICY_VIOLATED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com", /// "location": "locations/asia-northeast3" /// } /// } /// /// This response indicates creating the Cloud Storage Bucket in /// "locations/asia-northeast3" violates the location tax restriction. /// </summary> [pbr::OriginalName("LOCATION_TAX_POLICY_VIOLATED")] LocationTaxPolicyViolated = 10, /// <summary> /// The request is denied because the caller does not have required permission /// on the user project "projects/123" or the user project is invalid. For more /// information, check the [userProject System /// Parameters](https://cloud.google.com/apis/docs/system-parameters). /// /// Example of an ErrorInfo when the caller is calling Cloud Storage service /// with insufficient permissions on the user project: /// /// { "reason": "USER_PROJECT_DENIED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("USER_PROJECT_DENIED")] UserProjectDenied = 11, /// <summary> /// The request is denied because the consumer "projects/123" is suspended due /// to Terms of Service(Tos) violations. Check [Project suspension /// guidelines](https://cloud.google.com/resource-manager/docs/project-suspension-guidelines) /// for more information. /// /// Example of an ErrorInfo when calling Cloud Storage service with the /// suspended consumer "projects/123": /// /// { "reason": "CONSUMER_SUSPENDED", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("CONSUMER_SUSPENDED")] ConsumerSuspended = 12, /// <summary> /// The request is denied because the associated consumer is invalid. It may be /// in a bad format, cannot be found, or have been deleted. /// /// Example of an ErrorInfo when calling Cloud Storage service with the /// invalid consumer "projects/123": /// /// { "reason": "CONSUMER_INVALID", /// "domain": "googleapis.com", /// "metadata": { /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("CONSUMER_INVALID")] ConsumerInvalid = 14, /// <summary> /// The request is denied because it violates [VPC Service /// Controls](https://cloud.google.com/vpc-service-controls/docs/overview). /// The 'uid' field is a random generated identifier that customer can use it /// to search the audit log for a request rejected by VPC Service Controls. For /// more information, please refer [VPC Service Controls /// Troubleshooting](https://cloud.google.com/vpc-service-controls/docs/troubleshooting#unique-id) /// /// Example of an ErrorInfo when the consumer "projects/123" fails to call /// Cloud Storage service because the request is prohibited by the VPC Service /// Controls. /// /// { "reason": "SECURITY_POLICY_VIOLATED", /// "domain": "googleapis.com", /// "metadata": { /// "uid": "123456789abcde", /// "consumer": "projects/123", /// "service": "storage.googleapis.com" /// } /// } /// </summary> [pbr::OriginalName("SECURITY_POLICY_VIOLATED")] SecurityPolicyViolated = 15, /// <summary> /// The request is denied because the provided access token has expired. /// /// Example of an ErrorInfo when the request is calling Cloud Storage service /// with an expired access token: /// /// { "reason": "ACCESS_TOKEN_EXPIRED", /// "domain": "googleapis.com", /// "metadata": { /// "service": "storage.googleapis.com", /// "method": "google.storage.v1.Storage.GetObject" /// } /// } /// </summary> [pbr::OriginalName("ACCESS_TOKEN_EXPIRED")] AccessTokenExpired = 16, /// <summary> /// The request is denied because the provided access token doesn't have at /// least one of the acceptable scopes required for the API. Please check /// [OAuth 2.0 Scopes for Google /// APIs](https://developers.google.com/identity/protocols/oauth2/scopes) for /// the list of the OAuth 2.0 scopes that you might need to request to access /// the API. /// /// Example of an ErrorInfo when the request is calling Cloud Storage service /// with an access token that is missing required scopes: /// /// { "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", /// "domain": "googleapis.com", /// "metadata": { /// "service": "storage.googleapis.com", /// "method": "google.storage.v1.Storage.GetObject" /// } /// } /// </summary> [pbr::OriginalName("ACCESS_TOKEN_SCOPE_INSUFFICIENT")] AccessTokenScopeInsufficient = 17, /// <summary> /// The request is denied because the account associated with the provided /// access token is in an invalid state, such as disabled or deleted. /// For more information, see https://cloud.google.com/docs/authentication. /// /// Warning: For privacy reasons, the server may not be able to disclose the /// email address for some accounts. The client MUST NOT depend on the /// availability of the `email` attribute. /// /// Example of an ErrorInfo when the request is to the Cloud Storage API with /// an access token that is associated with a disabled or deleted [service /// account](http://cloud/iam/docs/service-accounts): /// /// { "reason": "ACCOUNT_STATE_INVALID", /// "domain": "googleapis.com", /// "metadata": { /// "service": "storage.googleapis.com", /// "method": "google.storage.v1.Storage.GetObject", /// "email": "user@123.iam.gserviceaccount.com" /// } /// } /// </summary> [pbr::OriginalName("ACCOUNT_STATE_INVALID")] AccountStateInvalid = 18, /// <summary> /// The request is denied because the type of the provided access token is not /// supported by the API being called. /// /// Example of an ErrorInfo when the request is to the Cloud Storage API with /// an unsupported token type. /// /// { "reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED", /// "domain": "googleapis.com", /// "metadata": { /// "service": "storage.googleapis.com", /// "method": "google.storage.v1.Storage.GetObject" /// } /// } /// </summary> [pbr::OriginalName("ACCESS_TOKEN_TYPE_UNSUPPORTED")] AccessTokenTypeUnsupported = 19, } #endregion } #endregion Designer generated code
// <copyright file="Sorting.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2015 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; namespace MathNet.Numerics { /// <summary> /// Sorting algorithms for single, tuple and triple lists. /// </summary> public static class Sorting { /// <summary> /// Sort a list of keys, in place using the quick sort algorithm using the quick sort algorithm. /// </summary> /// <typeparam name="T">The type of elements in the key list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<T>(IList<T> keys, IComparer<T> comparer = null) { int count = keys.Count; if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<T>.Default; } if (count == 2) { if (comparer.Compare(keys[0], keys[1]) > 0) { Swap(keys, 0, 1); } return; } // insertion sort if (count <= 10) { for (int i = 1; i < count; i++) { var key = keys[i]; int j = i - 1; while (j >= 0 && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = key; } return; } // array case var keysArray = keys as T[]; if (null != keysArray) { Array.Sort(keysArray, comparer); return; } // generic list case var keysList = keys as List<T>; if (null != keysList) { keysList.Sort(comparer); return; } // local sort implementation QuickSort(keys, comparer, 0, count - 1); } /// <summary> /// Sort a list of keys and items with respect to the keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="TKey">The type of elements in the key list.</typeparam> /// <typeparam name="TItem">The type of elements in the item list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="items">List to permute the same way as the key list.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<TKey, TItem>(IList<TKey> keys, IList<TItem> items, IComparer<TKey> comparer = null) { int count = keys.Count; if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<TKey>.Default; } if (count == 2) { if (comparer.Compare(keys[0], keys[1]) > 0) { Swap(keys, 0, 1); Swap(items, 0, 1); } return; } // insertion sort if (count <= 10) { for (int i = 1; i < count; i++) { var key = keys[i]; var item = items[i]; int j = i - 1; while (j >= 0 && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; items[j + 1] = items[j]; j--; } keys[j + 1] = key; items[j + 1] = item; } return; } #if !PORTABLE // array case var keysArray = keys as TKey[]; var itemsArray = items as TItem[]; if ((null != keysArray) && (null != itemsArray)) { Array.Sort(keysArray, itemsArray, comparer); return; } #endif // local sort implementation QuickSort(keys, items, comparer, 0, count - 1); } /// <summary> /// Sort a list of keys, items1 and items2 with respect to the keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="TKey">The type of elements in the key list.</typeparam> /// <typeparam name="TItem1">The type of elements in the first item list.</typeparam> /// <typeparam name="TItem2">The type of elements in the second item list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="items1">First list to permute the same way as the key list.</param> /// <param name="items2">Second list to permute the same way as the key list.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<TKey, TItem1, TItem2>(IList<TKey> keys, IList<TItem1> items1, IList<TItem2> items2, IComparer<TKey> comparer = null) { int count = keys.Count; if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<TKey>.Default; } if (count == 2) { if (comparer.Compare(keys[0], keys[1]) > 0) { Swap(keys, 0, 1); Swap(items1, 0, 1); Swap(items2, 0, 1); } return; } // insertion sort if (count <= 10) { for (int i = 1; i < count; i++) { var key = keys[i]; var item1 = items1[i]; var item2 = items2[i]; int j = i - 1; while (j >= 0 && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; items1[j + 1] = items1[j]; items2[j + 1] = items2[j]; j--; } keys[j + 1] = key; items1[j + 1] = item1; items2[j + 1] = item2; } return; } // local sort implementation QuickSort(keys, items1, items2, comparer, 0, count - 1); } /// <summary> /// Sort a range of a list of keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="T">The type of element in the list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="index">The zero-based starting index of the range to sort.</param> /// <param name="count">The length of the range to sort.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<T>(IList<T> keys, int index, int count, IComparer<T> comparer = null) { if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0 || index + count > keys.Count) { throw new ArgumentOutOfRangeException("count"); } if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<T>.Default; } if (count == 2) { if (comparer.Compare(keys[index], keys[index + 1]) > 0) { Swap(keys, index, index + 1); } return; } // insertion sort if (count <= 10) { int to = index + count; for (int i = index + 1; i < to; i++) { var key = keys[i]; int j = i - 1; while (j >= index && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; j--; } keys[j + 1] = key; } return; } // array case var keysArray = keys as T[]; if (null != keysArray) { Array.Sort(keysArray, index, count, comparer); return; } // generic list case var keysList = keys as List<T>; if (null != keysList) { keysList.Sort(index, count, comparer); return; } // fall back: local sort implementation QuickSort(keys, comparer, index, count - 1); } /// <summary> /// Sort a list of keys and items with respect to the keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="TKey">The type of elements in the key list.</typeparam> /// <typeparam name="TItem">The type of elements in the item list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="items">List to permute the same way as the key list.</param> /// <param name="index">The zero-based starting index of the range to sort.</param> /// <param name="count">The length of the range to sort.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<TKey, TItem>(IList<TKey> keys, IList<TItem> items, int index, int count, IComparer<TKey> comparer = null) { if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0 || index + count > keys.Count) { throw new ArgumentOutOfRangeException("count"); } if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<TKey>.Default; } if (count == 2) { if (comparer.Compare(keys[index], keys[index + 1]) > 0) { Swap(keys, index, index + 1); Swap(items, index, index + 1); } return; } // insertion sort if (count <= 10) { int to = index + count; for (int i = index + 1; i < to; i++) { var key = keys[i]; var item = items[i]; int j = i - 1; while (j >= index && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; items[j + 1] = items[j]; j--; } keys[j + 1] = key; items[j + 1] = item; } return; } #if !PORTABLE // array case var keysArray = keys as TKey[]; var itemsArray = items as TItem[]; if ((null != keysArray) && (null != itemsArray)) { Array.Sort(keysArray, itemsArray, index, count, comparer); return; } #endif // fall back: local sort implementation QuickSort(keys, items, comparer, index, count - 1); } /// <summary> /// Sort a list of keys, items1 and items2 with respect to the keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="TKey">The type of elements in the key list.</typeparam> /// <typeparam name="TItem1">The type of elements in the first item list.</typeparam> /// <typeparam name="TItem2">The type of elements in the second item list.</typeparam> /// <param name="keys">List to sort.</param> /// <param name="items1">First list to permute the same way as the key list.</param> /// <param name="items2">Second list to permute the same way as the key list.</param> /// <param name="index">The zero-based starting index of the range to sort.</param> /// <param name="count">The length of the range to sort.</param> /// <param name="comparer">Comparison, defining the sort order.</param> public static void Sort<TKey, TItem1, TItem2>(IList<TKey> keys, IList<TItem1> items1, IList<TItem2> items2, int index, int count, IComparer<TKey> comparer = null) { if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0 || index + count > keys.Count) { throw new ArgumentOutOfRangeException("count"); } if (count <= 1) { return; } if (null == comparer) { comparer = Comparer<TKey>.Default; } if (count == 2) { if (comparer.Compare(keys[index], keys[index + 1]) > 0) { Swap(keys, index, index + 1); Swap(items1, index, index + 1); Swap(items2, index, index + 1); } return; } // insertion sort if (count <= 10) { int to = index + count; for (int i = index + 1; i < to; i++) { var key = keys[i]; var item1 = items1[i]; var item2 = items2[i]; int j = i - 1; while (j >= index && comparer.Compare(keys[j], key) > 0) { keys[j + 1] = keys[j]; items1[j + 1] = items1[j]; items2[j + 1] = items2[j]; j--; } keys[j + 1] = key; items1[j + 1] = item1; items2[j + 1] = item2; } return; } // fall back: local sort implementation QuickSort(keys, items1, items2, comparer, index, count - 1); } /// <summary> /// Sort a list of keys and items with respect to the keys, in place using the quick sort algorithm. /// </summary> /// <typeparam name="T1">The type of elements in the primary list.</typeparam> /// <typeparam name="T2">The type of elements in the secondary list.</typeparam> /// <param name="primary">List to sort.</param> /// <param name="secondary">List to sort on duplicate primary items, and permute the same way as the key list.</param> /// <param name="primaryComparer">Comparison, defining the primary sort order.</param> /// <param name="secondaryComparer">Comparison, defining the secondary sort order.</param> public static void SortAll<T1, T2>(IList<T1> primary, IList<T2> secondary, IComparer<T1> primaryComparer = null, IComparer<T2> secondaryComparer = null) { if (null == primaryComparer) { primaryComparer = Comparer<T1>.Default; } if (null == secondaryComparer) { secondaryComparer = Comparer<T2>.Default; } // local sort implementation QuickSortAll(primary, secondary, primaryComparer, secondaryComparer, 0, primary.Count - 1); } /// <summary> /// Recursive implementation for an in place quick sort on a list. /// </summary> /// <typeparam name="T">The type of the list on which the quick sort is performed.</typeparam> /// <param name="keys">The list which is sorted using quick sort.</param> /// <param name="comparer">The method with which to compare two elements of the quick sort.</param> /// <param name="left">The left boundary of the quick sort.</param> /// <param name="right">The right boundary of the quick sort.</param> static void QuickSort<T>(IList<T> keys, IComparer<T> comparer, int left, int right) { do { // Pivoting int a = left; int b = right; int p = a + ((b - a) >> 1); // midpoint if (comparer.Compare(keys[a], keys[p]) > 0) { Swap(keys, a, p); } if (comparer.Compare(keys[a], keys[b]) > 0) { Swap(keys, a, b); } if (comparer.Compare(keys[p], keys[b]) > 0) { Swap(keys, p, b); } T pivot = keys[p]; // Hoare Partitioning do { while (comparer.Compare(keys[a], pivot) < 0) { a++; } while (comparer.Compare(pivot, keys[b]) < 0) { b--; } if (a > b) { break; } if (a < b) { Swap(keys, a, b); } a++; b--; } while (a <= b); // In order to limit the recursion depth to log(n), we sort the // shorter partition recursively and the longer partition iteratively. if ((b - left) <= (right - a)) { if (left < b) { QuickSort(keys, comparer, left, b); } left = a; } else { if (a < right) { QuickSort(keys, comparer, a, right); } right = b; } } while (left < right); } /// <summary> /// Recursive implementation for an in place quick sort on a list while reordering one other list accordingly. /// </summary> /// <typeparam name="T">The type of the list on which the quick sort is performed.</typeparam> /// <typeparam name="TItems">The type of the list which is automatically reordered accordingly.</typeparam> /// <param name="keys">The list which is sorted using quick sort.</param> /// <param name="items">The list which is automatically reordered accordingly.</param> /// <param name="comparer">The method with which to compare two elements of the quick sort.</param> /// <param name="left">The left boundary of the quick sort.</param> /// <param name="right">The right boundary of the quick sort.</param> static void QuickSort<T, TItems>(IList<T> keys, IList<TItems> items, IComparer<T> comparer, int left, int right) { do { // Pivoting int a = left; int b = right; int p = a + ((b - a) >> 1); // midpoint if (comparer.Compare(keys[a], keys[p]) > 0) { Swap(keys, a, p); Swap(items, a, p); } if (comparer.Compare(keys[a], keys[b]) > 0) { Swap(keys, a, b); Swap(items, a, b); } if (comparer.Compare(keys[p], keys[b]) > 0) { Swap(keys, p, b); Swap(items, p, b); } T pivot = keys[p]; // Hoare Partitioning do { while (comparer.Compare(keys[a], pivot) < 0) { a++; } while (comparer.Compare(pivot, keys[b]) < 0) { b--; } if (a > b) { break; } if (a < b) { Swap(keys, a, b); Swap(items, a, b); } a++; b--; } while (a <= b); // In order to limit the recursion depth to log(n), we sort the // shorter partition recursively and the longer partition iteratively. if ((b - left) <= (right - a)) { if (left < b) { QuickSort(keys, items, comparer, left, b); } left = a; } else { if (a < right) { QuickSort(keys, items, comparer, a, right); } right = b; } } while (left < right); } /// <summary> /// Recursive implementation for an in place quick sort on one list while reordering two other lists accordingly. /// </summary> /// <typeparam name="T">The type of the list on which the quick sort is performed.</typeparam> /// <typeparam name="TItems1">The type of the first list which is automatically reordered accordingly.</typeparam> /// <typeparam name="TItems2">The type of the second list which is automatically reordered accordingly.</typeparam> /// <param name="keys">The list which is sorted using quick sort.</param> /// <param name="items1">The first list which is automatically reordered accordingly.</param> /// <param name="items2">The second list which is automatically reordered accordingly.</param> /// <param name="comparer">The method with which to compare two elements of the quick sort.</param> /// <param name="left">The left boundary of the quick sort.</param> /// <param name="right">The right boundary of the quick sort.</param> static void QuickSort<T, TItems1, TItems2>( IList<T> keys, IList<TItems1> items1, IList<TItems2> items2, IComparer<T> comparer, int left, int right) { do { // Pivoting int a = left; int b = right; int p = a + ((b - a) >> 1); // midpoint if (comparer.Compare(keys[a], keys[p]) > 0) { Swap(keys, a, p); Swap(items1, a, p); Swap(items2, a, p); } if (comparer.Compare(keys[a], keys[b]) > 0) { Swap(keys, a, b); Swap(items1, a, b); Swap(items2, a, b); } if (comparer.Compare(keys[p], keys[b]) > 0) { Swap(keys, p, b); Swap(items1, p, b); Swap(items2, p, b); } T pivot = keys[p]; // Hoare Partitioning do { while (comparer.Compare(keys[a], pivot) < 0) { a++; } while (comparer.Compare(pivot, keys[b]) < 0) { b--; } if (a > b) { break; } if (a < b) { Swap(keys, a, b); Swap(items1, a, b); Swap(items2, a, b); } a++; b--; } while (a <= b); // In order to limit the recursion depth to log(n), we sort the // shorter partition recursively and the longer partition iteratively. if ((b - left) <= (right - a)) { if (left < b) { QuickSort(keys, items1, items2, comparer, left, b); } left = a; } else { if (a < right) { QuickSort(keys, items1, items2, comparer, a, right); } right = b; } } while (left < right); } /// <summary> /// Recursive implementation for an in place quick sort on the primary and then by the secondary list while reordering one secondary list accordingly. /// </summary> /// <typeparam name="T1">The type of the primary list.</typeparam> /// <typeparam name="T2">The type of the secondary list.</typeparam> /// <param name="primary">The list which is sorted using quick sort.</param> /// <param name="secondary">The list which is sorted secondarily (on primary duplicates) and automatically reordered accordingly.</param> /// <param name="primaryComparer">The method with which to compare two elements of the primary list.</param> /// <param name="secondaryComparer">The method with which to compare two elements of the secondary list.</param> /// <param name="left">The left boundary of the quick sort.</param> /// <param name="right">The right boundary of the quick sort.</param> static void QuickSortAll<T1, T2>( IList<T1> primary, IList<T2> secondary, IComparer<T1> primaryComparer, IComparer<T2> secondaryComparer, int left, int right) { do { // Pivoting int a = left; int b = right; int p = a + ((b - a) >> 1); // midpoint int ap = primaryComparer.Compare(primary[a], primary[p]); if (ap > 0 || ap == 0 && secondaryComparer.Compare(secondary[a], secondary[p]) > 0) { Swap(primary, a, p); Swap(secondary, a, p); } int ab = primaryComparer.Compare(primary[a], primary[b]); if (ab > 0 || ab == 0 && secondaryComparer.Compare(secondary[a], secondary[b]) > 0) { Swap(primary, a, b); Swap(secondary, a, b); } int pb = primaryComparer.Compare(primary[p], primary[b]); if (pb > 0 || pb == 0 && secondaryComparer.Compare(secondary[p], secondary[b]) > 0) { Swap(primary, p, b); Swap(secondary, p, b); } T1 pivot1 = primary[p]; T2 pivot2 = secondary[p]; // Hoare Partitioning do { int ax; while ((ax = primaryComparer.Compare(primary[a], pivot1)) < 0 || ax == 0 && secondaryComparer.Compare(secondary[a], pivot2) < 0) { a++; } int xb; while ((xb = primaryComparer.Compare(pivot1, primary[b])) < 0 || xb == 0 && secondaryComparer.Compare(pivot2, secondary[b]) < 0) { b--; } if (a > b) { break; } if (a < b) { Swap(primary, a, b); Swap(secondary, a, b); } a++; b--; } while (a <= b); // In order to limit the recursion depth to log(n), we sort the // shorter partition recursively and the longer partition iteratively. if ((b - left) <= (right - a)) { if (left < b) { QuickSortAll(primary, secondary, primaryComparer, secondaryComparer, left, b); } left = a; } else { if (a < right) { QuickSortAll(primary, secondary, primaryComparer, secondaryComparer, a, right); } right = b; } } while (left < right); } /// <summary> /// Performs an in place swap of two elements in a list. /// </summary> /// <typeparam name="T">The type of elements stored in the list.</typeparam> /// <param name="keys">The list in which the elements are stored.</param> /// <param name="a">The index of the first element of the swap.</param> /// <param name="b">The index of the second element of the swap.</param> static void Swap<T>(IList<T> keys, int a, int b) { if (a == b) { return; } T local = keys[a]; keys[a] = keys[b]; keys[b] = local; } } }
#region License // // ElementLabel.cs July 2006 // // Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net> // // 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 Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>ElementLabel</c> represents a label that is used to /// represent an XML element in a class schema. This element can be /// used to convert an XML node into either a primitive value such as /// a string or composite object value, which is itself a schema for /// a section of XML within the XML document. /// </summary> /// <seealso> /// SimpleFramework.Xml.Element /// </seealso> class ElementLabel : Label { /// <summary> /// This is the decorator that is associated with the element. /// </summary> private Decorator decorator; /// <summary> /// The contact that this element label represents. /// </summary> private Signature detail; /// <summary> /// References the annotation that was used by the field. /// </summary> private Element label; /// <summary> /// This is the type of the class that the field references. /// </summary> private Class type; /// <summary> /// This is the name of the element for this label instance. /// </summary> private String name; /// <summary> /// Constructor for the <c>ElementLabel</c> object. This is /// used to create a label that can convert a XML node into a /// composite object or a primitive type from an XML element. /// </summary> /// <param name="contact"> /// this is the field that this label represents /// </param> /// <param name="label"> /// this is the annotation for the contact /// </param> public ElementLabel(Contact contact, Element label) { this.detail = new Signature(contact, this); this.decorator = new Qualifier(contact); this.type = contact.Type; this.name = label.name(); this.label = label; } /// <summary> /// This is used to acquire the <c>Decorator</c> for this. /// A decorator is an object that adds various details to the /// node without changing the overall structure of the node. For /// example comments and namespaces can be added to the node with /// a decorator as they do not affect the deserialization. /// </summary> /// <returns> /// this returns the decorator associated with this /// </returns> public Decorator Decorator { get { return decorator; } } //public Decorator GetDecorator() { // return decorator; //} /// Creates a converter that can be used to transform an XML node to /// an object and vice versa. The converter created will handles /// only XML elements and requires the context object to be provided. /// </summary> /// <param name="context"> /// this is the context object used for serialization /// </param> /// <returns> /// this returns a converter for serializing XML elements /// </returns> public Converter GetConverter(Context context) { Type type = Contact; if(context.isPrimitive(type)) { return new Primitive(context, type); } return new Composite(context, type); } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <param name="context"> /// this is used to provide a styled name /// </param> /// <returns> /// returns the name that is used for the XML property /// </returns> public String GetName(Context context) { Style style = context.getStyle(); String name = detail.GetName(); return style.getElement(name); } /// <summary> /// This is used to provide a configured empty value used when the /// annotated value is null. This ensures that XML can be created /// with required details regardless of whether values are null or /// not. It also provides a means for sensible default values. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns the string to use for default values /// </returns> public Object GetEmpty(Context context) { return null; } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String Name { get { return detail.GetName(); } } //public String GetName() { // return detail.GetName(); //} /// This is used to acquire the contact object for this label. The /// contact retrieved can be used to set any object or primitive that /// has been deserialized, and can also be used to acquire values to /// be serialized in the case of object persistence. All contacts /// that are retrieved from this method will be accessible. /// </summary> /// <returns> /// returns the contact that this label is representing /// </returns> public Contact Contact { get { return detail.Contact; } } //public Contact GetContact() { // return detail.Contact; //} /// This is used to acquire the name of the element or attribute /// as taken from the annotation. If the element or attribute /// explicitly specifies a name then that name is used for the /// XML element or attribute used. If however no overriding name /// is provided then the method or field is used for the name. /// </summary> /// <returns> /// returns the name of the annotation for the contact /// </returns> public String Override { get { return name; } } //public String GetOverride() { // return name; //} /// This acts as a convenience method used to determine the type of /// contact this represents. This is used when an object is written /// to XML. It determines whether a <c>class</c> attribute /// is required within the serialized XML element, that is, if the /// class returned by this is different from the actual value of the /// object to be serialized then that type needs to be remembered. /// </summary> /// <returns> /// this returns the type of the contact class /// </returns> public Class Type { get { return type; } } //public Class GetType() { // return type; //} /// This is typically used to acquire the entry value as acquired /// from the annotation. However given that the annotation this /// represents does not have a entry attribute this will always /// provide a null value for the entry string. /// </summary> /// <returns> /// this will always return null for the entry value /// </returns> public String Entry { get { return null; } } //public String GetEntry() { // return null; //} /// This is used to acquire the dependent class for this label. /// This returns null as there are no dependents to the element /// annotation as it can only hold primitives with no dependents. /// </summary> /// <returns> /// this is used to return the dependent type of null /// </returns> public Type Dependent { get { return null; } } //public Type GetDependent() { // return null; //} /// This method is used to determine if the label represents an /// attribute. This is used to style the name so that elements /// are styled as elements and attributes are styled as required. /// </summary> /// <returns> /// this is used to determine if this is an attribute /// </returns> public bool IsAttribute() { return false; } /// <summary> /// This is used to determine if the label is a collection. If the /// label represents a collection then any original assignment to /// the field or method can be written to without the need to /// create a new collection. This allows obscure collections to be /// used and also allows initial entries to be maintained. /// </summary> /// <returns> /// true if the label represents a collection value /// </returns> public bool IsCollection() { return false; } /// <summary> /// This is used to determine whether the XML element is required. /// This ensures that if an XML element is missing from a document /// that deserialization can continue. Also, in the process of /// serialization, if a value is null it does not need to be /// written to the resulting XML document. /// </summary> /// <returns> /// true if the label represents a some required data /// </returns> public bool IsRequired() { return label.required(); } /// <summary> /// This is used to determine whether the annotation requires it /// and its children to be written as a CDATA block. This is done /// when a primitive or other such element requires a text value /// and that value needs to be encapsulated within a CDATA block. /// </summary> /// <returns> /// this returns true if the element requires CDATA /// </returns> public bool IsData() { return label.data(); } /// <summary> /// This method is used by the deserialization process to check /// to see if an annotation is inline or not. If an annotation /// represents an inline XML entity then the deserialization /// and serialization process ignores overrides and special /// attributes. By default all XML elements are not inline. /// </summary> /// <returns> /// this always returns false for element labels /// </returns> public bool IsInline() { return false; } /// <summary> /// This is used to describe the annotation and method or field /// that this label represents. This is used to provide error /// messages that can be used to debug issues that occur when /// processing a method. This will provide enough information /// such that the problem can be isolated correctly. /// </summary> /// <returns> /// this returns a string representation of the label /// </returns> public String ToString() { return detail.ToString(); } } }
// 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.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal class WinHttpRequestStream : Stream { private static byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" private static byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" private volatile bool _disposed; private WinHttpRequestState _state; private bool _chunkedMode; // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedSendPinnedBuffer; internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode) { _state = state; _chunkedMode = chunkedMode; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override void Flush() { // Nothing to do. } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - offset) { throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer)); } if (token.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(); tcs.TrySetCanceled(token); return tcs.Task; } CheckDisposed(); if (_state.TcsInternalWriteDataToRequestStream != null && !_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted) { throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed); } return InternalWriteAsync(buffer, offset, count, token); } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } internal async Task EndUploadAsync(CancellationToken token) { if (_chunkedMode) { await InternalWriteDataAsync(s_endChunk, 0, s_endChunk.Length, token).ConfigureAwait(false); } } protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; // TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further // operations will be made to the send/receive buffers. if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { return _chunkedMode ? InternalWriteChunkedModeAsync(buffer, offset, count, token) : InternalWriteDataAsync(buffer, offset, count, token); } private async Task InternalWriteChunkedModeAsync(byte[] buffer, int offset, int count, CancellationToken token) { // WinHTTP does not fully support chunked uploads. It simply allows one to omit the 'Content-Length' header // and instead use the 'Transfer-Encoding: chunked' header. The caller is still required to encode the // request body according to chunking rules. Debug.Assert(_chunkedMode); string chunkSizeString = String.Format("{0:x}\r\n", count); byte[] chunkSize = Encoding.UTF8.GetBytes(chunkSizeString); await InternalWriteDataAsync(chunkSize, 0, chunkSize.Length, token).ConfigureAwait(false); await InternalWriteDataAsync(buffer, offset, count, token).ConfigureAwait(false); await InternalWriteDataAsync(s_crLfTerminator, 0, s_crLfTerminator.Length, token).ConfigureAwait(false); } private Task<bool> InternalWriteDataAsync(byte[] buffer, int offset, int count, CancellationToken token) { Debug.Assert(count >= 0); if (count == 0) { return Task.FromResult<bool>(true); } // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer) { if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _cachedSendPinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); } _state.TcsInternalWriteDataToRequestStream = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (_state.Lock) { if (!Interop.WinHttp.WinHttpWriteData( _state.RequestHandle, Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset), (uint)count, IntPtr.Zero)) { _state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, WinHttpException.CreateExceptionUsingLastError().InitializeStackTrace())); } } // TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation. return _state.TcsInternalWriteDataToRequestStream.Task; } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using UnityEngine; using System.Collections.Generic; /// <summary> /// Controls the player's movement in virtual reality. /// </summary> [RequireComponent(typeof(CharacterController))] public class OVRPlayerController : MonoBehaviour { /// <summary> /// The rate acceleration during movement. /// </summary> public float Acceleration = 0.1f; /// <summary> /// The rate of damping on movement. /// </summary> public float Damping = 0.3f; /// <summary> /// The rate of additional damping when moving sideways or backwards. /// </summary> public float BackAndSideDampen = 0.5f; /// <summary> /// The force applied to the character when jumping. /// </summary> public float JumpForce = 0.3f; /// <summary> /// The rate of rotation when using a gamepad. /// </summary> public float RotationAmount = 1.5f; /// <summary> /// The rate of rotation when using the keyboard. /// </summary> public float RotationRatchet = 45.0f; /// <summary> /// The player's current rotation about the Y axis. /// </summary> private float YRotation = 0.0f; /// <summary> /// If true, tracking data from a child OVRCameraRig will update the direction of movement. /// </summary> public bool HmdRotatesY = true; /// <summary> /// Modifies the strength of gravity. /// </summary> public float GravityModifier = 0.379f; private float MoveScale = 1.0f; private Vector3 MoveThrottle = Vector3.zero; private float FallSpeed = 0.0f; private OVRPose? InitialPose; private Quaternion initialRotation; private Quaternion currentRotation; /// <summary> /// If true, each OVRPlayerController will use the player's physical height. /// </summary> public bool useProfileHeight = true; protected CharacterController Controller = null; protected OVRCameraRig CameraController = null; private float MoveScaleMultiplier = 1.0f; private float RotationScaleMultiplier = 1.0f; private bool SkipMouseRotation = false; private bool HaltUpdateMovement = false; private bool prevHatLeft = false; private bool prevHatRight = false; private float SimulationRate = 60f; void Awake() { Controller = gameObject.GetComponent<CharacterController>(); if(Controller == null) Debug.LogWarning("OVRPlayerController: No CharacterController attached."); // We use OVRCameraRig to set rotations to cameras, // and to be influenced by rotation OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached."); else CameraController = CameraControllers[0]; YRotation = transform.rotation.eulerAngles.y; #if UNITY_ANDROID && !UNITY_EDITOR OVRManager.display.RecenteredPose += ResetOrientation; #endif } protected virtual void Update() { if(initialRotation == null){ initialRotation = transform.rotation; } else{ currentRotation = transform.rotation; } if (useProfileHeight) { if (InitialPose == null) { InitialPose = new OVRPose() { position = CameraController.transform.localPosition, orientation = CameraController.transform.localRotation }; } var p = CameraController.transform.localPosition; p.y = OVRManager.profile.eyeHeight - 0.5f * Controller.height; p.z = OVRManager.profile.eyeDepth; CameraController.transform.localPosition = p; } else if (InitialPose != null) { CameraController.transform.localPosition = InitialPose.Value.position; CameraController.transform.localRotation = InitialPose.Value.orientation; InitialPose = null; } UpdateMovement(); Vector3 moveDirection = Vector3.zero; float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime)); MoveThrottle.x /= motorDamp; MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y; MoveThrottle.z /= motorDamp; moveDirection += MoveThrottle * SimulationRate * Time.deltaTime; // Gravity if (Controller.isGrounded && FallSpeed <= 0) FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f))); else FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime); moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime; // Offset correction for uneven ground float bumpUpOffset = 0.0f; if (Controller.isGrounded && MoveThrottle.y <= 0.001f) { bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude); moveDirection -= bumpUpOffset * Vector3.up; } Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1)); // Move contoller Controller.Move(moveDirection); Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1)); if (predictedXZ != actualXZ) MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime); } public virtual void UpdateMovement() { if (HaltUpdateMovement) return; bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); if(Input.GetKey(KeyCode.U)) Jump (); bool dpad_move = false; if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Up)) { moveForward = true; dpad_move = true; } if (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down)) { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if ( (moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight) ) MoveScale = 0.70710678f; // No positional movement if we are in the air //if (!Controller.isGrounded) //MoveScale = 0.0f; MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) moveInfluence *= 2.0f; Quaternion ort = (HmdRotatesY) ? CameraController.centerEyeAnchor.rotation : transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); if (moveBack) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if (moveLeft) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if (moveRight) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); bool curHatLeft = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.LeftShoulder); Vector3 euler = transform.rotation.eulerAngles; if (curHatLeft && !prevHatLeft) euler.y -= RotationRatchet; prevHatLeft = curHatLeft; bool curHatRight = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.RightShoulder); if(curHatRight && !prevHatRight) euler.y += RotationRatchet; prevHatRight = curHatRight; //Use keys to ratchet rotation if (Input.GetKeyDown(KeyCode.Q)) euler.y -= RotationRatchet; if (Input.GetKeyDown(KeyCode.E)) euler.y += RotationRatchet; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; if (!SkipMouseRotation) euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; moveInfluence = SimulationRate * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftTrigger); #endif float leftAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftXAxis); float leftAxisY = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.LeftYAxis); if(leftAxisY > 0.0f) MoveThrottle += ort * (leftAxisY * moveInfluence * Vector3.forward); if(leftAxisY < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisY) * moveInfluence * BackAndSideDampen * Vector3.back); if(leftAxisX < 0.0f) MoveThrottle += ort * (Mathf.Abs(leftAxisX) * moveInfluence * BackAndSideDampen * Vector3.left); if(leftAxisX > 0.0f) MoveThrottle += ort * (leftAxisX * moveInfluence * BackAndSideDampen * Vector3.right); float rightAxisX = OVRGamepadController.GPC_GetAxis(OVRGamepadController.Axis.RightXAxis); euler.y += rightAxisX * rotateInfluence; transform.rotation = Quaternion.Euler(euler); } /// <summary> /// Jump! Must be enabled manually. /// </summary> public bool Jump() { if (!Controller.isGrounded) return false; MoveThrottle += new Vector3(0, JumpForce, 0); return true; } /// <summary> /// Stop this instance. /// </summary> public void Stop() { Controller.Move(Vector3.zero); MoveThrottle = Vector3.zero; FallSpeed = 0.0f; } /// <summary> /// Gets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void GetMoveScaleMultiplier(ref float moveScaleMultiplier) { moveScaleMultiplier = MoveScaleMultiplier; } /// <summary> /// Sets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void SetMoveScaleMultiplier(float moveScaleMultiplier) { MoveScaleMultiplier = moveScaleMultiplier; } /// <summary> /// Gets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier) { rotationScaleMultiplier = RotationScaleMultiplier; } /// <summary> /// Sets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void SetRotationScaleMultiplier(float rotationScaleMultiplier) { RotationScaleMultiplier = rotationScaleMultiplier; } /// <summary> /// Gets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">Allow mouse rotation.</param> public void GetSkipMouseRotation(ref bool skipMouseRotation) { skipMouseRotation = SkipMouseRotation; } /// <summary> /// Sets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param> public void SetSkipMouseRotation(bool skipMouseRotation) { SkipMouseRotation = skipMouseRotation; } /// <summary> /// Gets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">Halt update movement.</param> public void GetHaltUpdateMovement(ref bool haltUpdateMovement) { haltUpdateMovement = HaltUpdateMovement; } /// <summary> /// Sets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param> public void SetHaltUpdateMovement(bool haltUpdateMovement) { HaltUpdateMovement = haltUpdateMovement; } /// <summary> /// Resets the player look rotation when the device orientation is reset. /// </summary> public void ResetOrientation() { Vector3 euler = transform.rotation.eulerAngles; euler.y = YRotation; transform.rotation = Quaternion.Euler(euler); } public float changeInRotation(){ return Quaternion.Angle(currentRotation, initialRotation); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebApiBasicAuth.Areas.HelpPage.ModelDescriptions; using WebApiBasicAuth.Areas.HelpPage.Models; namespace WebApiBasicAuth.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using System.Collections; using System.Collections.Generic; using Leap.Unity.Attributes; namespace Leap.Unity { /** A basic Leap hand model constructed dynamically vs. using pre-existing geometry*/ public class CapsuleHand : IHandModel { private const int TOTAL_JOINT_COUNT = 4 * 5; private const float CYLINDER_MESH_RESOLUTION = 0.1f; //in centimeters, meshes within this resolution will be re-used private const int THUMB_BASE_INDEX = (int)Finger.FingerType.TYPE_THUMB * 4; private const int PINKY_BASE_INDEX = (int)Finger.FingerType.TYPE_PINKY * 4; private const float SPHERE_RADIUS = 0.008f; private const float CYLINDER_RADIUS = 0.006f; private const float PALM_RADIUS = 0.015f; private static int _leftColorIndex = 0; private static int _rightColorIndex = 0; private static Color[] _leftColorList = { new Color(0.0f, 0.0f, 1.0f), new Color(0.2f, 0.0f, 0.4f), new Color(0.0f, 0.2f, 0.2f) }; private static Color[] _rightColorList = { new Color(1.0f, 0.0f, 0.0f), new Color(1.0f, 1.0f, 0.0f), new Color(1.0f, 0.5f, 0.0f) }; [SerializeField] private Chirality handedness; [SerializeField] private bool _showArm = true; [SerializeField] private Material _material; [SerializeField] private Mesh _sphereMesh; [MinValue(3)] [SerializeField] private int _cylinderResolution = 12; private Material _sphereMat; private Hand _hand; private Vector3[] _spherePositions; public override ModelType HandModelType { get { return ModelType.Graphics; } } public override Chirality Handedness { get { return handedness; } set { } } public override bool SupportsEditorPersistence() { return true; } public override Hand GetLeapHand() { return _hand; } public override void SetLeapHand(Hand hand) { _hand = hand; } public override void InitHand() { if (_material != null) { _sphereMat = new Material(_material); _sphereMat.hideFlags = HideFlags.DontSaveInEditor; } } private void OnValidate() { _meshMap.Clear(); } public override void BeginHand() { base.BeginHand(); if (_hand.IsLeft) { _sphereMat.color = _leftColorList[_leftColorIndex]; _leftColorIndex = (_leftColorIndex + 1) % _leftColorList.Length; } else { _sphereMat.color = _rightColorList[_rightColorIndex]; _rightColorIndex = (_rightColorIndex + 1) % _rightColorList.Length; } } public override void UpdateHand() { if (_spherePositions == null || _spherePositions.Length != TOTAL_JOINT_COUNT) { _spherePositions = new Vector3[TOTAL_JOINT_COUNT]; } if (_sphereMat == null) { _sphereMat = new Material(_material); _sphereMat.hideFlags = HideFlags.DontSaveInEditor; } //Update all joint spheres in the fingers foreach (var finger in _hand.Fingers) { for (int j = 0; j < 4; j++) { int key = getFingerJointIndex((int)finger.Type, j); Vector3 position = finger.Bone((Bone.BoneType)j).NextJoint.ToVector3(); _spherePositions[key] = position; drawSphere(position); } } //Now we just have a few more spheres for the hands //PalmPos, WristPos, and mockThumbJointPos, which is derived and not taken from the frame obj Vector3 palmPosition = _hand.PalmPosition.ToVector3(); drawSphere(palmPosition, PALM_RADIUS); Vector3 wristPos = _hand.PalmPosition.ToVector3(); drawSphere(wristPos); Vector3 thumbBaseToPalm = _spherePositions[THUMB_BASE_INDEX] - _hand.PalmPosition.ToVector3(); Vector3 mockThumbJointPos = _hand.PalmPosition.ToVector3() + Vector3.Reflect(thumbBaseToPalm, _hand.Basis.xBasis.ToVector3()); drawSphere(mockThumbJointPos); //If we want to show the arm, do the calculations and display the meshes if (_showArm) { var arm = _hand.Arm; Vector3 right = arm.Basis.xBasis.ToVector3() * arm.Width * 0.7f * 0.5f; Vector3 wrist = arm.WristPosition.ToVector3(); Vector3 elbow = arm.ElbowPosition.ToVector3(); float armLength = Vector3.Distance(wrist, elbow); wrist -= arm.Direction.ToVector3() * armLength * 0.05f; Vector3 armFrontRight = wrist + right; Vector3 armFrontLeft = wrist - right; Vector3 armBackRight = elbow + right; Vector3 armBackLeft = elbow - right; drawSphere(armFrontRight); drawSphere(armFrontLeft); drawSphere(armBackLeft); drawSphere(armBackRight); drawCylinder(armFrontLeft, armFrontRight); drawCylinder(armBackLeft, armBackRight); drawCylinder(armFrontLeft, armBackLeft); drawCylinder(armFrontRight, armBackRight); } //Draw cylinders between finger joints for (int i = 0; i < 5; i++) { for (int j = 0; j < 3; j++) { int keyA = getFingerJointIndex(i, j); int keyB = getFingerJointIndex(i, j + 1); Vector3 posA = _spherePositions[keyA]; Vector3 posB = _spherePositions[keyB]; drawCylinder(posA, posB); } } //Draw cylinders between finger knuckles for (int i = 0; i < 4; i++) { int keyA = getFingerJointIndex(i, 0); int keyB = getFingerJointIndex(i + 1, 0); Vector3 posA = _spherePositions[keyA]; Vector3 posB = _spherePositions[keyB]; drawCylinder(posA, posB); } //Draw the rest of the hand drawCylinder(mockThumbJointPos, THUMB_BASE_INDEX); drawCylinder(mockThumbJointPos, PINKY_BASE_INDEX); } private void drawSphere(Vector3 position, float radius = SPHERE_RADIUS) { //multiply radius by 2 because the default unity sphere has a radius of 0.5 meters at scale 1. Graphics.DrawMesh(_sphereMesh, Matrix4x4.TRS(position, Quaternion.identity, Vector3.one * radius * 2.0f), _sphereMat, 0); } private void drawCylinder(Vector3 a, Vector3 b) { float length = (a - b).magnitude; Graphics.DrawMesh(getCylinderMesh(length), Matrix4x4.TRS(a, Quaternion.LookRotation(b - a), Vector3.one), _material, gameObject.layer); } private void drawCylinder(int a, int b) { drawCylinder(_spherePositions[a], _spherePositions[b]); } private void drawCylinder(Vector3 a, int b) { drawCylinder(a, _spherePositions[b]); } private int getFingerJointIndex(int fingerIndex, int jointIndex) { return fingerIndex * 4 + jointIndex; } private Dictionary<int, Mesh> _meshMap = new Dictionary<int, Mesh>(); private Mesh getCylinderMesh(float length) { int lengthKey = Mathf.RoundToInt(length * 100 / CYLINDER_MESH_RESOLUTION); Mesh mesh; if (_meshMap.TryGetValue(lengthKey, out mesh)) { return mesh; } mesh = new Mesh(); mesh.name = "GeneratedCylinder"; mesh.hideFlags = HideFlags.DontSave; List<Vector3> verts = new List<Vector3>(); List<Color> colors = new List<Color>(); List<int> tris = new List<int>(); Vector3 p0 = Vector3.zero; Vector3 p1 = Vector3.forward * length; for (int i = 0; i < _cylinderResolution; i++) { float angle = (Mathf.PI * 2.0f * i) / _cylinderResolution; float dx = CYLINDER_RADIUS * Mathf.Cos(angle); float dy = CYLINDER_RADIUS * Mathf.Sin(angle); Vector3 spoke = new Vector3(dx, dy, 0); verts.Add((p0 + spoke) * transform.lossyScale.x); verts.Add((p1 + spoke) * transform.lossyScale.x); colors.Add(Color.white); colors.Add(Color.white); int triStart = verts.Count; int triCap = _cylinderResolution * 2; tris.Add((triStart + 0) % triCap); tris.Add((triStart + 2) % triCap); tris.Add((triStart + 1) % triCap); tris.Add((triStart + 2) % triCap); tris.Add((triStart + 3) % triCap); tris.Add((triStart + 1) % triCap); } mesh.SetVertices(verts); mesh.SetIndices(tris.ToArray(), MeshTopology.Triangles, 0); mesh.RecalculateBounds(); mesh.RecalculateNormals(); mesh.UploadMeshData(true); _meshMap[lengthKey] = mesh; return mesh; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Text; namespace OpenTK { #if NO_SYSDRAWING /// <summary> /// Defines a point on a two-dimensional plane. /// </summary> public struct Point : IEquatable<Point> { #region Fields int x, y; #endregion #region Constructors /// <summary> /// Constructs a new Point instance. /// </summary> /// <param name="x">The X coordinate of this instance.</param> /// <param name="y">The Y coordinate of this instance.</param> public Point(int x, int y) : this() { X = x; Y = y; } #endregion #region Public Members /// <summary> /// Gets a <see cref="System.Boolean"/> that indicates whether this instance is empty or zero. /// </summary> public bool IsEmpty { get { return X == 0 && Y == 0; } } /// <summary> /// Gets or sets the X coordinate of this instance. /// </summary> public int X { get { return x; } set { x = value; } } /// <summary> /// Gets or sets the Y coordinate of this instance. /// </summary> public int Y { get { return y; } set { y = value; } } /// <summary> /// Returns the Point (0, 0). /// </summary> public static readonly Point Zero = new Point(); /// <summary> /// Returns the Point (0, 0). /// </summary> public static readonly Point Empty = new Point(); /// <summary> /// Translates the specified Point by the specified Size. /// </summary> /// <param name="point"> /// The <see cref="Point"/> instance to translate. /// </param> /// <param name="size"> /// The <see cref="Size"/> instance to translate point with. /// </param> /// <returns> /// A new <see cref="Point"/> instance translated by size. /// </returns> public static Point operator +(Point point, Size size) { return new Point(point.X + size.Width, point.Y + size.Height); } /// <summary> /// Translates the specified Point by the negative of the specified Size. /// </summary> /// <param name="point"> /// The <see cref="Point"/> instance to translate. /// </param> /// <param name="size"> /// The <see cref="Size"/> instance to translate point with. /// </param> /// <returns> /// A new <see cref="Point"/> instance translated by size. /// </returns> public static Point operator -(Point point, Size size) { return new Point(point.X - size.Width, point.Y - size.Height); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left is equal to right; false otherwise.</returns> public static bool operator ==(Point left, Point right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left is not equal to right; false otherwise.</returns> public static bool operator !=(Point left, Point right) { return !left.Equals(right); } /// <summary> /// Converts an OpenTK.Point instance to a System.Drawing.Point. /// </summary> /// <param name="point"> /// The <see cref="Point"/> instance to convert. /// </param> /// <returns> /// A <see cref="System.Drawing.Point"/> instance equivalent to point. /// </returns> public static implicit operator System.Drawing.Point(Point point) { return new System.Drawing.Point(point.X, point.Y); } /// <summary> /// Converts a System.Drawing.Point instance to an OpenTK.Point. /// </summary> /// <param name="point"> /// The <see cref="System.Drawing.Point"/> instance to convert. /// </param> /// <returns> /// A <see cref="Point"/> instance equivalent to point. /// </returns> public static implicit operator Point(System.Drawing.Point point) { return new Point(point.X, point.Y); } /// <summary> /// Converts an OpenTK.Point instance to a System.Drawing.PointF. /// </summary> /// <param name="point"> /// The <see cref="Point"/> instance to convert. /// </param> /// <returns> /// A <see cref="System.Drawing.PointF"/> instance equivalent to point. /// </returns> public static implicit operator System.Drawing.PointF(Point point) { return new System.Drawing.PointF(point.X, point.Y); } /// <summary> /// Indicates whether this instance is equal to the specified object. /// </summary> /// <param name="obj">The object instance to compare to.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (obj is Point) return Equals((Point)obj); return false; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A <see cref="System.Int32"/> that represents the hash code for this instance./></returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } /// <summary> /// Returns a <see cref="System.String"/> that describes this instance. /// </summary> /// <returns>A <see cref="System.String"/> that describes this instance.</returns> public override string ToString() { return String.Format("{{{0}, {1}}}", X, Y); } #endregion #region IEquatable<Point> Members /// <summary> /// Indicates whether this instance is equal to the specified Point. /// </summary> /// <param name="other">The instance to compare to.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public bool Equals(Point other) { return X == other.X && Y == other.Y; } #endregion } #endif }
/* * ImageFormat.cs - Implementation of the * "System.Drawing.Imaging.ImageFormat" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing.Imaging { #if !ECMA_COMPAT public sealed class ImageFormat { // Internal state. private Guid guid; private static readonly ImageFormat bmp = new ImageFormat (new Guid("{b96b3cab-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat emf = new ImageFormat (new Guid("{b96b3cac-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat exif = new ImageFormat (new Guid("{b96b3cb2-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat gif = new ImageFormat (new Guid("{b96b3cb0-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat icon = new ImageFormat (new Guid("{b96b3cb5-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat jpeg = new ImageFormat (new Guid("{b96b3cae-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat memoryBmp = new ImageFormat (new Guid("{b96b3caa-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat png = new ImageFormat (new Guid("{b96b3caf-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat tiff = new ImageFormat (new Guid("{b96b3cb1-0728-11d3-9d7b-0000f81ef32e}")); private static readonly ImageFormat wmf = new ImageFormat (new Guid("{b96b3cad-0728-11d3-9d7b-0000f81ef32e}")); // Constructor. public ImageFormat(Guid guid) { this.guid = guid; } // Get the GUID for this image format. public Guid Guid { get { return guid; } } // Standard image formats. public static ImageFormat Bmp { get { return bmp; } } public static ImageFormat Emf { get { return emf; } } public static ImageFormat Exif { get { return exif; } } public static ImageFormat Gif { get { return gif; } } public static ImageFormat Icon { get { return icon; } } public static ImageFormat Jpeg { get { return jpeg; } } public static ImageFormat MemoryBmp { get { return memoryBmp; } } public static ImageFormat Png { get { return png; } } public static ImageFormat Tiff { get { return tiff; } } public static ImageFormat Wmf { get { return wmf; } } // Determine if two objects are equal. public override bool Equals(Object obj) { ImageFormat other = (obj as ImageFormat); if(other != null) { return (other.guid.Equals(guid)); } else { return false; } } // Get the hash code for this object. public override int GetHashCode() { return guid.GetHashCode(); } // Convert this object into a string. public override String ToString() { if(this == bmp) { return "Bmp"; } else if(this == emf) { return "Emf"; } else if(this == exif) { return "Exif"; } else if(this == gif) { return "Gif"; } else if(this == icon) { return "Icon"; } else if(this == jpeg) { return "Jpeg"; } else if(this == memoryBmp) { return "MemoryBMP"; } else if(this == png) { return "Png"; } else if(this == tiff) { return "Tiff"; } else if(this == wmf) { return "Wmf"; } else { return "[ImageFormat: " + guid.ToString() + "]"; } } }; // class ImageFormat #endif // !ECMA_COMPAT }; // namespace System.Drawing.Imaging
// ForeignKeyConstraintTest.cs - NUnit Test Cases for [explain here] // // Authors: // Franklin Wise (gracenote@earthlink.net) // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) Franklin Wise // (C) 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data; namespace MonoTests.System.Data { [TestFixture] public class ForeignKeyConstraintTest : Assertion { private DataSet _ds; //NOTE: fk constraints only work when the table is part of a DataSet [SetUp] public void GetReady() { _ds = new DataSet(); //Setup DataTable DataTable table; table = new DataTable("TestTable"); table.Columns.Add("Col1",typeof(int)); table.Columns.Add("Col2",typeof(int)); table.Columns.Add("Col3",typeof(int)); _ds.Tables.Add(table); table = new DataTable("TestTable2"); table.Columns.Add("Col1",typeof(int)); table.Columns.Add("Col2",typeof(int)); table.Columns.Add("Col3",typeof(int)); _ds.Tables.Add(table); } // Tests ctor (string, DataColumn, DataColumn) [Test] public void Ctor1 () { DataTable Table = _ds.Tables [0]; AssertEquals ("test#01", 0, Table.Constraints.Count); Table = _ds.Tables [1]; AssertEquals ("test#02", 0, Table.Constraints.Count); // ctor (string, DataColumn, DataColumn ForeignKeyConstraint Constraint = new ForeignKeyConstraint ("test", _ds.Tables [0].Columns [2], _ds.Tables [1].Columns [0]); Table = _ds.Tables [1]; Table.Constraints.Add (Constraint); AssertEquals ("test#03", 1, Table.Constraints.Count); AssertEquals ("test#04", "test", Table.Constraints [0].ConstraintName); AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [0].GetType ()); Table = _ds.Tables [0]; AssertEquals ("test#06", 1, Table.Constraints.Count); AssertEquals ("test#07", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#08", typeof (UniqueConstraint), Table.Constraints [0].GetType ()); } // Tests ctor (DataColumn, DataColumn) [Test] public void Ctor2 () { DataTable Table = _ds.Tables [0]; AssertEquals ("test#01", 0, Table.Constraints.Count); Table = _ds.Tables [1]; AssertEquals ("test#02", 0, Table.Constraints.Count); // ctor (string, DataColumn, DataColumn ForeignKeyConstraint Constraint = new ForeignKeyConstraint (_ds.Tables [0].Columns [2], _ds.Tables [1].Columns [0]); Table = _ds.Tables [1]; Table.Constraints.Add (Constraint); AssertEquals ("test#03", 1, Table.Constraints.Count); AssertEquals ("test#04", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [0].GetType ()); Table = _ds.Tables [0]; AssertEquals ("test#06", 1, Table.Constraints.Count); AssertEquals ("test#07", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#08", typeof (UniqueConstraint), Table.Constraints [0].GetType ()); } // Test ctor (DataColumn [], DataColumn []) [Test] public void Ctor3 () { DataTable Table = _ds.Tables [0]; AssertEquals ("test#01", 0, Table.Constraints.Count); Table = _ds.Tables [1]; AssertEquals ("test#02", 0, Table.Constraints.Count); DataColumn [] Cols1 = new DataColumn [2]; Cols1 [0] = _ds.Tables [0].Columns [1]; Cols1 [1] = _ds.Tables [0].Columns [2]; DataColumn [] Cols2 = new DataColumn [2]; Cols2 [0] = _ds.Tables [1].Columns [0]; Cols2 [1] = _ds.Tables [1].Columns [1]; ForeignKeyConstraint Constraint = new ForeignKeyConstraint (Cols1, Cols2); Table = _ds.Tables [1]; Table.Constraints.Add (Constraint); AssertEquals ("test#03", 1, Table.Constraints.Count); AssertEquals ("test#04", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [0].GetType ()); Table = _ds.Tables [0]; AssertEquals ("test#06", 1, Table.Constraints.Count); AssertEquals ("test#07", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#08", typeof (UniqueConstraint), Table.Constraints [0].GetType ()); } // Tests ctor (string, DataColumn [], DataColumn []) [Test] public void Ctor4 () { DataTable Table = _ds.Tables [0]; AssertEquals ("test#01", 0, Table.Constraints.Count); Table = _ds.Tables [1]; AssertEquals ("test#02", 0, Table.Constraints.Count); DataColumn [] Cols1 = new DataColumn [2]; Cols1 [0] = _ds.Tables [0].Columns [1]; Cols1 [1] = _ds.Tables [0].Columns [2]; DataColumn [] Cols2 = new DataColumn [2]; Cols2 [0] = _ds.Tables [1].Columns [0]; Cols2 [1] = _ds.Tables [1].Columns [1]; ForeignKeyConstraint Constraint = new ForeignKeyConstraint ("Test", Cols1, Cols2); Table = _ds.Tables [1]; Table.Constraints.Add (Constraint); AssertEquals ("test#03", 1, Table.Constraints.Count); AssertEquals ("test#04", "Test", Table.Constraints [0].ConstraintName); AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [0].GetType ()); Table = _ds.Tables [0]; AssertEquals ("test#06", 1, Table.Constraints.Count); AssertEquals ("test#07", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#08", typeof (UniqueConstraint), Table.Constraints [0].GetType ()); } [Test] public void TestCtor5() { DataTable table1 = new DataTable ("Table1"); DataTable table2 = new DataTable ("Table2"); DataSet dataSet = new DataSet(); dataSet.Tables.Add (table1); dataSet.Tables.Add (table2); DataColumn column1 = new DataColumn ("col1"); DataColumn column2 = new DataColumn ("col2"); DataColumn column3 = new DataColumn ("col3"); table1.Columns.Add (column1); table1.Columns.Add (column2); table1.Columns.Add (column3); DataColumn column4 = new DataColumn ("col4"); DataColumn column5 = new DataColumn ("col5"); DataColumn column6 = new DataColumn ("col6"); table2.Columns.Add (column4); table2.Columns.Add (column5); table2.Columns.Add (column6); string []parentColumnNames = {"col1", "col2", "col3"}; string []childColumnNames = {"col4", "col5", "col6"}; string parentTableName = "table1"; // Create a ForeingKeyConstraint Object using the constructor // ForeignKeyConstraint (string, string, string[], string[], AcceptRejectRule, Rule, Rule); ForeignKeyConstraint fkc = new ForeignKeyConstraint ("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade); // Assert that the Constraint object does not belong to any table yet #if NET_1_1 try { DataTable tmp = fkc.Table; Fail ("When table is null, get_Table causes an InvalidOperationException."); } catch (InvalidOperationException) { } #else Assertion.AssertEquals ("#A01 Table should not be set", fkc.Table, null); #endif Constraint []constraints = new Constraint[3]; constraints [0] = new UniqueConstraint (column1); constraints [1] = new UniqueConstraint (column2); constraints [2] = fkc; // Try to add the constraint to ConstraintCollection of the DataTable through Add() try{ table2.Constraints.Add (fkc); throw new ApplicationException ("An Exception was expected"); } // LAMESPEC : spec says InvalidConstraintException but throws this catch (ArgumentException) { } #if false // FIXME: Here this test crashes under MS.NET. // OK - So AddRange() is the only way! table2.Constraints.AddRange (constraints); // After AddRange(), Check the properties of ForeignKeyConstraint object Assertion.Assert("#A04", fkc.RelatedColumns [0].ColumnName.Equals ("col1")); Assertion.Assert("#A05", fkc.RelatedColumns [1].ColumnName.Equals ("col2")); Assertion.Assert("#A06", fkc.RelatedColumns [2].ColumnName.Equals ("col3")); Assertion.Assert("#A07", fkc.Columns [0].ColumnName.Equals ("col4")); Assertion.Assert("#A08", fkc.Columns [1].ColumnName.Equals ("col5")); Assertion.Assert("#A09", fkc.Columns [2].ColumnName.Equals ("col6")); #endif // Try to add columns with names which do not exist in the table parentColumnNames [2] = "noColumn"; ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint ("hello world", parentTableName, parentColumnNames, childColumnNames, AcceptRejectRule.Cascade, Rule.Cascade, Rule.Cascade); constraints [0] = new UniqueConstraint (column1); constraints [1] = new UniqueConstraint (column2); constraints [2] = foreignKeyConstraint; try{ table2.Constraints.AddRange (constraints); throw new ApplicationException ("An Exception was expected"); } catch (ArgumentException e) { } catch (InvalidConstraintException e){ // Could not test on ms.net, as ms.net does not reach here so far. } #if false // FIXME: Here this test crashes under MS.NET. // Check whether the child table really contains the foreign key constraint named "hello world" Assertion.Assert("#A11 ", table2.Constraints.Contains ("hello world")); #endif } // If Childs and parents are in same table [Test] public void KeyBetweenColumns () { DataTable Table = _ds.Tables [0]; AssertEquals ("test#01", 0, Table.Constraints.Count); Table = _ds.Tables [1]; AssertEquals ("test#02", 0, Table.Constraints.Count); ForeignKeyConstraint Constraint = new ForeignKeyConstraint ("Test", _ds.Tables [0].Columns [0], _ds.Tables [0].Columns [2]); Table = _ds.Tables [0]; Table.Constraints.Add (Constraint); AssertEquals ("test#03", 2, Table.Constraints.Count); AssertEquals ("test#04", "Constraint1", Table.Constraints [0].ConstraintName); AssertEquals ("test#05", typeof (UniqueConstraint), Table.Constraints [0].GetType ()); AssertEquals ("test#04", "Test", Table.Constraints [1].ConstraintName); AssertEquals ("test#05", typeof (ForeignKeyConstraint), Table.Constraints [1].GetType ()); } [Test] public void CtorExceptions () { ForeignKeyConstraint fkc; DataTable localTable = new DataTable(); localTable.Columns.Add("Col1",typeof(int)); localTable.Columns.Add("Col2",typeof(bool)); //Null try { fkc = new ForeignKeyConstraint((DataColumn)null,(DataColumn)null); Fail("Failed to throw ArgumentNullException."); } #if NET_1_1 catch (NullReferenceException) {} #else catch (ArgumentNullException) {} #endif catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("A1: Wrong Exception type. " + exc.ToString()); } //zero length collection try { fkc = new ForeignKeyConstraint(new DataColumn[]{},new DataColumn[]{}); Fail("B1: Failed to throw ArgumentException."); } catch (ArgumentException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("A2: Wrong Exception type. " + exc.ToString()); } //different datasets try { fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[0]); Fail("Failed to throw InvalidOperationException."); } catch (InvalidOperationException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("A3: Wrong Exception type. " + exc.ToString()); } try { fkc = new ForeignKeyConstraint(_ds.Tables[0].Columns[0], localTable.Columns[1]); Fail("Failed to throw InvalidConstraintException."); } #if NET_1_1 // tables in different datasets catch (InvalidOperationException) {} #else //different dataTypes catch (InvalidConstraintException) {} #endif // Cannot create a Key from Columns that belong to // different tables. try { fkc = new ForeignKeyConstraint(new DataColumn [] {_ds.Tables[0].Columns[0], _ds.Tables[0].Columns[1]}, new DataColumn [] {localTable.Columns[1], _ds.Tables[1].Columns [0]}); Fail("Failed to throw InvalidOperationException."); } catch (InvalidConstraintException) {} catch (AssertionException exc) {throw exc;} } [Test] public void CtorExceptions2 () { DataColumn col = new DataColumn("MyCol1",typeof(int)); ForeignKeyConstraint fkc; //Columns must belong to a Table try { fkc = new ForeignKeyConstraint(col, _ds.Tables[0].Columns[0]); Fail("FTT1: Failed to throw ArgumentException."); } catch (ArgumentException) {} catch (AssertionException exc) {throw exc;} // catch (Exception exc) // { // Fail("WET1: Wrong Exception type. " + exc.ToString()); // } //Columns must belong to the same table //InvalidConstraintException DataColumn [] difTable = new DataColumn [] {_ds.Tables[0].Columns[2], _ds.Tables[1].Columns[0]}; try { fkc = new ForeignKeyConstraint(difTable,new DataColumn[] { _ds.Tables[0].Columns[1], _ds.Tables[0].Columns[0]}); Fail("FTT2: Failed to throw InvalidConstraintException."); } catch (InvalidConstraintException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("WET2: Wrong Exception type. " + exc.ToString()); } //parent columns and child columns should be the same length //ArgumentException DataColumn [] twoCol = new DataColumn [] {_ds.Tables[0].Columns[0],_ds.Tables[0].Columns[1]}; try { fkc = new ForeignKeyConstraint(twoCol, new DataColumn[] { _ds.Tables[0].Columns[0]}); Fail("FTT3: Failed to throw ArgumentException."); } catch (ArgumentException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("WET3: Wrong Exception type. " + exc.ToString()); } //InvalidOperation: Parent and child are the same column. try { fkc = new ForeignKeyConstraint( _ds.Tables[0].Columns[0], _ds.Tables[0].Columns[0] ); Fail("FTT4: Failed to throw InvalidOperationException."); } catch (InvalidOperationException) {} catch (AssertionException exc) {throw exc;} catch (Exception exc) { Fail("WET4: Wrong Exception type. " + exc.ToString()); } } [Test] public void EqualsAndHashCode() { DataTable tbl = _ds.Tables[0]; DataTable tbl2 = _ds.Tables[1]; ForeignKeyConstraint fkc = new ForeignKeyConstraint( new DataColumn[] {tbl.Columns[0], tbl.Columns[1]} , new DataColumn[] {tbl2.Columns[0], tbl2.Columns[1]} ); ForeignKeyConstraint fkc2 = new ForeignKeyConstraint( new DataColumn[] {tbl.Columns[0], tbl.Columns[1]} , new DataColumn[] {tbl2.Columns[0], tbl2.Columns[1]} ); ForeignKeyConstraint fkcDiff = new ForeignKeyConstraint( tbl.Columns[1], tbl.Columns[2]); Assert( "Equals failed. 1" , fkc.Equals(fkc2)); Assert( "Equals failed. 2" , fkc2.Equals(fkc)); Assert( "Equals failed. 3" , fkc.Equals(fkc)); Assert( "Equals failed diff. 1" , fkc.Equals(fkcDiff) == false); Assert( "Hash Code Failed. 1", fkc.GetHashCode() == fkc2.GetHashCode() ); Assert( "Hash Code Failed. 2", fkc.GetHashCode() != fkcDiff.GetHashCode() ); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Candles.Algo File: CandleSourceEnumerator.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Candles { using System; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using StockSharp.Localization; class CandleSourceEnumerator<TSource, TValue> where TSource : class, ICandleSource<TValue> { private sealed class SourceInfo { public SourceInfo(TSource source, Range<DateTimeOffset> range) { Source = source; Range = range; } public TSource Source { get; } public Range<DateTimeOffset> Range { get; private set; } public override string ToString() { return Range.ToString(); } public void ExtendRange(Range<DateTimeOffset> additionalRange) { Range = new Range<DateTimeOffset>(Range.Min, additionalRange.Max); } } private readonly CandleSeries _series; private readonly Func<TValue, DateTimeOffset> _processing; private readonly Action _stopped; private readonly SynchronizedQueue<SourceInfo> _sources = new SynchronizedQueue<SourceInfo>(); private bool _manualStopped; private DateTimeOffset? _nextSourceBegin; public CandleSourceEnumerator(CandleSeries series, DateTimeOffset from, DateTimeOffset to, IEnumerable<TSource> sources, Func<TValue, DateTimeOffset> processing, Action stopped) { if (series == null) throw new ArgumentNullException(nameof(series)); if (from >= to) throw new ArgumentOutOfRangeException(nameof(to), to, LocalizedStrings.Str635Params.Put(from)); if (sources == null) throw new ArgumentNullException(nameof(sources)); if (processing == null) throw new ArgumentNullException(nameof(processing)); if (stopped == null) throw new ArgumentNullException(nameof(stopped)); var info = new List<SourceInfo>(); var requestRanges = new List<Range<DateTimeOffset>>(new[] { new Range<DateTimeOffset>(from, to) }); foreach (var group in sources.GroupBy(s => s.SpeedPriority).OrderBy(g => g.Key)) { foreach (var source in group) { foreach (var supportedRange in source.GetSupportedRanges(series)) { var index = 0; while (index < requestRanges.Count) { var requestRange = requestRanges[index]; var intersectedRange = requestRange.Intersect(supportedRange); if (intersectedRange != null) { info.Add(new SourceInfo(source, intersectedRange)); requestRanges.Remove(requestRange); var results = requestRange.Exclude(supportedRange).ToArray(); requestRanges.InsertRange(index, results); index += results.Length; } else index++; } } } } SourceInfo prevInfo = null; foreach (var i in info.OrderBy(i => i.Range.Min)) { if (prevInfo == null) { _sources.Enqueue(i); prevInfo = i; } else { if (prevInfo.Source == i.Source) prevInfo.ExtendRange(i.Range); else { _sources.Enqueue(i); prevInfo = i; } } } _series = series; _processing = processing; _stopped = stopped; } public TSource CurrentSource { get; private set; } public void Start() { if (_sources.IsEmpty()) { RaiseStop(); return; } var info = _sources.Dequeue(); CurrentSource = info.Source; CurrentSource.Processing += OnProcessing; CurrentSource.Stopped += OnStopped; var next = _sources.Count > 0 ? _sources.Peek() : null; _nextSourceBegin = next?.Range.Min; CurrentSource.Start(_series, info.Range.Min, info.Range.Max); } private void RaiseStop() { _stopped(); } private void OnProcessing(CandleSeries series, TValue value) { if (series != _series) return; var date = _processing(value); if (_nextSourceBegin != null && date > _nextSourceBegin) CurrentSource.Stop(series); } private void OnStopped(CandleSeries series) { if (series != _series) return; var raiseStop = false; lock (_sources.SyncRoot) { CurrentSource.Processing -= OnProcessing; CurrentSource.Stopped -= OnStopped; CurrentSource = null; _nextSourceBegin = null; if (_manualStopped || _sources.IsEmpty()) raiseStop = true; else Start(); } if (raiseStop) RaiseStop(); } public void Stop() { var raiseStop = false; lock (_sources.SyncRoot) { if (CurrentSource != null) { _manualStopped = true; CurrentSource.Stop(_series); } else raiseStop = true; } if (raiseStop) RaiseStop(); } } }
// 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.Diagnostics; using System.Globalization; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class SortedListTests { [Fact] public static void Ctor_Empty() { var sortList = new SortedList(); Assert.Equal(0, sortList.Count); Assert.Equal(0, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Ctor_Int(int initialCapacity) { var sortList = new SortedList(initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("initialCapacity", () => new SortedList(-1)); // InitialCapacity < 0 } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Ctor_IComparer_Int(int initialCapacity) { var sortList = new SortedList(new CustomComparer(), initialCapacity); Assert.Equal(0, sortList.Count); Assert.Equal(initialCapacity, sortList.Capacity); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_IComparer_Int_NegativeInitialCapacity_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("value", () => new SortedList(new CustomComparer(), -1)); // InitialCapacity < 0 } [Fact] public static void Ctor_IComparer() { var sortList = new SortedList(new CustomComparer()); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_IComparer_Null() { var sortList = new SortedList((IComparer)null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public static void Ctor_IDictionary(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); Assert.Equal(sortList.GetByIndex(i), value); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("d", () => new SortedList((IDictionary)null)); // Dictionary is null } [Theory] [InlineData(0, true)] [InlineData(1, true)] [InlineData(10, true)] [InlineData(100, true)] [InlineData(0, false)] [InlineData(1, false)] [InlineData(10, false)] [InlineData(100, false)] public static void Ctor_IDictionary_IComparer(int count, bool sorted) { var hashtable = new Hashtable(); if (sorted) { // Create a hashtable in the correctly sorted order for (int i = count - 1; i >= 0; i--) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } else { // Create a hashtable in the wrong order and make sure it is sorted for (int i = 0; i < count; i++) { hashtable.Add("Key_" + i.ToString("D2"), "Value_" + i.ToString("D2")); } } var sortList = new SortedList(hashtable, new CustomComparer()); Assert.Equal(count, sortList.Count); Assert.True(sortList.Capacity >= sortList.Count); for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i.ToString("D2"); string expectedValue = "Value_" + (count - i - 1).ToString("D2"); Assert.Equal(sortList.GetByIndex(i), expectedValue); Assert.Equal(hashtable[key], sortList[key]); } Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_IDictionary_IComparer_Null() { var sortList = new SortedList(new Hashtable(), null); Assert.Equal(0, sortList.Count); Assert.False(sortList.IsFixedSize); Assert.False(sortList.IsReadOnly); Assert.False(sortList.IsSynchronized); } [Fact] public static void Ctor_IDictionary_IComparer_NullDictionary_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("d", () => new SortedList(null, new CustomComparer())); // Dictionary is null } [Fact] public static void DebuggerAttribute() { var list = new SortedList() { { "a", 1 }, { "b", 2 } }; DebuggerAttributes.ValidateDebuggerDisplayReferences(new SortedList()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(list); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), SortedList.Synchronized(list)); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(SortedList), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public static void Add() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; sortList2.Add(key, value); Assert.True(sortList2.ContainsKey(key)); Assert.True(sortList2.ContainsValue(value)); Assert.Equal(i, sortList2.IndexOfKey(key)); Assert.Equal(i, sortList2.IndexOfValue(value)); Assert.Equal(i + 1, sortList2.Count); } }); } [Fact] public static void Add_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("key", () => sortList2.Add(null, 101)); // Key is null Assert.Throws<ArgumentException>(null, () => sortList2.Add(1, 101)); // Key already exists }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Clear(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { sortList2.Clear(); Assert.Equal(0, sortList2.Count); sortList2.Clear(); Assert.Equal(0, sortList2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void Clone(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { SortedList sortListClone = (SortedList)sortList2.Clone(); Assert.Equal(sortList2.Count, sortListClone.Count); Assert.False(sortListClone.IsSynchronized); // IsSynchronized is not copied Assert.Equal(sortList2.IsFixedSize, sortListClone.IsFixedSize); Assert.Equal(sortList2.IsReadOnly, sortListClone.IsReadOnly); for (int i = 0; i < sortListClone.Count; i++) { Assert.Equal(sortList2[i], sortListClone[i]); } }); } [Fact] public static void Clone_IsShallowCopy() { var sortList = new SortedList(); for (int i = 0; i < 10; i++) { sortList.Add(i, new Foo()); } SortedList sortListClone = (SortedList)sortList.Clone(); string stringValue = "Hello World"; for (int i = 0; i < 10; i++) { Assert.Equal(stringValue, ((Foo)sortListClone[i]).StringValue); } // Now we remove an object from the original list, but this should still be present in the clone sortList.RemoveAt(9); Assert.Equal(stringValue, ((Foo)sortListClone[9]).StringValue); stringValue = "Good Bye"; ((Foo)sortList[0]).StringValue = stringValue; Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); // If we change the object, of course, the previous should not happen sortListClone[0] = new Foo(); Assert.Equal(stringValue, ((Foo)sortList[0]).StringValue); stringValue = "Hello World"; Assert.Equal(stringValue, ((Foo)sortListClone[0]).StringValue); } [Fact] public static void ContainsKey() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { string key = "Key_" + i; sortList2.Add(key, i); Assert.True(sortList2.Contains(key)); Assert.True(sortList2.ContainsKey(key)); } Assert.False(sortList2.ContainsKey("Non_Existent_Key")); for (int i = 0; i < sortList2.Count; i++) { string removedKey = "Key_" + i; sortList2.Remove(removedKey); Assert.False(sortList2.Contains(removedKey)); Assert.False(sortList2.ContainsKey(removedKey)); } }); } [Fact] public static void ContainsKey_NullKey_ThrowsArgumentNullException() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("key", () => sortList2.Contains(null)); // Key is null Assert.Throws<ArgumentNullException>("key", () => sortList2.ContainsKey(null)); // Key is null }); } [Fact] public static void ContainsValue() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 100; i++) { sortList2.Add(i, "Value_" + i); Assert.True(sortList2.ContainsValue("Value_" + i)); } Assert.False(sortList2.ContainsValue("Non_Existent_Value")); for (int i = 0; i < sortList2.Count; i++) { sortList2.Remove(i); Assert.False(sortList2.ContainsValue("Value_" + i)); } }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public static void CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { var array = new object[index + count]; sortList2.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { int actualIndex = i - index; string key = "Key_" + actualIndex.ToString("D2"); string value = "Value_" + actualIndex; DictionaryEntry entry = (DictionaryEntry)array[i]; Assert.Equal(key, entry.Key); Assert.Equal(value, entry.Value); } }); } [Fact] public static void CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("array", () => sortList2.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => sortList2.CopyTo(new object[10, 10], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => sortList2.CopyTo(new object[100], -1)); // Index < 0 Assert.Throws<ArgumentException>(null, () => sortList2.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Fact] public static void GetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { Assert.Equal(i, sortList2.GetByIndex(i)); int i2 = sortList2.IndexOfKey(i); Assert.Equal(i, i2); i2 = sortList2.IndexOfValue(i); Assert.Equal(i, i2); } }); } [Fact] public static void GetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(-1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetByIndex(sortList2.Count)); // Index >= list.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetEnumerator_IDictionaryEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.NotSame(sortList2.GetEnumerator(), sortList2.GetEnumerator()); IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(enumerator.Current, enumerator.Entry); Assert.Equal(enumerator.Entry.Key, enumerator.Key); Assert.Equal(enumerator.Entry.Value, enumerator.Value); Assert.Equal(sortList2.GetKey(counter), enumerator.Entry.Key); Assert.Equal(sortList2.GetByIndex(counter), enumerator.Entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void GetEnumerator_IDictionaryEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IDictionaryEnumerator enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if index < 0 enumerator = sortList2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw after resetting enumerator = sortList2.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); // Current etc. throw if the current index is >= count enumerator = sortList2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.Entry); Assert.Throws<InvalidOperationException>(() => enumerator.Key); Assert.Throws<InvalidOperationException>(() => enumerator.Value); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetEnumerator_IEnumerator(int count) { SortedList sortList = Helpers.CreateIntSortedList(count); Assert.NotSame(sortList.GetEnumerator(), sortList.GetEnumerator()); IEnumerator enumerator = sortList.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { DictionaryEntry dictEntry = (DictionaryEntry)enumerator.Current; Assert.Equal(sortList.GetKey(counter), dictEntry.Key); Assert.Equal(sortList.GetByIndex(counter), dictEntry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } } [Fact] public static void GetEnumerator_IEnumerator_Invalid() { SortedList sortList = Helpers.CreateIntSortedList(100); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current doesn't IEnumerator enumerator = ((IEnumerable)sortList).GetEnumerator(); enumerator.MoveNext(); sortList.Add(101, 101); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current throws if index < 0 enumerator = sortList.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw after resetting enumerator = sortList.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throw if the current index is >= count enumerator = sortList.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetKeyList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys1 = sortList2.GetKeyList(); IList keys2 = sortList2.GetKeyList(); // Test we have copied the correct keys Assert.Equal(count, keys1.Count); Assert.Equal(count, keys2.Count); for (int i = 0; i < keys1.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, keys1[i]); Assert.Equal(key, keys2[i]); Assert.True(sortList2.ContainsKey(keys1[i])); } }); } [Fact] public static void GetKeyList_IsSameAsKeysProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetKeyList(), sortList.Keys); } [Fact] public static void GetKeyList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.True(keys.IsReadOnly); Assert.True(keys.IsFixedSize); Assert.False(keys.IsSynchronized); Assert.Equal(sortList2.SyncRoot, keys.SyncRoot); }); } [Fact] public static void GetKeyList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.True(keys.Contains(key)); } Assert.False(keys.Contains("Key_101")); // No such key }); } [Fact] public static void GetKeyList_Contains_InvalidValueType_ThrowsInvalidOperationException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<InvalidOperationException>(() => keys.Contains("hello")); // Value is a different object type }); } [Fact] public static void GetKeyList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); for (int i = 0; i < keys.Count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(i, keys.IndexOf(key)); } Assert.Equal(-1, keys.IndexOf("Key_101")); }); } [Fact] public static void GetKeyList_IndexOf_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<ArgumentNullException>("key", () => keys.IndexOf(null)); // Value is null Assert.Throws<InvalidOperationException>(() => keys.IndexOf("hello")); // Value is a different object type }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public static void GetKeyList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList keys = sortList2.GetKeyList(); keys.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(keys[i - index], array[i]); } }); } [Fact] public static void GetKeyList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<ArgumentNullException>("dest", () => keys.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[10, 10], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => keys.CopyTo(new object[100], -1)); // Index < 0 Assert.Throws<ArgumentException>(string.Empty, () => keys.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetKeyList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.NotSame(keys.GetEnumerator(), keys.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = keys[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void GetKeyList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = keys.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = keys.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = keys.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public static void GetKeyList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList keys = sortList2.GetKeyList(); Assert.Throws<NotSupportedException>(() => keys.Add(101)); Assert.Throws<NotSupportedException>(() => keys.Clear()); Assert.Throws<NotSupportedException>(() => keys.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => keys.Remove(1)); Assert.Throws<NotSupportedException>(() => keys.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => keys[0] = 101); }); } [Theory] [InlineData(0)] [InlineData(100)] public static void GetKey(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); Assert.Equal(key, sortList2.GetKey(sortList2.IndexOfKey(key))); } }); } [Fact] public static void GetKey_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(-1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.GetKey(sortList2.Count)); // Index >= count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetValueList(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values1 = sortList2.GetValueList(); IList values2 = sortList2.GetValueList(); // Test we have copied the correct values Assert.Equal(count, values1.Count); Assert.Equal(count, values2.Count); for (int i = 0; i < values1.Count; i++) { string value = "Value_" + i; Assert.Equal(value, values1[i]); Assert.Equal(value, values2[i]); Assert.True(sortList2.ContainsValue(values2[i])); } }); } [Fact] public static void GetValueList_IsSameAsValuesProperty() { var sortList = Helpers.CreateIntSortedList(10); Assert.Same(sortList.GetValueList(), sortList.Values); } [Fact] public static void GetValueList_IListProperties() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.True(values.IsReadOnly); Assert.True(values.IsFixedSize); Assert.False(values.IsSynchronized); Assert.Equal(sortList2.SyncRoot, values.SyncRoot); }); } [Fact] public static void GetValueList_Contains() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.True(values.Contains(value)); } // No such value Assert.False(values.Contains("Value_101")); Assert.False(values.Contains(101)); Assert.False(values.Contains(null)); }); } [Fact] public static void GetValueList_IndexOf() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); for (int i = 0; i < values.Count; i++) { string value = "Value_" + i; Assert.Equal(i, values.IndexOf(value)); } Assert.Equal(-1, values.IndexOf(101)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(0, 50)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] public static void GetValueList_CopyTo(int count, int index) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { object[] array = new object[index + count]; IList values = sortList2.GetValueList(); values.CopyTo(array, index); Assert.Equal(index + count, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(values[i - index], array[i]); } }); } [Fact] public static void GetValueList_CopyTo_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.Throws<ArgumentNullException>("dest", () => values.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => values.CopyTo(new object[10, 10], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => values.CopyTo(new object[100], -1)); // Index < 0 Assert.Throws<ArgumentException>(string.Empty, () => values.CopyTo(new object[150], 51)); // Index + list.Count > array.Count }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] public static void GetValueList_GetEnumerator(int count) { SortedList sortList1 = Helpers.CreateIntSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.NotSame(values.GetEnumerator(), values.GetEnumerator()); IEnumerator enumerator = sortList2.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { object key = values[counter]; DictionaryEntry entry = (DictionaryEntry)enumerator.Current; Assert.Equal(key, entry.Key); Assert.Equal(sortList2[key], entry.Value); counter++; } Assert.Equal(count, counter); enumerator.Reset(); } }); } [Fact] public static void ValueList_GetEnumerator_Invalid() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); // If the underlying collection is modified, MoveNext, Reset, Entry, Key and Value throw, but Current etc. doesn't IEnumerator enumerator = values.GetEnumerator(); enumerator.MoveNext(); sortList2.Add(101, 101); Assert.NotNull(enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); // Current etc. throw if index < 0 enumerator = values.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw after resetting enumerator = values.GetEnumerator(); enumerator.MoveNext(); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current etc. throw if the current index is >= count enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public static void GetValueList_TryingToModifyCollection_ThrowsNotSupportedException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { IList values = sortList2.GetValueList(); Assert.Throws<NotSupportedException>(() => values.Add(101)); Assert.Throws<NotSupportedException>(() => values.Clear()); Assert.Throws<NotSupportedException>(() => values.Insert(0, 101)); Assert.Throws<NotSupportedException>(() => values.Remove(1)); Assert.Throws<NotSupportedException>(() => values.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => values[0] = 101); }); } [Fact] public static void IndexOfKey() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; int index = sortList2.IndexOfKey(key); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfKey("Non Existent Key")); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfKey(removedKey)); }); } [Fact] public static void IndexOfKey_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("key", () => sortList2.IndexOfKey(null)); // Key is null }); } [Fact] public static void IndexOfValue() { SortedList sortList1 = Helpers.CreateStringSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { string value = "Value_" + i; int index = sortList2.IndexOfValue(value); Assert.Equal(i, index); Assert.Equal(value, sortList2.GetByIndex(index)); } Assert.Equal(-1, sortList2.IndexOfValue("Non Existent Value")); string removedKey = "Key_01"; string removedValue = "Value_1"; sortList2.Remove(removedKey); Assert.Equal(-1, sortList2.IndexOfValue(removedValue)); Assert.Equal(-1, sortList2.IndexOfValue(null)); sortList2.Add("Key_101", null); Assert.NotEqual(-1, sortList2.IndexOfValue(null)); }); } [Fact] public static void IndexOfValue_SameValue() { var sortList1 = new SortedList(); sortList1.Add("Key_0", "Value_0"); sortList1.Add("Key_1", "Value_Same"); sortList1.Add("Key_2", "Value_Same"); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Equal(1, sortList2.IndexOfValue("Value_Same")); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(4)] [InlineData(5000)] public static void Capacity_Get_Set(int capacity) { var sortList = new SortedList(); sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); // Ensure nothing changes if we set capacity to the same value again sortList.Capacity = capacity; Assert.Equal(capacity, sortList.Capacity); } [Fact] public static void Capacity_Set_ShrinkingCapacity_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = sortList2.Count - 1); // Capacity < count }); } [Fact] public static void Capacity_Set_Invalid() { var sortList1 = new SortedList(); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("value", () => sortList2.Capacity = -1); // Capacity < 0 Assert.Throws<OutOfMemoryException>(() => sortList2.Capacity = int.MaxValue); // Capacity is too large }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] public static void Item_Get(int count) { SortedList sortList1 = Helpers.CreateStringSortedList(count); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < count; i++) { string key = "Key_" + i.ToString("D2"); string value = "Value_" + i; Assert.Equal(value, sortList2[key]); } Assert.Null(sortList2["No Such Key"]); string removedKey = "Key_01"; sortList2.Remove(removedKey); Assert.Null(sortList2[removedKey]); }); } [Fact] public static void Item_Get_DifferentCulture() { var sortList = new SortedList(); CultureInfo currentCulture = CultureInfo.DefaultThreadCurrentCulture; try { CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US"); var cultureNames = new string[] { "cs-CZ","da-DK","de-DE","el-GR","en-US", "es-ES","fi-FI","fr-FR","hu-HU","it-IT", "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL", "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR", "zh-CN","zh-HK","zh-TW" }; var installedCultures = new CultureInfo[cultureNames.Length]; var cultureDisplayNames = new string[installedCultures.Length]; int uniqueDisplayNameCount = 0; foreach (string cultureName in cultureNames) { var culture = new CultureInfo(cultureName); installedCultures[uniqueDisplayNameCount] = culture; cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName; sortList.Add(cultureDisplayNames[uniqueDisplayNameCount], culture); uniqueDisplayNameCount++; } // In Czech ch comes after h if the comparer changes based on the current culture of the thread // we will not be able to find some items CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("cs-CZ"); for (int i = 0; i < uniqueDisplayNameCount; i++) { Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]); } } catch (CultureNotFoundException) { } finally { CultureInfo.DefaultThreadCurrentCulture = currentCulture; } } [Fact] public static void Item_Set() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Change existing keys for (int i = 0; i < sortList2.Count; i++) { sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); // Make sure nothing bad happens when we try to set the key to its current valeu sortList2[i] = i + 1; Assert.Equal(i + 1, sortList2[i]); } // Add new keys sortList2[101] = 2048; Assert.Equal(2048, sortList2[101]); sortList2[102] = null; Assert.Equal(null, sortList2[102]); }); } [Fact] public static void Item_Set_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("key", () => sortList2[null] = 101); // Key is null }); } [Fact] public static void RemoveAt() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.RemoveAt(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } }); } [Fact] public static void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(-1)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.RemoveAt(sortList2.Count)); // Index >= count }); } [Fact] public static void Remove() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { // Remove from the end for (int i = sortList2.Count - 1; i >= 0; i--) { sortList2.Remove(i); Assert.False(sortList2.ContainsKey(i)); Assert.False(sortList2.ContainsValue(i)); Assert.Equal(i, sortList2.Count); } sortList2.Remove(101); // No such key }); } [Fact] public static void Remove_NullKey_ThrowsArgumentNullException() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentNullException>("key", () => sortList2.Remove(null)); // Key is null }); } [Fact] public static void SetByIndex() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < sortList2.Count; i++) { sortList2.SetByIndex(i, i + 1); Assert.Equal(i + 1, sortList2.GetByIndex(i)); } }); } [Fact] public static void SetByIndex_InvalidIndex_ThrowsArgumentOutOfRangeExeption() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(-1, 101)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => sortList2.SetByIndex(sortList2.Count, 101)); // Index >= list.Count }); } [Fact] public static void Synchronized_IsSynchronized() { SortedList sortList = SortedList.Synchronized(new SortedList()); Assert.True(sortList.IsSynchronized); } [Fact] public static void Synchronized_NullList_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("list", () => SortedList.Synchronized(null)); // List is null } [Fact] public static void TrimToSize() { SortedList sortList1 = Helpers.CreateIntSortedList(100); Helpers.PerformActionOnAllSortedListWrappers(sortList1, sortList2 => { for (int i = 0; i < 10; i++) { sortList2.RemoveAt(0); } sortList2.TrimToSize(); Assert.Equal(sortList2.Count, sortList2.Capacity); sortList2.Clear(); sortList2.TrimToSize(); Assert.Equal(0, sortList2.Capacity); }); } private class Foo { public string StringValue { get; set; } = "Hello World"; } private class CustomComparer : IComparer { public int Compare(object obj1, object obj2) => -string.Compare(obj1.ToString(), obj2.ToString()); } } public class SortedList_SyncRootTests { private SortedList _sortListDaughter; private SortedList _sortListGrandDaughter; private const int NumberOfElements = 100; [Fact] [OuterLoop] public void GetSyncRootBasic() { // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother SortedList // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var sortListMother = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListMother.Add("Key_" + i, "Value_" + i); } Assert.Equal(sortListMother.SyncRoot.GetType(), typeof(object)); SortedList sortListSon = SortedList.Synchronized(sortListMother); _sortListGrandDaughter = SortedList.Synchronized(sortListSon); _sortListDaughter = SortedList.Synchronized(sortListMother); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListMother.SyncRoot, sortListSon.SyncRoot); Assert.Equal(_sortListGrandDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(_sortListDaughter.SyncRoot, sortListMother.SyncRoot); Assert.Equal(sortListSon.SyncRoot, sortListMother.SyncRoot); //we are going to rumble with the SortedLists with some threads var workers = new Task[4]; for (int i = 0; i < workers.Length; i += 2) { var name = "Thread_worker_" + i; var action1 = new Action(() => AddMoreElements(name)); var action2 = new Action(RemoveElements); workers[i] = Task.Run(action1); workers[i + 1] = Task.Run(action2); } Task.WaitAll(workers); // Checking time // Now lets see how this is done. // Either there are some elements or none var sortListPossible = new SortedList(); for (int i = 0; i < NumberOfElements; i++) { sortListPossible.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < workers.Length; i++) { sortListPossible.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } //lets check the values if IDictionaryEnumerator enumerator = sortListMother.GetEnumerator(); while (enumerator.MoveNext()) { Assert.True(sortListPossible.ContainsKey(enumerator.Key)); Assert.True(sortListPossible.ContainsValue(enumerator.Value)); } } private void AddMoreElements(string threadName) { _sortListGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _sortListDaughter.Clear(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 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. */ //#define Debug using System; using System.Net; using System.Reflection; using System.Threading; using OpenMetaverse; using Aurora.Framework; namespace OpenSim.Region.ClientStack.LindenUDP { #region Delegates /// <summary> /// Fired when updated networking stats are produced for this client /// </summary> /// <param name = "inPackets">Number of incoming packets received since this /// event was last fired</param> /// <param name = "outPackets">Number of outgoing packets sent since this /// event was last fired</param> /// <param name = "unAckedBytes">Current total number of bytes in packets we /// are waiting on ACKs for</param> public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes); /// <summary> /// Fired when the queue for one or more packet categories is empty. This /// event can be hooked to put more data on the empty queues /// </summary> public delegate void QueueEmpty(object o); #endregion Delegates public class UDPprioQueue { public int Count; public int nlevels; public int[] promotioncntr; public int promotionratemask; public Aurora.Framework.LocklessQueue<object>[] queues; public UDPprioQueue(int NumberOfLevels, int PromRateMask) { // PromRatemask: 0x03 promotes on each 4 calls, 0x1 on each 2 calls etc nlevels = NumberOfLevels; queues = new Aurora.Framework.LocklessQueue<object>[nlevels]; promotioncntr = new int[nlevels]; for (int i = 0; i < nlevels; i++) { queues[i] = new Aurora.Framework.LocklessQueue<object>(); promotioncntr[i] = 0; } promotionratemask = PromRateMask; } public bool Enqueue(int prio, object o) // object so it can be a complex info with methods to call etc to get packets on dequeue { if (prio < 0 || prio >= nlevels) // safe than sorrow return false; queues[prio].Enqueue(o); // store it in its level Interlocked.Increment(ref Count); Interlocked.Increment(ref promotioncntr[prio]); if ((promotioncntr[prio] & promotionratemask) == 0) // keep top free of lower priority things // time to move objects up in priority // so they don't get stalled if high trafic on higher levels { int i = prio; while (--i >= 0) { object ob; if (queues[i].Dequeue(out ob)) queues[i + 1].Enqueue(ob); } } return true; } public bool Dequeue(out OutgoingPacket pack) { int i = nlevels; while (--i >= 0) // go down levels looking for data { object o; if (!queues[i].Dequeue(out o)) continue; if (!(o is OutgoingPacket)) continue; pack = (OutgoingPacket) o; Interlocked.Decrement(ref Count); return true; // else do call to a funtion that will return the packet or whatever } pack = null; return false; } } /// <summary> /// Tracks state for a client UDP connection and provides client-specific methods /// </summary> public sealed class LLUDPClient { /// <summary> /// Percentage of the task throttle category that is allocated to avatar and prim /// state updates /// </summary> private const float STATE_TASK_PERCENTAGE = 0.3f; private const float TRANSFER_ASSET_PERCENTAGE = 0.9f; private const float AVATAR_INFO_STATE_PERCENTAGE = 0.5f; private const int MAXPERCLIENTRATE = 625000; private const int MINPERCLIENTRATE = 6250; private const int STARTPERCLIENTRATE = 25000; private const int MAX_PACKET_SKIP_RATE = 4; /// <summary> /// AgentID for this client /// </summary> public readonly UUID AgentID; /// <summary> /// Circuit code that this client is connected on /// </summary> public readonly uint CircuitCode; /// <summary> /// Packets we have sent that need to be ACKed by the client /// </summary> public readonly UnackedPacketCollection NeedAcks = new UnackedPacketCollection(); /// <summary> /// Sequence numbers of packets we've received (for duplicate checking) /// </summary> public readonly IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(200); // private readonly TokenBucket[] m_throttleCategories; /// <summary> /// Throttle buckets for each packet category /// </summary> /// <summary> /// Outgoing queues for throttled packets /// </summary> // private readonly Aurora.Framework.LocklessQueue<OutgoingPacket>[] m_packetOutboxes = new Aurora.Framework.LocklessQueue<OutgoingPacket>[(int)ThrottleOutPacketType.Count]; private readonly int[] PacketsCounts = new int[(int) ThrottleOutPacketType.Count]; /// <summary> /// ACKs that are queued up, waiting to be sent to the client /// </summary> public readonly Aurora.Framework.LocklessQueue<uint> PendingAcks = new Aurora.Framework.LocklessQueue<uint>(); private readonly int[] Rates; /// <summary> /// The remote address of the connected client /// </summary> public readonly IPEndPoint RemoteEndPoint; private readonly int m_defaultRTO = 1000; private readonly int m_maxRTO = 20000; private readonly UDPprioQueue m_outbox = new UDPprioQueue(8, 0x01); // 8 priority levels (7 max , 0 lowest), autopromotion on every 2 enqueues /// <summary> /// Throttle bucket for this agent's connection /// </summary> private readonly TokenBucket m_throttle; /// <summary> /// A reference to the LLUDPServer that is managing this client /// </summary> private readonly LLUDPServer m_udpServer; /// <summary> /// Number of bytes received since the last acknowledgement was sent out. This is used /// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2) /// </summary> public int BytesSinceLastACK; /// <summary> /// Current ping sequence number /// </summary> public byte CurrentPingSequence; /// <summary> /// Current packet sequence number /// </summary> public int CurrentSequence; /// <summary> /// True when this connection is alive, otherwise false /// </summary> public bool IsConnected = true; /// <summary> /// True when this connection is paused, otherwise false /// </summary> public bool IsPaused; public int[] MapCatsToPriority = new int[(int) ThrottleOutPacketType.Count]; /// <summary> /// Number of packets received from this client /// </summary> public int PacketsReceived; /// <summary> /// Total byte count of unacked packets sent to this client /// </summary> public int PacketsResent; /// <summary> /// Number of packets sent to this client /// </summary> public int PacketsSent; /// <summary> /// Retransmission timeout. Packets that have not been acknowledged in this number of /// milliseconds or longer will be resent /// </summary> /// <remarks> /// Calculated from <seealso cref = "SRTT" /> and <seealso cref = "RTTVAR" /> using the /// guidelines in RFC 2988 /// </remarks> public int RTO; /// <summary> /// Round-trip time variance. Measures the consistency of round-trip times /// </summary> public float RTTVAR; /// <summary> /// Smoothed round-trip time. A smoothed average of the round-trip time for sending a /// reliable packet to the client and receiving an ACK /// </summary> public float SRTT; /// <summary> /// Environment.TickCount when the last packet was received for this client /// </summary> public int TickLastPacketReceived; private int TotalRateMin; private int TotalRateRequested; /// <summary> /// Total byte count of unacked packets sent to this client /// </summary> public int UnackedBytes; /// <summary> /// Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired /// </summary> private int m_nextOnQueueEmpty = 1; private OutgoingPacket m_nextOutPacket; /// <summary> /// Caches packed throttle information /// </summary> private byte[] m_packedThrottles; /// <summary> /// Total number of received packets that we have reported to the OnPacketStats event(s) /// </summary> private int m_packetsReceivedReported; /// <summary> /// Total number of sent packets that we have reported to the OnPacketStats event(s) /// </summary> private int m_packetsSentReported; /// <summary> /// Default constructor /// </summary> /// <param name = "server">Reference to the UDP server this client is connected to</param> /// <param name = "rates">Default throttling rates and maximum throttle limits</param> /// <param name = "parentThrottle">Parent HTB (hierarchical token bucket) /// that the child throttles will be governed by</param> /// <param name = "circuitCode">Circuit code for this connection</param> /// <param name = "agentID">AgentID for the connected agent</param> /// <param name = "remoteEndPoint">Remote endpoint for this connection</param> /// <param name="defaultRTO"></param> /// <param name="maxRTO"></param> public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO) { AgentID = agentID; RemoteEndPoint = remoteEndPoint; CircuitCode = circuitCode; m_udpServer = server; if (defaultRTO != 0) m_defaultRTO = defaultRTO; if (maxRTO != 0) m_maxRTO = maxRTO; // Create a token bucket throttle for this client that has the scene token bucket as a parent m_throttle = new TokenBucket(parentThrottle, rates.TotalLimit, 0); // remember the rates the client requested Rates = new int[(int) ThrottleOutPacketType.Count]; for (int i = 0; i < (int) ThrottleOutPacketType.Count; i++) { PacketsCounts[i] = 0; } //Set the priorities for the different packet types //Higher is more important MapCatsToPriority[(int) ThrottleOutPacketType.Resend] = 7; MapCatsToPriority[(int) ThrottleOutPacketType.Land] = 1; MapCatsToPriority[(int) ThrottleOutPacketType.Wind] = 0; MapCatsToPriority[(int) ThrottleOutPacketType.Cloud] = 0; MapCatsToPriority[(int) ThrottleOutPacketType.Task] = 4; MapCatsToPriority[(int) ThrottleOutPacketType.Texture] = 2; MapCatsToPriority[(int) ThrottleOutPacketType.Asset] = 3; MapCatsToPriority[(int) ThrottleOutPacketType.Transfer] = 5; MapCatsToPriority[(int) ThrottleOutPacketType.State] = 5; MapCatsToPriority[(int) ThrottleOutPacketType.AvatarInfo] = 6; MapCatsToPriority[(int) ThrottleOutPacketType.OutBand] = 7; // Default the retransmission timeout to one second RTO = m_defaultRTO; // Initialize this to a sane value to prevent early disconnects TickLastPacketReceived = Environment.TickCount & Int32.MaxValue; } /// <summary> /// Fired when updated networking stats are produced for this client /// </summary> public event PacketStats OnPacketStats; /// <summary> /// Fired when the queue for a packet category is empty. This event can be /// hooked to put more data on the empty queue /// </summary> public event QueueEmpty OnQueueEmpty; /// <summary> /// Shuts down this client connection /// </summary> public void Shutdown() { IsConnected = false; for (int i = 0; i < (int) ThrottleOutPacketType.Count; i++) { PacketsCounts[i] = 0; } OnPacketStats = null; OnQueueEmpty = null; } public string GetStats() { return string.Format( "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}", PacketsReceived, PacketsSent, PacketsResent, UnackedBytes, PacketsCounts[(int) ThrottleOutPacketType.Resend], PacketsCounts[(int) ThrottleOutPacketType.Land], PacketsCounts[(int) ThrottleOutPacketType.Wind], PacketsCounts[(int) ThrottleOutPacketType.Cloud], PacketsCounts[(int) ThrottleOutPacketType.Task], PacketsCounts[(int) ThrottleOutPacketType.Texture], PacketsCounts[(int) ThrottleOutPacketType.Asset], PacketsCounts[(int) ThrottleOutPacketType.State], PacketsCounts[(int) ThrottleOutPacketType.OutBand] ); } public void SendPacketStats() { PacketStats callback = OnPacketStats; if (callback != null) { int newPacketsReceived = PacketsReceived - m_packetsReceivedReported; int newPacketsSent = PacketsSent - m_packetsSentReported; callback(newPacketsReceived, newPacketsSent, UnackedBytes); m_packetsReceivedReported += newPacketsReceived; m_packetsSentReported += newPacketsSent; } } public void SlowDownSend() { float tmp = m_throttle.MaxBurst*0.95f; if (tmp < TotalRateMin) tmp = TotalRateMin; m_throttle.MaxBurst = (int) tmp; m_throttle.DripRate = (int) tmp; } public void SetThrottles(byte[] throttleData) { byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7*4]; Buffer.BlockCopy(throttleData, 0, newData, 0, 7*4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i*4, 4); adjData = newData; } else { adjData = throttleData; } // 0.125f converts from bits to bytes int resend = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int land = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int wind = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int cloud = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int task = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int texture = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); pos += 4; int asset = (int) (BitConverter.ToSingle(adjData, pos)*0.125f); int total = resend + land + wind + cloud + task + texture + asset; // These are subcategories of task that we allocate a percentage to int state = (int) (task*STATE_TASK_PERCENTAGE); task -= state; int transfer = (int) (asset*TRANSFER_ASSET_PERCENTAGE); asset -= transfer; // avatar info cames out from state int avatarinfo = (int) (state*AVATAR_INFO_STATE_PERCENTAGE); state -= avatarinfo; // int total = resend + land + wind + cloud + task + texture + asset + state + avatarinfo; // Make sure none of the throttles are set below our packet MTU, // otherwise a throttle could become permanently clogged Rates[(int) ThrottleOutPacketType.Resend] = resend; Rates[(int) ThrottleOutPacketType.Land] = land; Rates[(int) ThrottleOutPacketType.Wind] = wind; Rates[(int) ThrottleOutPacketType.Cloud] = cloud; Rates[(int) ThrottleOutPacketType.Task] = task + state + avatarinfo; Rates[(int) ThrottleOutPacketType.Texture] = texture; Rates[(int) ThrottleOutPacketType.Asset] = asset + transfer; Rates[(int) ThrottleOutPacketType.State] = state; TotalRateRequested = total; TotalRateMin = (int) (total*0.1); if (TotalRateMin < MINPERCLIENTRATE) TotalRateMin = MINPERCLIENTRATE; total = TotalRateMin; // let it grow slowlly //MainConsole.Instance.WarnFormat("[LLUDPCLIENT]: {0} is setting throttles. Resend={1}, Land={2}, Wind={3}, Cloud={4}, Task={5}, Texture={6}, Asset={7}, State={8}, AvatarInfo={9}, Transfer={10}, TaskFull={11}, Total={12}", // AgentID, resend, land, wind, cloud, task, texture, asset, state, avatarinfo, transfer, task + state + avatarinfo, total); // Update the token buckets with new throttle values TokenBucket bucket = m_throttle; bucket.DripRate = total; bucket.MaxBurst = total; // Reset the packed throttles cached data m_packedThrottles = null; } public byte[] GetThrottlesPacked(float multiplier) { byte[] data = m_packedThrottles; if (data == null) { data = new byte[7*4]; int i = 0; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Resend]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Land]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Wind]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Cloud]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Task]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Texture]*8*multiplier), 0, data, i, 4); i += 4; Buffer.BlockCopy(Utils.FloatToBytes((float) Rates[(int) ThrottleOutPacketType.Asset]*8*multiplier), 0, data, i, 4); m_packedThrottles = data; } return data; } public bool EnqueueOutgoing(OutgoingPacket packet) { int category = (int) packet.Category; if (category >= 0 && category < (int) ThrottleOutPacketType.Count) { //All packets are enqueued, except those that don't have a queue int prio = MapCatsToPriority[category]; m_outbox.Enqueue(prio, packet); return true; } // We don't have a token bucket for this category, // so it will not be queued and sent immediately return false; } /// <summary> /// tries to send queued packets /// </summary> /// <remarks> /// This function is only called from a synchronous loop in the /// UDPServer so we don't need to bother making this thread safe /// </remarks> /// <returns>True if any packets were sent, otherwise false</returns> public bool DequeueOutgoing(int MaxNPacks) { bool packetSent = false; for (int i = 0; i < MaxNPacks; i++) { OutgoingPacket packet; if (m_nextOutPacket != null) { packet = m_nextOutPacket; if (m_throttle.RemoveTokens(packet.Buffer.DataLength)) { // Send the packet m_udpServer.SendPacketFinal(packet); m_nextOutPacket = null; packetSent = true; } } // No dequeued packet waiting to be sent, try to pull one off // this queue else if (m_outbox.Dequeue(out packet)) { MainConsole.Instance.Output(AgentID + " - " + packet.Packet.Type, "Verbose"); // A packet was pulled off the queue. See if we have // enough tokens in the bucket to send it out if (packet.Category == ThrottleOutPacketType.OutBand || m_throttle.RemoveTokens(packet.Buffer.DataLength)) { packetSent = true; //Send the packet PacketsCounts[(int) packet.Category] += packet.Packet.Length; m_udpServer.SendPacketFinal(packet); PacketsSent++; } else { m_nextOutPacket = packet; break; } } else break; } if (packetSent) { if (m_throttle.MaxBurst < TotalRateRequested) { float tmp = m_throttle.MaxBurst*1.005f; m_throttle.DripRate = (int) tmp; m_throttle.MaxBurst = (int) tmp; } } if (m_nextOnQueueEmpty != 0 && Util.EnvironmentTickCountSubtract(m_nextOnQueueEmpty) >= 0) { // Use a value of 0 to signal that FireQueueEmpty is running m_nextOnQueueEmpty = 0; // Asynchronously run the callback int ptmp = m_outbox.queues[MapCatsToPriority[(int) ThrottleOutPacketType.Task]].Count; int atmp = m_outbox.queues[MapCatsToPriority[(int) ThrottleOutPacketType.AvatarInfo]].Count; int ttmp = m_outbox.queues[MapCatsToPriority[(int) ThrottleOutPacketType.Texture]].Count; int[] arg = {ptmp, atmp, ttmp}; Util.FireAndForget(FireQueueEmpty, arg); } return packetSent; } public int GetCurTexPacksInQueue() { return m_outbox.queues[MapCatsToPriority[(int) ThrottleOutPacketType.Texture]].Count; } public int GetCurTaskPacksInQueue() { return m_outbox.queues[MapCatsToPriority[(int) ThrottleOutPacketType.Task]].Count; } /// <summary> /// Called when an ACK packet is received and a round-trip time for a /// packet is calculated. This is used to calculate the smoothed /// round-trip time, round trip time variance, and finally the /// retransmission timeout /// </summary> /// <param name = "r">Round-trip time of a single packet and its /// acknowledgement</param> public void UpdateRoundTrip(float r) { const float ALPHA = 0.125f; const float BETA = 0.25f; const float K = 4.0f; if (RTTVAR == 0.0f) { // First RTT measurement SRTT = r; RTTVAR = r*0.5f; } else { // Subsequence RTT measurement RTTVAR = (1.0f - BETA)*RTTVAR + BETA*Math.Abs(SRTT - r); SRTT = (1.0f - ALPHA)*SRTT + ALPHA*r; } int rto = (int) (SRTT + Math.Max(m_udpServer.TickCountResolution, K*RTTVAR)); // Clamp the retransmission timeout to manageable values rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO); RTO = rto; //MainConsole.Instance.Debug("[LLUDPCLIENT]: Setting agent " + this.Agent.FullName + "'s RTO to " + RTO + "ms with an RTTVAR of " + // RTTVAR + " based on new RTT of " + r + "ms"); } /// <summary> /// Exponential backoff of the retransmission timeout, per section 5.5 /// of RFC 2988 /// </summary> public void BackoffRTO() { // Reset SRTT and RTTVAR, we assume they are bogus since things // didn't work out and we're backing off the timeout SRTT = 0.0f; RTTVAR = 0.0f; // Double the retransmission timeout RTO = Math.Min(RTO*2, m_maxRTO); } /// <summary> /// Fires the OnQueueEmpty callback and sets the minimum time that it /// can be called again /// </summary> /// <param name = "o">Throttle categories to fire the callback for, /// stored as an object to match the WaitCallback delegate /// signature</param> private void FireQueueEmpty(object o) { const int MIN_CALLBACK_MS = 30; QueueEmpty callback = OnQueueEmpty; int start = Util.EnvironmentTickCount(); if (callback != null) { try { callback(o); } catch (Exception e) { MainConsole.Instance.Error("[LLUDPCLIENT]: OnQueueEmpty() threw an exception: " + e.Message, e); } } m_nextOnQueueEmpty = start + MIN_CALLBACK_MS; // if (m_nextOnQueueEmpty == 0) // m_nextOnQueueEmpty = 1; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using NPOI.Util; /** * The common object data record is used to store all common preferences for an excel object. * NOTE: This source is automatically generated please do not modify this file. Either subclass or * Remove the record in src/records/definitions. * @author Glen Stampoultzis (glens at apache.org) */ public enum CommonObjectType:short { Group = 0, Line = 1, Rectangle = 2, Oval = 3, Arc = 4, Chart = 5, Text = 6, Button = 7, Picture = 8, Polygon = 9, Reserved1 = 10, Checkbox = 11, OptionButton = 12, EditBox = 13, Label = 14, DialogBox = 15, Spinner = 16, ScrollBar = 17, ListBox = 18, GroupBox = 19, ComboBox = 20, Reserved2 = 21, Reserved3 = 22, Reserved4 = 23, Reserved5 = 24, Comment = 25, Reserved6 = 26, Reserved7 = 27, Reserved8 = 28, Reserved9 = 29, MicrosoftOfficeDrawing = 30, } public class CommonObjectDataSubRecord : SubRecord { public const short sid = 0x15; private short field_1_objectType; private int field_2_objectId; private short field_3_option; private BitField locked = BitFieldFactory.GetInstance(0x1); private BitField printable = BitFieldFactory.GetInstance(0x10); private BitField autoFill = BitFieldFactory.GetInstance(0x2000); private BitField autoline = BitFieldFactory.GetInstance(0x4000); private int field_4_reserved1; private int field_5_reserved2; private int field_6_reserved3; public CommonObjectDataSubRecord() { } /** * Constructs a CommonObjectData record and Sets its fields appropriately. * * @param in the RecordInputstream to Read the record from */ public CommonObjectDataSubRecord(ILittleEndianInput in1, int size) { if (size != 18) { throw new RecordFormatException("Expected size 18 but got (" + size + ")"); } field_1_objectType = in1.ReadShort(); field_2_objectId = in1.ReadUShort(); field_3_option = in1.ReadShort(); field_4_reserved1 = in1.ReadInt(); field_5_reserved2 = in1.ReadInt(); field_6_reserved3 = in1.ReadInt(); } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[ftCmo]\n"); buffer.Append(" .objectType = ") .Append("0x").Append(HexDump.ToHex((short)ObjectType)) .Append(" (").Append(ObjectType).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .objectId = ") .Append("0x").Append(HexDump.ToHex(ObjectId)) .Append(" (").Append(ObjectId).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .option = ") .Append("0x").Append(HexDump.ToHex(Option)) .Append(" (").Append(Option).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .locked = ").Append(IsLocked).Append('\n'); buffer.Append(" .printable = ").Append(IsPrintable).Append('\n'); buffer.Append(" .autoFill = ").Append(IsAutoFill).Append('\n'); buffer.Append(" .autoline = ").Append(IsAutoline).Append('\n'); buffer.Append(" .reserved1 = ") .Append("0x").Append(HexDump.ToHex(Reserved1)) .Append(" (").Append(Reserved1).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .reserved2 = ") .Append("0x").Append(HexDump.ToHex(Reserved2)) .Append(" (").Append(Reserved2).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append(" .reserved3 = ") .Append("0x").Append(HexDump.ToHex(Reserved3)) .Append(" (").Append(Reserved3).Append(" )"); buffer.Append(Environment.NewLine); buffer.Append("[/ftCmo]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(sid); out1.WriteShort(DataSize); out1.WriteShort(field_1_objectType); out1.WriteShort(field_2_objectId); out1.WriteShort(field_3_option); out1.WriteInt(field_4_reserved1); out1.WriteInt(field_5_reserved2); out1.WriteInt(field_6_reserved3); } /** * Size of record (exluding 4 byte header) */ public override int DataSize { get { return 2 + 2 + 2 + 4 + 4 + 4; } } public override short Sid { get { return sid; } } public override Object Clone() { CommonObjectDataSubRecord rec = new CommonObjectDataSubRecord(); rec.field_1_objectType = field_1_objectType; rec.field_2_objectId = field_2_objectId; rec.field_3_option = field_3_option; rec.field_4_reserved1 = field_4_reserved1; rec.field_5_reserved2 = field_5_reserved2; rec.field_6_reserved3 = field_6_reserved3; return rec; } /** * Get the object type field for the CommonObjectData record. */ public CommonObjectType ObjectType { get { return (CommonObjectType)field_1_objectType; } set { this.field_1_objectType = (short)value; } } /** * Get the object id field for the CommonObjectData record. */ public int ObjectId { get { return field_2_objectId; } set { this.field_2_objectId = value; } } /** * Get the option field for the CommonObjectData record. */ public short Option { get { return field_3_option; } set { this.field_3_option = value; } } /** * Get the reserved1 field for the CommonObjectData record. */ public int Reserved1 { get { return field_4_reserved1; } set { this.field_4_reserved1 = value; } } /** * Get the reserved2 field for the CommonObjectData record. */ public int Reserved2 { get { return field_5_reserved2; } set { this.field_5_reserved2 = value; } } /** * Get the reserved3 field for the CommonObjectData record. */ public int Reserved3 { get { return field_6_reserved3; } set { this.field_6_reserved3 = value; } } /** * true if object is locked when sheet has been protected * @return the locked field value. */ public bool IsLocked { get { return locked.IsSet(field_3_option); } set { field_3_option = locked.SetShortBoolean(field_3_option, value); } } /** * object appears when printed * @return the printable field value. */ public bool IsPrintable { get { return printable.IsSet(field_3_option); } set { field_3_option = printable.SetShortBoolean(field_3_option, value); } } /** * whether object uses an automatic Fill style * @return the autoFill field value. */ public bool IsAutoFill { get { return autoFill.IsSet(field_3_option); } set { field_3_option = autoFill.SetShortBoolean(field_3_option, value); } } /** * whether object uses an automatic line style * @return the autoline field value. */ public bool IsAutoline { get { return autoline.IsSet(field_3_option); } set { field_3_option = autoline.SetShortBoolean(field_3_option, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using System.Numerics; using Xunit; namespace System.Security.Cryptography.Rsa.Tests { public partial class ImportExport { [Fact] public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = RSAFactory.Create()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); } [Fact] public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParameters = TestData.DiminishedDPParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(diminishedDPParameters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(diminishedDPParameters, exported); } [Fact] public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = RSAFactory.Create()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(imported, exported); } } [Fact] public static void UnusualExponentImportExport() { // Most choices for the Exponent value in an RSA key use a Fermat prime. // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same // representation in both big- and little-endian. // // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1). // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export. RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(unusualExponentParameters); exported = rsa.ExportParameters(true); } // Exponent is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(unusualExponentParameters, exported); } [Fact] public static void ImportExport1032() { RSAParameters imported = TestData.RSA1032Parameters; RSAParameters exported; RSAParameters exportedPublic; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); exported = rsa.ExportParameters(true); exportedPublic = rsa.ExportParameters(false); } AssertKeyEquals(imported, exported); Assert.Equal(exportedPublic.Modulus, imported.Modulus); Assert.Equal(exportedPublic.Exponent, imported.Exponent); Assert.Null(exportedPublic.D); } [Fact] public static void ImportReset() { using (RSA rsa = RSAFactory.Create()) { RSAParameters exported = rsa.ExportParameters(true); RSAParameters imported; // Ensure that we cause the KeySize value to change. if (rsa.KeySize == 1024) { imported = TestData.RSA2048Params; } else { imported = TestData.RSA1024Params; } Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize); Assert.NotEqual(imported.Modulus, exported.Modulus); rsa.ImportParameters(imported); Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize); exported = rsa.ExportParameters(true); AssertKeyEquals(imported, exported); } } [Fact] public static void ImportPrivateExportPublic() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPublic = rsa.ExportParameters(false); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); } } [Fact] public static void MultiExport() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPrivate = rsa.ExportParameters(true); RSAParameters exportedPrivate2 = rsa.ExportParameters(true); RSAParameters exportedPublic = rsa.ExportParameters(false); RSAParameters exportedPublic2 = rsa.ExportParameters(false); RSAParameters exportedPrivate3 = rsa.ExportParameters(true); RSAParameters exportedPublic3 = rsa.ExportParameters(false); AssertKeyEquals(imported, exportedPrivate); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); AssertKeyEquals(exportedPrivate, exportedPrivate2); AssertKeyEquals(exportedPrivate, exportedPrivate3); AssertKeyEquals(exportedPublic, exportedPublic2); AssertKeyEquals(exportedPublic, exportedPublic3); } } [Fact] public static void PublicOnlyPrivateExport() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true)); } } [Fact] public static void ImportNoExponent() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, }; using (RSA rsa = RSAFactory.Create()) { if (rsa is RSACng && PlatformDetection.IsFullFramework) AssertExtensions.Throws<ArgumentException>(null, () => rsa.ImportParameters(imported)); else Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoModulus() { RSAParameters imported = new RSAParameters { Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { if (rsa is RSACng && PlatformDetection.IsFullFramework) AssertExtensions.Throws<ArgumentException>(null, () => rsa.ImportParameters(imported)); else Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] #if TESTING_CNG_IMPLEMENTATION [ActiveIssue(18882, TargetFrameworkMonikers.NetFramework)] #endif public static void ImportNoDP() { // Because RSAParameters is a struct, this is a copy, // so assigning DP is not destructive to other tests. RSAParameters imported = TestData.RSA1024Params; imported.DP = null; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } internal static void AssertKeyEquals(in RSAParameters expected, in RSAParameters actual) { Assert.Equal(expected.Modulus, actual.Modulus); Assert.Equal(expected.Exponent, actual.Exponent); Assert.Equal(expected.P, actual.P); Assert.Equal(expected.DP, actual.DP); Assert.Equal(expected.Q, actual.Q); Assert.Equal(expected.DQ, actual.DQ); Assert.Equal(expected.InverseQ, actual.InverseQ); if (expected.D == null) { Assert.Null(actual.D); } else { Assert.NotNull(actual.D); // If the value matched expected, take that as valid and shortcut the math. // If it didn't, we'll test that the value is at least legal. if (!expected.D.SequenceEqual(actual.D)) { VerifyDValue(actual); } } } internal static void ValidateParameters(ref RSAParameters rsaParams) { Assert.NotNull(rsaParams.Modulus); Assert.NotNull(rsaParams.Exponent); // Key compatibility: RSA as an algorithm is achievable using just N (Modulus), // E (public Exponent) and D (private exponent). Having all of the breakdowns // of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider // have thrown if D is provided and the rest of the private key values are not. // So, here we're going to assert that none of them were null for private keys. if (rsaParams.D == null) { Assert.Null(rsaParams.P); Assert.Null(rsaParams.DP); Assert.Null(rsaParams.Q); Assert.Null(rsaParams.DQ); Assert.Null(rsaParams.InverseQ); } else { Assert.NotNull(rsaParams.P); Assert.NotNull(rsaParams.DP); Assert.NotNull(rsaParams.Q); Assert.NotNull(rsaParams.DQ); Assert.NotNull(rsaParams.InverseQ); } } private static void VerifyDValue(in RSAParameters rsaParams) { if (rsaParams.P == null) { return; } // Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1 // is true. // // This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)), // because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will // still work through this formula. BigInteger p = PositiveBigInteger(rsaParams.P); BigInteger q = PositiveBigInteger(rsaParams.Q); BigInteger e = PositiveBigInteger(rsaParams.Exponent); BigInteger d = PositiveBigInteger(rsaParams.D); BigInteger lambda = LeastCommonMultiple(p - 1, q - 1); BigInteger modProduct = (d * e) % lambda; Assert.Equal(BigInteger.One, modProduct); } private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b) { BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b); return BigInteger.Abs(a) / gcd * BigInteger.Abs(b); } private static BigInteger PositiveBigInteger(byte[] bigEndianBytes) { byte[] littleEndianBytes; if (bigEndianBytes[0] >= 0x80) { // Insert a padding 00 byte so the number is treated as positive. littleEndianBytes = new byte[bigEndianBytes.Length + 1]; Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length); } else { littleEndianBytes = (byte[])bigEndianBytes.Clone(); } Array.Reverse(littleEndianBytes); return new BigInteger(littleEndianBytes); } } }
//#define ASTAR_NoTagPenalty using System; using Pathfinding; using System.Collections.Generic; namespace Pathfinding.Nodes { public class GridNode : Node { //Flags used //last 8 bits - see Node class //First 8 bits for connectivity info inside this grid //Size = [Node, 28 bytes] + 4 = 32 bytes /** First 24 bits used for the index value of this node in the graph specified by the last 8 bits. \see #gridGraphs */ protected int indices; /** Internal list of grid graphs. * Used for fast typesafe lookup of graphs. */ public static GridGraph[] gridGraphs; /** Returns if this node has any valid grid connections */ public bool HasAnyGridConnections () { return (flags & 0xFF) != 0; } /** Has connection to neighbour \a i. * The neighbours are the up to 8 grid neighbours of this node. * \see SetConnection */ public bool GetConnection (int i) { return ((flags >> i) & 1) == 1; } /** Set connection to neighbour \a i. * \param i Connection to set [0...7] * \param value 1 or 0 (true/false) * The neighbours are the up to 8 grid neighbours of this node * \see GetConnection */ public void SetConnection (int i, int value) { flags = flags & ~(1 << i) | (value << i); } /** Sets a connection without clearing the previous value. * Faster if you are setting all connections at once and have cleared the value before calling this function * \see SetConnection */ public void SetConnectionRaw (int i, int value) { flags = flags | (value << i); } /** Returns index of which GridGraph this node is contained in */ public int GetGridIndex () { return indices >> 24; } /** Returns the grid index in the graph */ public int GetIndex () { return indices & 0xFFFFFF; } /** Set the grid index in the graph */ public void SetIndex (int i) { indices &= ~0xFFFFFF; indices |= i; } /** Sets the index of which GridGraph this node is contained in. * Only changes lookup variables, does not actually move the node to another graph. */ public void SetGridIndex (int gridIndex) { indices &= 0xFFFFFF; indices |= gridIndex << 24; } /** Returns if walkable before erosion. * Identical to Pathfinding.Node.Bit15 but should be used when possible to make the code more readable */ public bool WalkableErosion { get { return Bit15; }//return ((flags >> 15) & 1) != 0 ? true : false; } set { Bit15 = value; }//flags = (flags & ~(1 << 15)) | (value?1:0 << 15); } } /*public override bool ContainsConnection (Node node, Path p) { if (!node.IsWalkable (p)) { return false; } if (connections != null) { for (int i=0;i<connections.Length;i++) { if (connections[i] == node) { return true; } } } int index = indices & 0xFFFFFF; int[] neighbourOffsets = gridGraphs[indices >> 24].neighbourOffsets; GridNode[] nodes = gridGraphs[indices >> 24].nodes; for (int i=0;i<8;i++) { if (((flags >> i) & 1) == 1) { Node other = nodes[index+neighbourOffsets[i]]; if (other == node) { return true; } } } return false; }*/ /** Updates the grid connections of this node and it's neighbour nodes to reflect walkability of this node */ public void UpdateGridConnections () { GridGraph graph = gridGraphs[indices >> 24]; int index = GetIndex(); int x = index % graph.width; int z = index/graph.width; graph.CalculateConnections (graph.nodes, x, z, this); int[] neighbourOffsets = graph.neighbourOffsets; int[] neighbourOffsetsX = graph.neighbourXOffsets; int[] neighbourOffsetsZ = graph.neighbourZOffsets; //Loop through neighbours for (int i=0;i<8;i++) { //Find the coordinates for the neighbour int nx = x+neighbourOffsetsX[i]; int nz = z+neighbourOffsetsZ[i]; //Make sure it is not out of bounds if (nx < 0 || nz < 0 || nx >= graph.width || nz >= graph.depth) { continue; } GridNode node = (GridNode)graph.nodes[index+neighbourOffsets[i]]; //Calculate connections for neighbour graph.CalculateConnections (graph.nodes, nx, nz, node); } } /** Removes a connection from the node. * This can be a standard connection or a grid connection * \returns True if a connection was removed, false otherwsie */ public override bool RemoveConnection (Node node) { bool standard = base.RemoveConnection (node); GridGraph graph = gridGraphs[indices >> 24]; int index = indices & 0xFFFFFF; int x = index % graph.width; int z = index/graph.width; graph.CalculateConnections (graph.nodes, x, z, this); int[] neighbourOffsets = graph.neighbourOffsets; int[] neighbourOffsetsX = graph.neighbourXOffsets; int[] neighbourOffsetsZ = graph.neighbourZOffsets; for (int i=0;i<8;i++) { int nx = x+neighbourOffsetsX[i]; int nz = z+neighbourOffsetsZ[i]; if (nx < 0 || nz < 0 || nx >= graph.width || nz >= graph.depth) { continue; } GridNode gNode = (GridNode)graph.nodes[index+neighbourOffsets[i]]; if (gNode == node) { SetConnection (i,0); return true; } } return standard; } public override void UpdateConnections () { base.UpdateConnections (); UpdateGridConnections (); } public override void UpdateAllG (NodeRun nodeR, NodeRunData nodeRunData) { BaseUpdateAllG (nodeR, nodeRunData); int index = GetIndex (); int[] neighbourOffsets = gridGraphs[indices >> 24].neighbourOffsets; Node[] nodes = gridGraphs[indices >> 24].nodes; for (int i=0;i<8;i++) { if (GetConnection (i)) { //if (((flags >> i) & 1) == 1) { Node node = nodes[index+neighbourOffsets[i]]; NodeRun nodeR2 = node.GetNodeRun (nodeRunData); if (nodeR2.parent == nodeR && nodeR2.pathID == nodeRunData.pathID) { node.UpdateAllG (nodeR2,nodeRunData); } } } } public override void GetConnections (NodeDelegate callback) { GetConnectionsBase (callback); GridGraph graph = gridGraphs[indices >> 24]; int index = GetIndex (); int[] neighbourOffsets = graph.neighbourOffsets; Node[] nodes = graph.nodes; for (int i=0;i<8;i++) { if (((flags >> i) & 1) == 1) { Node node = nodes[index+neighbourOffsets[i]]; callback (node); } } } public override void FloodFill (Stack<Node> stack, int area) { base.FloodFill (stack,area); GridGraph graph = gridGraphs[indices >> 24]; int index = indices & 0xFFFFFF; int[] neighbourOffsets = graph.neighbourOffsets; //int[] neighbourCosts = graph.neighbourCosts; Node[] nodes = graph.nodes; for (int i=0;i<8;i++) { if (((flags >> i) & 1) == 1) { Node node = nodes[index+neighbourOffsets[i]]; if (node.walkable && node.area != area) { stack.Push (node); node.area = area; } } } } public override int[] InitialOpen (BinaryHeapM open, Int3 targetPosition, Int3 position, Path path, bool doOpen) { if (doOpen) { //Open (open,targetPosition,path); } return base.InitialOpen (open,targetPosition,position,path,doOpen); } public override void Open (NodeRunData nodeRunData, NodeRun nodeR, Int3 targetPosition, Path path) { BaseOpen (nodeRunData, nodeR, targetPosition, path); GridGraph graph = gridGraphs[indices >> 24]; int[] neighbourOffsets = graph.neighbourOffsets; int[] neighbourCosts = graph.neighbourCosts; Node[] nodes = graph.nodes; int index = GetIndex ();//indices & 0xFFFFFF; for (int i=0;i<8;i++) { if (GetConnection (i)) { //if (((flags >> i) & 1) == 1) { Node node = nodes[index+neighbourOffsets[i]]; if (!path.CanTraverse (node)) continue; NodeRun nodeR2 = node.GetNodeRun (nodeRunData); if (nodeR2.pathID != nodeRunData.pathID) { nodeR2.parent = nodeR; nodeR2.pathID = nodeRunData.pathID; nodeR2.cost = (uint)neighbourCosts[i]; node.UpdateH (targetPosition,path.heuristic,path.heuristicScale, nodeR2); node.UpdateG (nodeR2,nodeRunData); nodeRunData.open.Add (nodeR2); } else { //If not we can test if the path from the current node to this one is a better one then the one already used uint tmpCost = (uint)neighbourCosts[i];//(current.costs == null || current.costs.Length == 0 ? costs[current.neighboursKeys[i]] : current.costs[current.neighboursKeys[i]]); if (nodeR.g+tmpCost+node.penalty #if !ASTAR_NoTagPenalty + path.GetTagPenalty(node.tags) #endif < nodeR2.g) { nodeR2.cost = tmpCost; nodeR2.parent = nodeR; node.UpdateAllG (nodeR2,nodeRunData); } else if (nodeR2.g+tmpCost+penalty #if !ASTAR_NoTagPenalty + path.GetTagPenalty(tags) #endif < nodeR.g) {//Or if the path from this node ("node") to the current ("current") is better /*bool contains = false; //[Edit, no one-way links between nodes in a single grid] Make sure we don't travel along the wrong direction of a one way link now, make sure the Current node can be accesed from the Node. /*for (int y=0;y<node.connections.Length;y++) { if (node.connections[y].endNode == this) { contains = true; break; } } if (!contains) { continue; }*/ nodeR.parent = nodeR2; nodeR.cost = tmpCost; UpdateAllG (nodeR,nodeRunData); } } } } } public static void RemoveGridGraph (GridGraph graph) { if (gridGraphs == null) { return; } for (int i=0;i<gridGraphs.Length;i++) { if (gridGraphs[i] == graph) { if (gridGraphs.Length == 1) { gridGraphs = null; return; } for (int j=i+1;j<gridGraphs.Length;j++) { GridGraph gg = gridGraphs[j]; if (gg.nodes != null) { for (int n=0;n<gg.nodes.Length;n++) { if (gg.nodes[n] != null) ((GridNode)gg.nodes[n]).SetGridIndex (j-1); } } } GridGraph[] tmp = new GridGraph[gridGraphs.Length-1]; for (int j=0;j<i;j++) { tmp[j] = gridGraphs[j]; } for (int j=i+1;j<gridGraphs.Length;j++) { tmp[j-1] = gridGraphs[j]; } return; } } } public static int SetGridGraph (GridGraph graph) { if (gridGraphs == null) { gridGraphs = new GridGraph[1]; } else { for (int i=0;i<gridGraphs.Length;i++) { if (gridGraphs[i] == graph) { return i; } } GridGraph[] tmp = new GridGraph[gridGraphs.Length+1]; for (int i=0;i<gridGraphs.Length;i++) { tmp[i] = gridGraphs[i]; } gridGraphs = tmp; } gridGraphs[gridGraphs.Length-1] = graph; return gridGraphs.Length-1; } } }
namespace Serilog.Exceptions.Destructurers; using System; using System.Collections.Generic; using Serilog.Exceptions.Core; /// <summary> /// Base class for more specific destructurers. /// It destructures all the standard properties that every <see cref="Exception"/> has. /// </summary> public class ExceptionDestructurer : IExceptionDestructurer { /// <summary> /// Gets a collection of exceptions types from standard library that do not have any custom property, /// so they can be destructured using generic exception destructurer. /// </summary> #pragma warning disable CA1819 // Properties should not return arrays public virtual Type[] TargetTypes #pragma warning restore CA1819 // Properties should not return arrays { get { var targetTypes = new List<Type> { #pragma warning disable IDE0001 // Simplify Names #if NET461 || NET472 typeof(Microsoft.SqlServer.Server.InvalidUdtException), #endif #if !NETSTANDARD1_3 typeof(System.AccessViolationException), typeof(System.AppDomainUnloadedException), typeof(System.ApplicationException), typeof(System.ArithmeticException), typeof(System.ArrayTypeMismatchException), typeof(System.CannotUnloadAppDomainException), #endif typeof(System.Collections.Generic.KeyNotFoundException), #if !NETSTANDARD1_3 typeof(System.ComponentModel.Design.CheckoutException), typeof(System.ComponentModel.InvalidAsynchronousStateException), typeof(System.ComponentModel.InvalidEnumArgumentException), #endif #if NET461 || NET472 typeof(System.Configuration.SettingsPropertyIsReadOnlyException), typeof(System.Configuration.SettingsPropertyNotFoundException), typeof(System.Configuration.SettingsPropertyWrongTypeException), #endif #if !NETSTANDARD1_3 typeof(System.ContextMarshalException), typeof(System.Data.ConstraintException), typeof(System.Data.DataException), typeof(System.Data.DeletedRowInaccessibleException), typeof(System.Data.DuplicateNameException), typeof(System.Data.EvaluateException), typeof(System.Data.InRowChangingEventException), typeof(System.Data.InvalidConstraintException), typeof(System.Data.InvalidExpressionException), typeof(System.Data.MissingPrimaryKeyException), typeof(System.Data.NoNullAllowedException), #endif #if NET461 || NET472 typeof(System.Data.OperationAbortedException), #endif #if !NETSTANDARD1_3 typeof(System.Data.ReadOnlyException), typeof(System.Data.RowNotInTableException), typeof(System.Data.SqlTypes.SqlAlreadyFilledException), typeof(System.Data.SqlTypes.SqlNotFilledException), typeof(System.Data.StrongTypingException), typeof(System.Data.SyntaxErrorException), typeof(System.Data.VersionNotFoundException), #endif #if NET461 || NET472 typeof(System.Diagnostics.Eventing.Reader.EventLogInvalidDataException), typeof(System.Diagnostics.Eventing.Reader.EventLogNotFoundException), typeof(System.Diagnostics.Eventing.Reader.EventLogProviderDisabledException), typeof(System.Diagnostics.Eventing.Reader.EventLogReadingException), #endif typeof(System.Diagnostics.Tracing.EventSourceException), typeof(System.DataMisalignedException), typeof(System.DivideByZeroException), typeof(System.DllNotFoundException), #if !NETSTANDARD1_3 typeof(System.DuplicateWaitObjectException), typeof(System.EntryPointNotFoundException), #endif typeof(System.Exception), typeof(System.FieldAccessException), typeof(System.FormatException), typeof(System.IndexOutOfRangeException), typeof(System.InsufficientExecutionStackException), #if !NETSTANDARD1_3 typeof(System.InsufficientMemoryException), #endif typeof(System.InvalidCastException), typeof(System.InvalidOperationException), typeof(System.InvalidProgramException), typeof(System.InvalidTimeZoneException), typeof(System.IO.DirectoryNotFoundException), #if !NETSTANDARD1_3 typeof(System.IO.DriveNotFoundException), #endif typeof(System.IO.EndOfStreamException), #if !NETSTANDARD1_3 typeof(System.IO.InternalBufferOverflowException), #endif typeof(System.IO.InvalidDataException), typeof(System.IO.IOException), #if !NETSTANDARD1_3 typeof(System.IO.IsolatedStorage.IsolatedStorageException), #endif typeof(System.IO.PathTooLongException), #if NET461 || NET472 typeof(System.Management.Instrumentation.InstanceNotFoundException), typeof(System.Management.Instrumentation.InstrumentationBaseException), typeof(System.Management.Instrumentation.InstrumentationException), #endif typeof(System.MemberAccessException), typeof(System.MethodAccessException), #if !NETSTANDARD1_3 typeof(System.MulticastNotSupportedException), #endif typeof(System.Net.CookieException), #if !NETSTANDARD1_3 typeof(System.Net.NetworkInformation.PingException), typeof(System.Net.ProtocolViolationException), #endif typeof(System.NotImplementedException), typeof(System.NotSupportedException), typeof(System.NullReferenceException), typeof(System.OutOfMemoryException), typeof(System.OverflowException), typeof(System.PlatformNotSupportedException), typeof(System.RankException), typeof(System.Reflection.AmbiguousMatchException), #if !NETSTANDARD1_3 typeof(System.Reflection.CustomAttributeFormatException), typeof(System.Reflection.InvalidFilterCriteriaException), typeof(System.Reflection.TargetException), #endif typeof(System.Reflection.TargetInvocationException), typeof(System.Reflection.TargetParameterCountException), typeof(System.Resources.MissingManifestResourceException), #if NET5_0_OR_GREATER || NETSTANDARD2_1 typeof(System.Runtime.AmbiguousImplementationException), #endif typeof(System.Runtime.InteropServices.COMException), typeof(System.Runtime.InteropServices.InvalidComObjectException), typeof(System.Runtime.InteropServices.InvalidOleVariantTypeException), typeof(System.Runtime.InteropServices.MarshalDirectiveException), typeof(System.Runtime.InteropServices.SafeArrayRankMismatchException), typeof(System.Runtime.InteropServices.SafeArrayTypeMismatchException), typeof(System.Runtime.InteropServices.SEHException), #if NET461 || NET472 typeof(System.Runtime.Remoting.RemotingException), typeof(System.Runtime.Remoting.RemotingTimeoutException), typeof(System.Runtime.Remoting.ServerException), #endif #if !NETSTANDARD1_3 typeof(System.Runtime.Serialization.SerializationException), typeof(System.Security.Authentication.AuthenticationException), typeof(System.Security.Authentication.InvalidCredentialException), #endif typeof(System.Security.Cryptography.CryptographicException), #if !NETSTANDARD1_3 typeof(System.Security.Cryptography.CryptographicUnexpectedOperationException), #endif #if NET461 || NET472 typeof(System.Security.Policy.PolicyException), #endif typeof(System.Security.VerificationException), #if NET461 || NET472 typeof(System.Security.XmlSyntaxException), #endif #if !NETSTANDARD1_3 typeof(System.StackOverflowException), typeof(System.SystemException), #endif typeof(System.Threading.BarrierPostPhaseException), typeof(System.Threading.LockRecursionException), typeof(System.Threading.SemaphoreFullException), typeof(System.Threading.SynchronizationLockException), typeof(System.Threading.Tasks.TaskSchedulerException), #if !NETSTANDARD1_3 typeof(System.Threading.ThreadInterruptedException), typeof(System.Threading.ThreadStartException), typeof(System.Threading.ThreadStateException), #endif typeof(System.Threading.WaitHandleCannotBeOpenedException), typeof(System.TimeoutException), #if !NETSTANDARD1_3 typeof(System.TimeZoneNotFoundException), #endif typeof(System.TypeAccessException), #if !NETSTANDARD1_3 typeof(System.TypeUnloadedException), #endif typeof(System.UnauthorizedAccessException), typeof(System.UriFormatException), }; #pragma warning restore IDE0001 // Simplify Names return targetTypes.ToArray(); } } /// <inheritdoc cref="IExceptionDestructurer.Destructure"/> public virtual void Destructure( Exception exception, IExceptionPropertiesBag propertiesBag, Func<Exception, IReadOnlyDictionary<string, object?>?> destructureException) { #if NET6_0_OR_GREATER ArgumentNullException.ThrowIfNull(exception); ArgumentNullException.ThrowIfNull(propertiesBag); ArgumentNullException.ThrowIfNull(destructureException); #else if (exception is null) { throw new ArgumentNullException(nameof(exception)); } if (propertiesBag is null) { throw new ArgumentNullException(nameof(propertiesBag)); } if (destructureException is null) { throw new ArgumentNullException(nameof(destructureException)); } #endif propertiesBag.AddProperty("Type", exception.GetType().FullName); DestructureCommonExceptionProperties( exception, propertiesBag, destructureException, data => data.ToStringObjectDictionary()); } /// <summary> /// Destructures public properties of <see cref="Exception"/>. /// Omits less frequently used ones if they are null. /// </summary> /// <param name="exception">The exception that will be destructured.</param> /// <param name="propertiesBag">The bag when destructured properties will be put.</param> /// <param name="innerDestructure">Function that can be used to destructure inner exceptions if there are any.</param> /// <param name="destructureDataProperty">Injected function for destructuring <see cref="Exception.Data"/>.</param> internal static void DestructureCommonExceptionProperties( Exception exception, IExceptionPropertiesBag propertiesBag, Func<Exception, IReadOnlyDictionary<string, object?>?> innerDestructure, Func<System.Collections.IDictionary, object> destructureDataProperty) { if (exception.Data.Count != 0) { propertiesBag.AddProperty(nameof(Exception.Data), destructureDataProperty(exception.Data)); } if (!string.IsNullOrEmpty(exception.HelpLink)) { propertiesBag.AddProperty(nameof(Exception.HelpLink), exception.HelpLink); } if (exception.HResult != 0) { propertiesBag.AddProperty(nameof(Exception.HResult), exception.HResult); } propertiesBag.AddProperty(nameof(Exception.Message), exception.Message); propertiesBag.AddProperty(nameof(Exception.Source), exception.Source); propertiesBag.AddProperty(nameof(Exception.StackTrace), exception.StackTrace); #if !NETSTANDARD1_3 if (exception.TargetSite is not null) { propertiesBag.AddProperty(nameof(Exception.TargetSite), exception.TargetSite.ToString()); } #endif if (exception.InnerException is not null) { propertiesBag.AddProperty(nameof(Exception.InnerException), innerDestructure(exception.InnerException)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NotificationHubsOperations operations. /// </summary> public partial interface INotificationHubsOperations { /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// The notificationHub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Update a NotificationHub in a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update a NotificationHub /// Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NotificationHubResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NotificationHubResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Updates an authorization rule for a NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a notificationHub authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an authorization rule for a NotificationHub by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the NotificationHub /// Authorization Rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the NotificationHub Authorization /// Rule Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, PolicykeyResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PnsCredentialsResource>> GetPnsCredentialsWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace DD.CBU.Compute.Api.Contracts.Server { /// <remarks/> [System.Xml.Serialization.XmlIncludeAttribute(typeof(ServerWithBackupType))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.18020")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://oec.api.opsource.net/schemas/server")] public partial class ServerWithStateType { private string nameField; private string descriptionField; private OSType operatingSystemField; private int cpuCountField; private int memoryMbField; private DiskWithSpeedType[] diskField; private string[] softwareLabelField; private string sourceImageIdField; private string networkIdField; private string machineNameField; private string privateIpField; private string publicIpField; private System.DateTime createdField; private bool isDeployedField; private bool isStartedField; private string stateField; private ProgressStatusType statusField; private MachineStatusType[] machineStatusField; private string idField; private string locationField; /// <remarks/> public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> public string description { get { return this.descriptionField; } set { this.descriptionField = value; } } /// <remarks/> public OSType operatingSystem { get { return this.operatingSystemField; } set { this.operatingSystemField = value; } } /// <remarks/> public int cpuCount { get { return this.cpuCountField; } set { this.cpuCountField = value; } } /// <remarks/> public int memoryMb { get { return this.memoryMbField; } set { this.memoryMbField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("disk")] public DiskWithSpeedType[] disk { get { return this.diskField; } set { this.diskField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("softwareLabel")] public string[] softwareLabel { get { return this.softwareLabelField; } set { this.softwareLabelField = value; } } /// <remarks/> public string sourceImageId { get { return this.sourceImageIdField; } set { this.sourceImageIdField = value; } } /// <remarks/> public string networkId { get { return this.networkIdField; } set { this.networkIdField = value; } } /// <remarks/> public string machineName { get { return this.machineNameField; } set { this.machineNameField = value; } } /// <remarks/> public string privateIp { get { return this.privateIpField; } set { this.privateIpField = value; } } /// <remarks/> public string publicIp { get { return this.publicIpField; } set { this.publicIpField = value; } } /// <remarks/> public System.DateTime created { get { return this.createdField; } set { this.createdField = value; } } /// <remarks/> public bool isDeployed { get { return this.isDeployedField; } set { this.isDeployedField = value; } } /// <remarks/> public bool isStarted { get { return this.isStartedField; } set { this.isStartedField = value; } } /// <remarks/> public string state { get { return this.stateField; } set { this.stateField = value; } } /// <remarks/> public ProgressStatusType status { get { return this.statusField; } set { this.statusField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("machineStatus")] public MachineStatusType[] machineStatus { get { return this.machineStatusField; } set { this.machineStatusField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string id { get { return this.idField; } set { this.idField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string location { get { return this.locationField; } set { this.locationField = value; } } } }
// 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.Linq; using System.Net; using DataMigration.Tests.Helpers; using Microsoft.Azure.Management.DataMigration; using Microsoft.Azure.Management.DataMigration.Models; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; namespace DataMigration.Tests.ScenarioTests { public class CRUDTaskTests : CRUDDMSTestsBase { [Fact] public void CreateResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSTask(context, dmsClient, resourceGroup, service, project.Name, DmsTaskName); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void GetResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSTask(context, dmsClient, resourceGroup, service, project.Name, DmsTaskName); var getResult = dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, task.Name); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void RunCommandSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSSyncTask(context, dmsClient, resourceGroup, service, project.Name, DmsTaskName); bool wait = true; do { var getResult = dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, task.Name, "output"); Assert.True(getResult.Properties.State.Equals(TaskState.Queued) || getResult.Properties.State.Equals(TaskState.Running)); MigrateSqlServerSqlDbSyncTaskProperties properties = (MigrateSqlServerSqlDbSyncTaskProperties)getResult.Properties; var databaseLevelResult = (MigrateSqlServerSqlDbSyncTaskOutputDatabaseLevel)properties.Output.Where(o => o.GetType() == typeof(MigrateSqlServerSqlDbSyncTaskOutputDatabaseLevel)).FirstOrDefault(); if (databaseLevelResult != null && databaseLevelResult.MigrationState == SyncDatabaseMigrationReportingState.READYTOCOMPLETE) { wait = false; } } while (wait); var commandProperties = new MigrateSyncCompleteCommandProperties { Input = new MigrateSyncCompleteCommandInput { DatabaseName = "DatabaseName" }, }; var command = dmsClient.Tasks.Command(resourceGroup.Name, service.Name, project.Name, task.Name, commandProperties); Assert.Equal(command.State, CommandState.Accepted); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void DeleteResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSTask(context, dmsClient, resourceGroup, service, project.Name, DmsTaskName); var getResult = dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, task.Name); dmsClient.Tasks.Cancel(resourceGroup.Name, service.Name, project.Name, task.Name); Utilities.WaitIfNotInPlaybackMode(); dmsClient.Tasks.Delete(resourceGroup.Name, service.Name, project.Name, task.Name); var x = Assert.Throws<ApiErrorException>(() => dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, task.Name)); Assert.Equal(HttpStatusCode.NotFound, x.Response.StatusCode); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } private ProjectTask CreateDMSTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new ConnectToTargetSqlDbTaskProperties { Input = new ConnectToTargetSqlDbTaskInput( new SqlConnectionInfo { DataSource = "shuhuandmsdbs.database.windows.net", EncryptConnection = true, TrustServerCertificate = true, UserName = "testuser", Password = "testuserpw", Authentication = AuthenticationType.SqlAuthentication, } ) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private ProjectTask CreateDMSSyncTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new MigrateSqlServerSqlDbSyncTaskProperties { Input = new MigrateSqlServerSqlDbSyncTaskInput( new SqlConnectionInfo { DataSource = @"steven-work.redmond.corp.microsoft.com\stevenf16,12345", EncryptConnection = true, TrustServerCertificate = true, UserName = "testuser", Password = "Dr22VHg@_,P3", Authentication = AuthenticationType.SqlAuthentication, }, new SqlConnectionInfo { DataSource = "shuhuandmsdbs.database.windows.net", EncryptConnection = true, TrustServerCertificate = true, UserName = "testuser", Password = "Dr22VHg@_,P3", Authentication = AuthenticationType.SqlAuthentication, }, new List<MigrateSqlServerSqlDbSyncDatabaseInput> { new MigrateSqlServerSqlDbSyncDatabaseInput { Name = "JasmineTest", TargetDatabaseName = "JasmineTest", TableMap = new Dictionary<string, string> { { "dbo.TestTable1", "dbo.TestTable1" }, { "dbo.TestTable2", "dbo.TestTable2" } } } }) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; using System.Threading; namespace System.Globalization { // Gregorian Calendars use Era Info [Serializable] internal class EraInfo { internal int era; // The value of the era. internal long ticks; // The time in ticks when the era starts internal int yearOffset; // The offset to Gregorian year when the era starts. // Gregorian Year = Era Year + yearOffset // Era Year = Gregorian Year - yearOffset internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may // be affected by the DateTime.MinValue; internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1) [OptionalField(VersionAdded = 4)] internal String eraName; // The era name [OptionalField(VersionAdded = 4)] internal String abbrevEraName; // Abbreviated Era Name [OptionalField(VersionAdded = 4)] internal String englishEraName; // English era name internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, String eraName, String abbrevEraName, String englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; this.ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) [Serializable] internal class GregorianCalendarHelper { // 1 tick = 100ns = 10E-7 second // Number of ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; // // This is the max Gregorian year can be represented by DateTime class. The limitation // is derived from DateTime class. // internal int MaxYear { get { return (m_maxYear); } } internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; [OptionalField(VersionAdded = 1)] internal int m_maxYear = 9999; [OptionalField(VersionAdded = 1)] internal int m_minYear; internal Calendar m_Cal; [OptionalField(VersionAdded = 1)] internal EraInfo[] m_EraInfo; [OptionalField(VersionAdded = 1)] internal int[] m_eras = null; // Construct an instance of gregorian calendar. internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear; ; } /*=================================GetGregorianYear========================== **Action: Get the Gregorian year value for the specified year in an era. **Returns: The Gregorian year value. **Arguments: ** year the year value in Japanese calendar ** era the Japanese emperor era value. **Exceptions: ** ArgumentOutOfRangeException if year value is invalid or era value is invalid. ============================================================================*/ internal int GetGregorianYear(int year, int era) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } return (m_EraInfo[i].yearOffset + year); } } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } internal bool IsValidYear(int year, int era) { if (year < 0) { return false; } if (era == Calendar.CurrentEra) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { return false; } return true; } } return false; } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 int y400 = n / DaysPer400Years; // n = day number within 400-year period n -= y400 * DaysPer400Years; // y100 = number of whole 100-year periods within 400-year period int y100 = n / DaysPer100Years; // Last 100-year period has an extra day, so decrement result if 4 if (y100 == 4) y100 = 3; // n = day number within 100-year period n -= y100 * DaysPer100Years; // y4 = number of whole 4-year periods within 100-year period int y4 = n / DaysPer4Years; // n = day number within 4-year period n -= y4 * DaysPer4Years; // y1 = number of whole years within 4-year period int y1 = n / DaysPerYear; // Last year has an extra day, so decrement result if 4 if (y1 == 4) y1 = 3; // If year was requested, compute and return it if (part == DatePartYear) { return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1); } // n = day number within year n -= y1 * DaysPerYear; // If day-of-year was requested, return it if (part == DatePartDayOfYear) { return (n + 1); } // Leap year calculation looks different from IsLeapYear since y1, y4, // and y100 are relative to year 1, not year 0 bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3)); int[] days = leapYear ? DaysToMonth366 : DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it if (part == DatePartMonth) return (m); // Return 1-based day-of-month return (n - days[m - 1] + 1); } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal static long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { //TimeSpan.TimeToTicks is a family access function which does no error checking, so //we need to put some error checking out here. if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } return (InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException( "time", String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } Contract.EndContractBlock(); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } Contract.EndContractBlock(); CheckTicksRange(time.Ticks); int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public int GetDayOfYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartDayOfYear)); } // Returns the number of days in the month given by the year and // month arguments. // [Pure] public int GetDaysInMonth(int year, int month, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } // Returns the number of days in the year given by the year argument for the current era. // public int GetDaysInYear(int year, int era) { // // Convert year/era value to Gregorain year value. // year = GetGregorianYear(year, era); return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } // Returns the era for the specified DateTime value. public int GetEra(DateTime time) { long ticks = time.Ticks; // The assumption here is that m_EraInfo is listed in reverse order. for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (m_EraInfo[i].era); } } throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era); } public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return ((int[])m_eras.Clone()); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public int GetMonthsInYear(int year, int era) { year = GetGregorianYear(year, era); return (12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public int GetYear(DateTime time) { long ticks = time.Ticks; int year = GetDatePart(ticks, DatePartYear); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Returns the year that match the specified Gregorian year. The returned value is an // integer between 1 and 9999. // public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset // which will end up with zero as calendar year. // We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989 if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return (year - m_EraInfo[i].yearOffset); } } throw new ArgumentException(SR.Argument_NoEra); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public bool IsLeapDay(int year, int month, int day, int era) { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } Contract.EndContractBlock(); if (!IsLeapYear(year, era)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public int GetLeapMonth(int year, int era) { year = GetGregorianYear(year, era); return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public bool IsLeapMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return (new DateTime(ticks)); } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); // Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear() // can call GetYear() that exceeds the supported range of the Gregorian-based calendars. return (GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek)); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year < 100) { int y = year % 100; return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y); } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } } }
//============================================================================== // TorqueLab -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== $ShapeLab_NoProxyPreview = false; //============================================================================== // GuiShapeLabPreview - Called when the position of the active thread has changed, such as during playback function ShapeLabShapeView::onThreadPosChanged( %this, %pos, %inTransition ) { // Update sliders %frame = ShapeLabPreview.threadPosToKeyframe( %pos ); if (isObject(ShapeLabSeqSlider)) ShapeLabSeqSlider.setValue( %frame ); if (isObject(ShapeLabPreview-->currentFrame)) ShapeLabPreview-->currentFrame.setText( mRound(%frame) ); if ( ShapeLabThreadViewer-->transitionTo.getText() $= "synched position" ) { SLE_ThreadSlider.setValue( %frame ); // Highlight the slider during transitions if ( %inTransition ) SLE_ThreadSlider.profile = ToolsSliderMarker; else SLE_ThreadSlider.profile = ToolsSliderProfile; } } //============================================================================== // Set the sequence to play function ShapeLabPreview::setSequence( %this, %seqName,%seqSource ) { %this.usingProxySeq = false; if ( SLE_ThreadTransLastsCheck.getValue() ) { %transTime = SLE_ThreadTransDuration.getText(); if ( ShapeLabThreadViewer-->transitionTo.getText() $= "synched position" ) %transPos = -1; else %transPos = %this.keyframeToThreadPos( SLE_ThreadSlider.getValue() ); %transPlay = ( ShapeLabThreadViewer-->transitionTarget.getText() $= "plays during transition" ); } else { %transTime = 0; %transPos = 0; %transPlay = 0; } // No transition when sequence is not changing if ( %seqName $= ShapeLabShapeView.getThreadSequence() ) %transTime = 0; if ( %seqName !$= "" ) { // To be able to effectively scrub through the animation, we need to have all // frames available, even if it was added with only a subset. If that is the // case, then create a proxy sequence that has all the frames instead. if (%seqSource $= "") %seqSource = ShapeLab.getSequenceSource( %seqName ); %from = rtrim( getFields( %seqSource, 0, 1 ) ); %startFrame = getField( %seqSource, 2 ); %endFrame = getField( %seqSource, 3 ); %frameCount = getField( %seqSource, 4 ); if ( ( %startFrame != 0 ) || ( %endFrame != ( %frameCount-1 ) ) && !$ShapeLab_NoProxyPreview ) { %proxyName = ShapeLab.getProxyName( %seqName ); if ( ShapeLab.shape.getSequenceIndex( %proxyName ) != -1 ) { ShapeLab.shape.removeSequence( %proxyName ); ShapeLabShapeView.refreshThreadSequences(); } ShapeLab.shape.addSequence( %from, %proxyName ); // Limit the transition position to the in/out range %transPos = mClamp( %transPos, 0, 1 ); } ShapeLabShapeView.setThreadSequence( %seqName, %transTime, %transPos, %transPlay ); } SL_ActiveThreadInfo-->activeSeqText.setText("Sequence:\c1 "@%seqName); //ShapeLab.setActiveSequence(%seqName); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::getTimelineBitmapPos( %this, %val, %width ) { %frameCount = getWord( ShapeLabSeqSlider.range, 1 ); %pos_x = getWord( ShapeLabSeqSlider.getPosition(), 0 ); %len_x = getWord( ShapeLabSeqSlider.getExtent(), 0 ) - %width; return %pos_x + ( ( %len_x * %val / %frameCount ) ); } // Set the in or out sequence limit function ShapeLabPreview::setPlaybackLimit( %this, %limit, %val ) { // Determine where to place the in/out bar on the slider %thumbWidth = 8; // width of the thumb bitmap %pos_x = %this.getTimelineBitmapPos( %val, %thumbWidth ); if ( %limit $= "in" ) { %this.seqStartFrame = %val; %this-->seqIn.setText( %val ); %this-->seqInBar.setPosition( %pos_x, 0 ); } else { %this.seqEndFrame = %val; %this-->seqOut.setText( %val ); %this-->seqOutBar.setPosition( %pos_x, 0 ); } } //------------------------------------------------------------------------------ //============================================================================== //============================================================================== // ShapeLab -> Sequence Editing //============================================================================== //------------------------------------------------------------------------------ function ShapeLabSeqSlider::onMouseDragged( %this ) { // Pause the active thread when the slider is dragged if ( ShapeLabPreview-->pauseBtn.getValue() == 0 ) ShapeLabPreview-->pauseBtn.performClick(); ShapeLabPreview.setKeyframe( %this.getValue() ); } //============================================================================== function ShapeLabPreview::threadPosToKeyframe( %this, %pos ) { if ( %this.usingProxySeq ) { %start = getWord( ShapeLabSeqSlider.range, 0 ); %end = getWord( ShapeLabSeqSlider.range, 1 ); } else { %start = ShapeLabPreview.seqStartFrame; %end = ShapeLabPreview.seqEndFrame; } return %start + ( %end - %start ) * %pos; } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::keyframeToThreadPos( %this, %frame ) { if ( %this.usingProxySeq ) { %start = getWord( ShapeLabSeqSlider.range, 0 ); %end = getWord( ShapeLabSeqSlider.range, 1 ); } else { %start = ShapeLabPreview.seqStartFrame; %end = ShapeLabPreview.seqEndFrame; } return ( %frame - %start ) / ( %end - %start ); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::setKeyframe( %this, %frame ) { ShapeLabSeqSlider.setValue( %frame ); ShapeLabPreview-->currentFrame.setText( mRound(%frame) ); if ( ShapeLabThreadViewer-->transitionTo.getText() $= "synched position" ) SLE_ThreadSlider.setValue( %frame ); // Update the position of the active thread => if outside the in/out range, // need to switch to the proxy sequence if ( !%this.usingProxySeq && !$ShapeLab_NoProxyPreview) { if ( ( %frame < %this.seqStartFrame ) || ( %frame > %this.seqEndFrame) ) { %this.usingProxySeq = true; %proxyName = ShapeLab.getProxyName( ShapeLabShapeView.getThreadSequence() ); ShapeLabShapeView.setThreadSequence( %proxyName, 0, 0, false ); } } ShapeLabShapeView.threadPos = %this.keyframeToThreadPos( %frame ); } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::setNoProxySequence( %this ) { // no need to use the proxy sequence during playback if ( %this.usingProxySeq ) { %this.usingProxySeq = false; %seqName = ShapeLab.getUnproxyName( ShapeLabShapeView.getThreadSequence() ); ShapeLabShapeView.setThreadSequence( %seqName, 0, 0, false ); ShapeLabShapeView.threadPos = %this.keyframeToThreadPos( ShapeLabSeqSlider.getValue() ); } } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::togglePause( %this ) { if ( %this-->pauseBtn.getValue() == 0 ) { %this.lastDirBkwd = %this-->playBkwdBtn.getValue(); %this-->pauseBtn.performClick(); } else { %this.setNoProxySequence(); if ( %this.lastDirBkwd ) %this-->playBkwdBtn.performClick(); else %this-->playFwdBtn.performClick(); } } //------------------------------------------------------------------------------ //============================================================================== // Set the direction of the current thread (-1: reverse, 0: paused, 1: forward) function ShapeLabPreview::setThreadDirection( %this, %dir ) { // Update thread direction ShapeLabShapeView.threadDirection = %dir; // Sync the controls in the thread window switch ( %dir ) { case -1: ShapeLabThreadViewer-->playBkwdBtn.setStateOn( 1 ); case 0: ShapeLabThreadViewer-->pauseBtn.setStateOn( 1 ); case 1: ShapeLabThreadViewer-->playFwdBtn.setStateOn( 1 ); } } //------------------------------------------------------------------------------ //============================================================================== function ShapeLabPreview::togglePingPong( %this ) { ShapeLabShapeView.threadPingPong = %this-->pingpong.getValue(); if ( %this-->playFwdBtn.getValue() ) %this-->playFwdBtn.performClick(); else if ( %this-->playBkwdBtn.getValue() ) %this-->playBkwdBtn.performClick(); } //------------------------------------------------------------------------------ function ShapeLabPreview::onEditSeqInOut( %this, %type, %val ) { devLog("ShapeLabPreview::onEditSeqInOut %type, %val", %type, %val ); %frameCount = getWord( ShapeLabSeqSlider.range, 1 ); // Force value to a frame index within the slider range %val = mRound( %val ); if ( %val < 0 ) %val = 0; if ( %val > %frameCount ) %val = %frameCount; // Enforce 'in' value must be < 'out' value if ( %type $= "in" ) { if ( %val >= %this-->seqOut.getText() ) %val = %this-->seqOut.getText() - 1; SL_ActiveSequence-->frameIn.setText( %val ); %this-->seqIn.setText( %val ); } else { if ( %val <= %this-->seqIn.getText() ) %val = %this-->seqIn.getText() + 1; SL_ActiveSequence-->frameOut.setText( %val ); %this-->seqOut.setText( %val ); } ShapeLab.onEditSequenceSource( "",SL_ActiveSequence ); }
using System; using System.Xml.Serialization; namespace NBug.Core.Submission.Tracker.Mantis { [Serializable, SoapType(Namespace = "http://futureware.biz/mantisconnect")] public class IssueData { private string additional_informationField; private AttachmentData[] attachmentsField; private string buildField; private string categoryField; private CustomFieldValueForIssueData[] custom_fieldsField; private DateTime date_submittedField; private bool date_submittedFieldSpecified; private string descriptionField; private DateTime due_dateField; private bool due_dateFieldSpecified; private ObjectRef etaField; private string fixed_in_versionField; private AccountData handlerField; private string idField; private DateTime last_updatedField; private bool last_updatedFieldSpecified; private AccountData[] monitorsField; private IssueNoteData[] notesField; private string os_buildField; private string osField; private string platformField; private ObjectRef priorityField; private ObjectRef projectField; private ObjectRef projectionField; private RelationshipData[] relationshipsField; private AccountData reporterField; private ObjectRef reproducibilityField; private ObjectRef resolutionField; private ObjectRef severityField; private string sponsorship_totalField; private ObjectRef statusField; private string steps_to_reproduceField; private bool stickyField; private bool stickyFieldSpecified; private string summaryField; private ObjectRef[] tagsField; private string target_versionField; private string versionField; private ObjectRef view_stateField; [SoapElement(DataType = "integer")] public string id { get { return idField; } set { idField = value; } } public ObjectRef view_state { get { return view_stateField; } set { view_stateField = value; } } public DateTime last_updated { get { return last_updatedField; } set { last_updatedField = value; } } [SoapIgnore] public bool last_updatedSpecified { get { return last_updatedFieldSpecified; } set { last_updatedFieldSpecified = value; } } public ObjectRef project { get { return projectField; } set { projectField = value; } } public string category { get { return categoryField; } set { categoryField = value; } } public ObjectRef priority { get { return priorityField; } set { priorityField = value; } } public ObjectRef severity { get { return severityField; } set { severityField = value; } } public ObjectRef status { get { return statusField; } set { statusField = value; } } public AccountData reporter { get { return reporterField; } set { reporterField = value; } } public string summary { get { return summaryField; } set { summaryField = value; } } public string version { get { return versionField; } set { versionField = value; } } public string build { get { return buildField; } set { buildField = value; } } public string platform { get { return platformField; } set { platformField = value; } } public string os { get { return osField; } set { osField = value; } } public string os_build { get { return os_buildField; } set { os_buildField = value; } } public ObjectRef reproducibility { get { return reproducibilityField; } set { reproducibilityField = value; } } public DateTime date_submitted { get { return date_submittedField; } set { date_submittedField = value; } } [SoapIgnore] public bool date_submittedSpecified { get { return date_submittedFieldSpecified; } set { date_submittedFieldSpecified = value; } } [SoapElement(DataType = "integer")] public string sponsorship_total { get { return sponsorship_totalField; } set { sponsorship_totalField = value; } } public AccountData handler { get { return handlerField; } set { handlerField = value; } } public ObjectRef projection { get { return projectionField; } set { projectionField = value; } } public ObjectRef eta { get { return etaField; } set { etaField = value; } } public ObjectRef resolution { get { return resolutionField; } set { resolutionField = value; } } public string fixed_in_version { get { return fixed_in_versionField; } set { fixed_in_versionField = value; } } public string target_version { get { return target_versionField; } set { target_versionField = value; } } public string description { get { return descriptionField; } set { descriptionField = value; } } public string steps_to_reproduce { get { return steps_to_reproduceField; } set { steps_to_reproduceField = value; } } public string additional_information { get { return additional_informationField; } set { additional_informationField = value; } } public AttachmentData[] attachments { get { return attachmentsField; } set { attachmentsField = value; } } public RelationshipData[] relationships { get { return relationshipsField; } set { relationshipsField = value; } } public IssueNoteData[] notes { get { return notesField; } set { notesField = value; } } public CustomFieldValueForIssueData[] custom_fields { get { return custom_fieldsField; } set { custom_fieldsField = value; } } public DateTime due_date { get { return due_dateField; } set { due_dateField = value; } } [SoapIgnore] public bool due_dateSpecified { get { return due_dateFieldSpecified; } set { due_dateFieldSpecified = value; } } public AccountData[] monitors { get { return monitorsField; } set { monitorsField = value; } } public bool sticky { get { return stickyField; } set { stickyField = value; } } [SoapIgnore] public bool stickySpecified { get { return stickyFieldSpecified; } set { stickyFieldSpecified = value; } } public ObjectRef[] tags { get { return tagsField; } set { tagsField = value; } } } }
using Lucene.Net.Util; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Allocator = Lucene.Net.Util.ByteBlockPool.Allocator; using Analyzer = Lucene.Net.Analysis.Analyzer; using Codec = Lucene.Net.Codecs.Codec; using Constants = Lucene.Net.Util.Constants; using Counter = Lucene.Net.Util.Counter; using DeleteSlice = Lucene.Net.Index.DocumentsWriterDeleteQueue.DeleteSlice; using Directory = Lucene.Net.Store.Directory; using DirectTrackingAllocator = Lucene.Net.Util.ByteBlockPool.DirectTrackingAllocator; using FlushInfo = Lucene.Net.Store.FlushInfo; using InfoStream = Lucene.Net.Util.InfoStream; using Int32BlockPool = Lucene.Net.Util.Int32BlockPool; using IOContext = Lucene.Net.Store.IOContext; using IMutableBits = Lucene.Net.Util.IMutableBits; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using Similarity = Lucene.Net.Search.Similarities.Similarity; using TrackingDirectoryWrapper = Lucene.Net.Store.TrackingDirectoryWrapper; internal class DocumentsWriterPerThread { /// <summary> /// The <see cref="IndexingChain"/> must define the <see cref="GetChain(DocumentsWriterPerThread)"/> method /// which returns the <see cref="DocConsumer"/> that the <see cref="DocumentsWriter"/> calls to process the /// documents. /// </summary> internal abstract class IndexingChain { internal abstract DocConsumer GetChain(DocumentsWriterPerThread documentsWriterPerThread); } private static readonly IndexingChain defaultIndexingChain = new IndexingChainAnonymousInnerClassHelper(); public static IndexingChain DefaultIndexingChain => defaultIndexingChain; private class IndexingChainAnonymousInnerClassHelper : IndexingChain { public IndexingChainAnonymousInnerClassHelper() { } internal override DocConsumer GetChain(DocumentsWriterPerThread documentsWriterPerThread) { /* this is the current indexing chain: DocConsumer / DocConsumerPerThread --> code: DocFieldProcessor --> DocFieldConsumer / DocFieldConsumerPerField --> code: DocFieldConsumers / DocFieldConsumersPerField --> code: DocInverter / DocInverterPerField --> InvertedDocConsumer / InvertedDocConsumerPerField --> code: TermsHash / TermsHashPerField --> TermsHashConsumer / TermsHashConsumerPerField --> code: FreqProxTermsWriter / FreqProxTermsWriterPerField --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerField --> InvertedDocEndConsumer / InvertedDocConsumerPerField --> code: NormsConsumer / NormsConsumerPerField --> StoredFieldsConsumer --> TwoStoredFieldConsumers -> code: StoredFieldsProcessor -> code: DocValuesProcessor */ // Build up indexing chain: TermsHashConsumer termVectorsWriter = new TermVectorsConsumer(documentsWriterPerThread); TermsHashConsumer freqProxWriter = new FreqProxTermsWriter(); InvertedDocConsumer termsHash = new TermsHash(documentsWriterPerThread, freqProxWriter, true, new TermsHash(documentsWriterPerThread, termVectorsWriter, false, null)); NormsConsumer normsWriter = new NormsConsumer(); DocInverter docInverter = new DocInverter(documentsWriterPerThread.docState, termsHash, normsWriter); StoredFieldsConsumer storedFields = new TwoStoredFieldsConsumers( new StoredFieldsProcessor(documentsWriterPerThread), new DocValuesProcessor(documentsWriterPerThread.bytesUsed)); return new DocFieldProcessor(documentsWriterPerThread, docInverter, storedFields); } } public class DocState { internal readonly DocumentsWriterPerThread docWriter; internal Analyzer analyzer; internal InfoStream infoStream; internal Similarity similarity; internal int docID; internal IEnumerable<IIndexableField> doc; internal string maxTermPrefix; internal DocState(DocumentsWriterPerThread docWriter, InfoStream infoStream) { this.docWriter = docWriter; this.infoStream = infoStream; } // Only called by asserts public virtual bool TestPoint(string name) { return docWriter.TestPoint(name); } public virtual void Clear() { // don't hold onto doc nor analyzer, in case it is // largish: doc = null; analyzer = null; } } internal class FlushedSegment { internal readonly SegmentCommitInfo segmentInfo; internal readonly FieldInfos fieldInfos; internal readonly FrozenBufferedUpdates segmentUpdates; internal readonly IMutableBits liveDocs; internal readonly int delCount; internal FlushedSegment(SegmentCommitInfo segmentInfo, FieldInfos fieldInfos, BufferedUpdates segmentUpdates, IMutableBits liveDocs, int delCount) { this.segmentInfo = segmentInfo; this.fieldInfos = fieldInfos; this.segmentUpdates = segmentUpdates != null && segmentUpdates.Any() ? new FrozenBufferedUpdates(segmentUpdates, true) : null; this.liveDocs = liveDocs; this.delCount = delCount; } } /// <summary> /// Called if we hit an exception at a bad time (when /// updating the index files) and must discard all /// currently buffered docs. this resets our state, /// discarding any docs added since last flush. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual void Abort(ISet<string> createdFiles) { //System.out.println(Thread.currentThread().getName() + ": now abort seg=" + segmentInfo.name); hasAborted = aborting = true; try { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "now abort"); } try { consumer.Abort(); } #pragma warning disable 168 catch (Exception t) #pragma warning restore 168 { } pendingUpdates.Clear(); createdFiles.UnionWith(directory.CreatedFiles); } finally { aborting = false; if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "done abort"); } } } private const bool INFO_VERBOSE = false; internal readonly Codec codec; internal readonly TrackingDirectoryWrapper directory; internal readonly Directory directoryOrig; internal readonly DocState docState; internal readonly DocConsumer consumer; internal readonly Counter bytesUsed; internal SegmentWriteState flushState; // Updates for our still-in-RAM (to be flushed next) segment internal readonly BufferedUpdates pendingUpdates; private readonly SegmentInfo segmentInfo; // Current segment we are working on internal bool aborting = false; // True if an abort is pending internal bool hasAborted = false; // True if the last exception throws by #updateDocument was aborting private FieldInfos.Builder fieldInfos; private readonly InfoStream infoStream; private int numDocsInRAM; internal readonly DocumentsWriterDeleteQueue deleteQueue; private readonly DeleteSlice deleteSlice; private readonly NumberFormatInfo nf = CultureInfo.InvariantCulture.NumberFormat; internal readonly Allocator byteBlockAllocator; internal readonly Int32BlockPool.Allocator intBlockAllocator; private readonly LiveIndexWriterConfig indexWriterConfig; public DocumentsWriterPerThread(string segmentName, Directory directory, LiveIndexWriterConfig indexWriterConfig, InfoStream infoStream, DocumentsWriterDeleteQueue deleteQueue, FieldInfos.Builder fieldInfos) { this.directoryOrig = directory; this.directory = new TrackingDirectoryWrapper(directory); this.fieldInfos = fieldInfos; this.indexWriterConfig = indexWriterConfig; this.infoStream = infoStream; this.codec = indexWriterConfig.Codec; this.docState = new DocState(this, infoStream); this.docState.similarity = indexWriterConfig.Similarity; bytesUsed = Counter.NewCounter(); byteBlockAllocator = new DirectTrackingAllocator(bytesUsed); pendingUpdates = new BufferedUpdates(); intBlockAllocator = new Int32BlockAllocator(bytesUsed); this.deleteQueue = deleteQueue; Debug.Assert(numDocsInRAM == 0, "num docs " + numDocsInRAM); pendingUpdates.Clear(); deleteSlice = deleteQueue.NewSlice(); segmentInfo = new SegmentInfo(directoryOrig, Constants.LUCENE_MAIN_VERSION, segmentName, -1, false, codec, null); Debug.Assert(numDocsInRAM == 0); if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " init seg=" + segmentName + " delQueue=" + deleteQueue); } // this should be the last call in the ctor // it really sucks that we need to pull this within the ctor and pass this ref to the chain! consumer = indexWriterConfig.IndexingChain.GetChain(this); } internal virtual void SetAborting() { aborting = true; } internal virtual bool CheckAndResetHasAborted() { bool retval = hasAborted; hasAborted = false; return retval; } internal bool TestPoint(string message) { if (infoStream.IsEnabled("TP")) { infoStream.Message("TP", message); } return true; } public virtual void UpdateDocument(IEnumerable<IIndexableField> doc, Analyzer analyzer, Term delTerm) { // LUCENENET: .NET doesn't support asserts in release mode if (Lucene.Net.Diagnostics.Debugging.AssertsEnabled) TestPoint("DocumentsWriterPerThread addDocument start"); Debug.Assert(deleteQueue != null); docState.doc = doc; docState.analyzer = analyzer; docState.docID = numDocsInRAM; if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " update delTerm=" + delTerm + " docID=" + docState.docID + " seg=" + segmentInfo.Name); } bool success = false; try { try { consumer.ProcessDocument(fieldInfos); } finally { docState.Clear(); } success = true; } finally { if (!success) { if (!aborting) { // mark document as deleted DeleteDocID(docState.docID); numDocsInRAM++; } else { Abort(filesToDelete); } } } success = false; try { consumer.FinishDocument(); success = true; } finally { if (!success) { Abort(filesToDelete); } } FinishDocument(delTerm); } public virtual int UpdateDocuments(IEnumerable<IEnumerable<IIndexableField>> docs, Analyzer analyzer, Term delTerm) { // LUCENENET: .NET doesn't support asserts in release mode if (Lucene.Net.Diagnostics.Debugging.AssertsEnabled) TestPoint("DocumentsWriterPerThread addDocuments start"); Debug.Assert(deleteQueue != null); docState.analyzer = analyzer; if (INFO_VERBOSE && infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", Thread.CurrentThread.Name + " update delTerm=" + delTerm + " docID=" + docState.docID + " seg=" + segmentInfo.Name); } int docCount = 0; bool allDocsIndexed = false; try { foreach (IEnumerable<IIndexableField> doc in docs) { docState.doc = doc; docState.docID = numDocsInRAM; docCount++; bool success = false; try { consumer.ProcessDocument(fieldInfos); success = true; } finally { if (!success) { // An exc is being thrown... if (!aborting) { // Incr here because finishDocument will not // be called (because an exc is being thrown): numDocsInRAM++; } else { Abort(filesToDelete); } } } success = false; try { consumer.FinishDocument(); success = true; } finally { if (!success) { Abort(filesToDelete); } } FinishDocument(null); } allDocsIndexed = true; // Apply delTerm only after all indexing has // succeeded, but apply it only to docs prior to when // this batch started: if (delTerm != null) { deleteQueue.Add(delTerm, deleteSlice); Debug.Assert(deleteSlice.IsTailItem(delTerm), "expected the delete term as the tail item"); deleteSlice.Apply(pendingUpdates, numDocsInRAM - docCount); } } finally { if (!allDocsIndexed && !aborting) { // the iterator threw an exception that is not aborting // go and mark all docs from this block as deleted int docID = numDocsInRAM - 1; int endDocID = docID - docCount; while (docID > endDocID) { DeleteDocID(docID); docID--; } } docState.Clear(); } return docCount; } [MethodImpl(MethodImplOptions.NoInlining)] private void FinishDocument(Term delTerm) { /* * here we actually finish the document in two steps 1. push the delete into * the queue and update our slice. 2. increment the DWPT private document * id. * * the updated slice we get from 1. holds all the deletes that have occurred * since we updated the slice the last time. */ bool applySlice = numDocsInRAM != 0; if (delTerm != null) { deleteQueue.Add(delTerm, deleteSlice); Debug.Assert(deleteSlice.IsTailItem(delTerm), "expected the delete term as the tail item"); } else { applySlice &= deleteQueue.UpdateSlice(deleteSlice); } if (applySlice) { deleteSlice.Apply(pendingUpdates, numDocsInRAM); } // if we don't need to apply we must reset! else { deleteSlice.Reset(); } ++numDocsInRAM; } // Buffer a specific docID for deletion. Currently only // used when we hit an exception when adding a document internal virtual void DeleteDocID(int docIDUpto) { pendingUpdates.AddDocID(docIDUpto); // NOTE: we do not trigger flush here. this is // potentially a RAM leak, if you have an app that tries // to add docs but every single doc always hits a // non-aborting exception. Allowing a flush here gets // very messy because we are only invoked when handling // exceptions so to do this properly, while handling an // exception we'd have to go off and flush new deletes // which is risky (likely would hit some other // confounding exception). } /// <summary> /// Returns the number of delete terms in this <see cref="DocumentsWriterPerThread"/> /// </summary> public virtual int NumDeleteTerms => pendingUpdates.numTermDeletes; // public for FlushPolicy /// <summary> /// Returns the number of RAM resident documents in this <see cref="DocumentsWriterPerThread"/> /// </summary> public virtual int NumDocsInRAM => numDocsInRAM; // public for FlushPolicy /// <summary> /// Prepares this DWPT for flushing. this method will freeze and return the /// <see cref="DocumentsWriterDeleteQueue"/>s global buffer and apply all pending /// deletes to this DWPT. /// </summary> internal virtual FrozenBufferedUpdates PrepareFlush() { Debug.Assert(numDocsInRAM > 0); FrozenBufferedUpdates globalUpdates = deleteQueue.FreezeGlobalBuffer(deleteSlice); /* deleteSlice can possibly be null if we have hit non-aborting exceptions during indexing and never succeeded adding a document. */ if (deleteSlice != null) { // apply all deletes before we flush and release the delete slice deleteSlice.Apply(pendingUpdates, numDocsInRAM); Debug.Assert(deleteSlice.IsEmpty); deleteSlice.Reset(); } return globalUpdates; } /// <summary> /// Flush all pending docs to a new segment </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual FlushedSegment Flush() { Debug.Assert(numDocsInRAM > 0); Debug.Assert(deleteSlice.IsEmpty, "all deletes must be applied in prepareFlush"); segmentInfo.DocCount = numDocsInRAM; SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segmentInfo, fieldInfos.Finish(), indexWriterConfig.TermIndexInterval, pendingUpdates, new IOContext(new FlushInfo(numDocsInRAM, BytesUsed))); double startMBUsed = BytesUsed / 1024.0 / 1024.0; // Apply delete-by-docID now (delete-byDocID only // happens when an exception is hit processing that // doc, eg if analyzer has some problem w/ the text): if (pendingUpdates.docIDs.Count > 0) { flushState.LiveDocs = codec.LiveDocsFormat.NewLiveDocs(numDocsInRAM); foreach (int delDocID in pendingUpdates.docIDs) { flushState.LiveDocs.Clear(delDocID); } flushState.DelCountOnFlush = pendingUpdates.docIDs.Count; pendingUpdates.bytesUsed.AddAndGet(-pendingUpdates.docIDs.Count * BufferedUpdates.BYTES_PER_DEL_DOCID); pendingUpdates.docIDs.Clear(); } if (aborting) { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush: skip because aborting is set"); } return null; } if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush postings as segment " + flushState.SegmentInfo.Name + " numDocs=" + numDocsInRAM); } bool success = false; try { consumer.Flush(flushState); pendingUpdates.terms.Clear(); segmentInfo.SetFiles(new JCG.HashSet<string>(directory.CreatedFiles)); SegmentCommitInfo segmentInfoPerCommit = new SegmentCommitInfo(segmentInfo, 0, -1L, -1L); if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "new segment has " + (flushState.LiveDocs == null ? 0 : (flushState.SegmentInfo.DocCount - flushState.DelCountOnFlush)) + " deleted docs"); infoStream.Message("DWPT", "new segment has " + (flushState.FieldInfos.HasVectors ? "vectors" : "no vectors") + "; " + (flushState.FieldInfos.HasNorms ? "norms" : "no norms") + "; " + (flushState.FieldInfos.HasDocValues ? "docValues" : "no docValues") + "; " + (flushState.FieldInfos.HasProx ? "prox" : "no prox") + "; " + (flushState.FieldInfos.HasFreq ? "freqs" : "no freqs")); infoStream.Message("DWPT", "flushedFiles=" + string.Format(J2N.Text.StringFormatter.InvariantCulture, "{0}", segmentInfoPerCommit.GetFiles())); infoStream.Message("DWPT", "flushed codec=" + codec); } BufferedUpdates segmentDeletes; if (pendingUpdates.queries.Count == 0 && pendingUpdates.numericUpdates.Count == 0 && pendingUpdates.binaryUpdates.Count == 0) { pendingUpdates.Clear(); segmentDeletes = null; } else { segmentDeletes = pendingUpdates; } if (infoStream.IsEnabled("DWPT")) { double newSegmentSize = segmentInfoPerCommit.GetSizeInBytes() / 1024.0 / 1024.0; infoStream.Message("DWPT", "flushed: segment=" + segmentInfo.Name + " ramUsed=" + startMBUsed.ToString(nf) + " MB" + " newFlushedSize(includes docstores)=" + newSegmentSize.ToString(nf) + " MB" + " docs/MB=" + (flushState.SegmentInfo.DocCount / newSegmentSize).ToString(nf)); } Debug.Assert(segmentInfo != null); FlushedSegment fs = new FlushedSegment(segmentInfoPerCommit, flushState.FieldInfos, segmentDeletes, flushState.LiveDocs, flushState.DelCountOnFlush); SealFlushedSegment(fs); success = true; return fs; } finally { if (!success) { Abort(filesToDelete); } } } private readonly JCG.HashSet<string> filesToDelete = new JCG.HashSet<string>(); public virtual ISet<string> PendingFilesToDelete => filesToDelete; /// <summary> /// Seals the <see cref="Index.SegmentInfo"/> for the new flushed segment and persists /// the deleted documents <see cref="IMutableBits"/>. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] internal virtual void SealFlushedSegment(FlushedSegment flushedSegment) { Debug.Assert(flushedSegment != null); SegmentCommitInfo newSegment = flushedSegment.segmentInfo; IndexWriter.SetDiagnostics(newSegment.Info, IndexWriter.SOURCE_FLUSH); IOContext context = new IOContext(new FlushInfo(newSegment.Info.DocCount, newSegment.GetSizeInBytes())); bool success = false; try { if (indexWriterConfig.UseCompoundFile) { filesToDelete.UnionWith(IndexWriter.CreateCompoundFile(infoStream, directory, CheckAbort.NONE, newSegment.Info, context)); newSegment.Info.UseCompoundFile = true; } // Have codec write SegmentInfo. Must do this after // creating CFS so that 1) .si isn't slurped into CFS, // and 2) .si reflects useCompoundFile=true change // above: codec.SegmentInfoFormat.SegmentInfoWriter.Write(directory, newSegment.Info, flushedSegment.fieldInfos, context); // TODO: ideally we would freeze newSegment here!! // because any changes after writing the .si will be // lost... // Must write deleted docs after the CFS so we don't // slurp the del file into CFS: if (flushedSegment.liveDocs != null) { int delCount = flushedSegment.delCount; Debug.Assert(delCount > 0); if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "flush: write " + delCount + " deletes gen=" + flushedSegment.segmentInfo.DelGen); } // TODO: we should prune the segment if it's 100% // deleted... but merge will also catch it. // TODO: in the NRT case it'd be better to hand // this del vector over to the // shortly-to-be-opened SegmentReader and let it // carry the changes; there's no reason to use // filesystem as intermediary here. SegmentCommitInfo info = flushedSegment.segmentInfo; Codec codec = info.Info.Codec; codec.LiveDocsFormat.WriteLiveDocs(flushedSegment.liveDocs, directory, info, delCount, context); newSegment.DelCount = delCount; newSegment.AdvanceDelGen(); } success = true; } finally { if (!success) { if (infoStream.IsEnabled("DWPT")) { infoStream.Message("DWPT", "hit exception creating compound file for newly flushed segment " + newSegment.Info.Name); } } } } /// <summary> /// Get current segment info we are writing. </summary> internal virtual SegmentInfo SegmentInfo => segmentInfo; public virtual long BytesUsed => bytesUsed.Get() + pendingUpdates.bytesUsed; /// <summary> /// Initial chunks size of the shared byte[] blocks used to /// store postings data /// </summary> internal static readonly int BYTE_BLOCK_NOT_MASK = ~ByteBlockPool.BYTE_BLOCK_MASK; /// <summary> /// if you increase this, you must fix field cache impl for /// getTerms/getTermsIndex requires &lt;= 32768 /// </summary> internal static readonly int MAX_TERM_LENGTH_UTF8 = ByteBlockPool.BYTE_BLOCK_SIZE - 2; /// <summary> /// NOTE: This was IntBlockAllocator in Lucene /// </summary> private class Int32BlockAllocator : Int32BlockPool.Allocator { private readonly Counter bytesUsed; public Int32BlockAllocator(Counter bytesUsed) : base(Int32BlockPool.INT32_BLOCK_SIZE) { this.bytesUsed = bytesUsed; } /// <summary> /// Allocate another int[] from the shared pool /// </summary> public override int[] GetInt32Block() { int[] b = new int[Int32BlockPool.INT32_BLOCK_SIZE]; bytesUsed.AddAndGet(Int32BlockPool.INT32_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT32); return b; } public override void RecycleInt32Blocks(int[][] blocks, int offset, int length) { bytesUsed.AddAndGet(-(length * (Int32BlockPool.INT32_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT32))); } } public override string ToString() { return "DocumentsWriterPerThread [pendingDeletes=" + pendingUpdates + ", segment=" + (segmentInfo != null ? segmentInfo.Name : "null") + ", aborting=" + aborting + ", numDocsInRAM=" + numDocsInRAM + ", deleteQueue=" + deleteQueue + "]"; } } }
using System; using System.Drawing; using System.Drawing.Imaging; namespace Hydra.Framework.ImageProcessing.Analysis.Filters { // //********************************************************************** /// <summary> /// Sharpen /// </summary> //********************************************************************** // public class SharpenEx : IFilter { #region Private Constants // //********************************************************************** /// <summary> /// Default Sigma /// </summary> //********************************************************************** // private const double DefaultSigma_sc = 1.4; // //********************************************************************** /// <summary> /// Default Size /// </summary> //********************************************************************** // private const int DefaultSize_sc = 5; #endregion #region Private Member Variables // //********************************************************************** /// <summary> /// Correlation Filter /// </summary> //********************************************************************** // private Correlation filter_m; // //********************************************************************** /// <summary> /// Image Sigma /// </summary> //********************************************************************** // private double sigma_m = DefaultSigma_sc; // //********************************************************************** /// <summary> /// Image Size /// </summary> //********************************************************************** // private int size_m = DefaultSize_sc; #endregion #region Constructors // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:SharpenEx"/> class. /// </summary> //********************************************************************** // public SharpenEx() { CreateFilter(); } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:SharpenEx"/> class. /// </summary> /// <param name="sigma">The sigma.</param> //********************************************************************** // public SharpenEx(double sigma) { Sigma = sigma; } // //********************************************************************** /// <summary> /// Initialises a new instance of the <see cref="T:SharpenEx"/> class. /// </summary> /// <param name="sigma">The sigma.</param> /// <param name="size">The size.</param> //********************************************************************** // public SharpenEx(double sigma, int size) { Sigma = sigma; Size = size; } #endregion #region Properties // //********************************************************************** /// <summary> /// Gets or sets the sigma property. /// </summary> /// <value>The sigma.</value> //********************************************************************** // public double Sigma { get { return sigma_m; } set { // // get new sigma value // sigma_m = Math.Max(0.5, Math.Min(5.0, value)); // // create filter // CreateFilter(); } } // //********************************************************************** /// <summary> /// Gets or sets the size property. /// </summary> /// <value>The size.</value> //********************************************************************** // public int Size { get { return size_m; } set { size_m = Math.Max(3, Math.Min(21, value | 1)); // // create filter // CreateFilter(); } } #endregion #region Private Members // //********************************************************************** /// <summary> /// Create Gaussian filter /// </summary> //********************************************************************** // private void CreateFilter () { // // create Gaussian function // Hydra.Framework.ImageProcessing.Analysis.Maths.Gaussian gaus = new Hydra.Framework.ImageProcessing.Analysis.Maths.Gaussian(sigma_m); // // create Gaussian kernel // int[,] kernel = gaus.KernelDiscret2D(size_m); // // calculte sum of the kernel // int sum = 0; for (int i = 0; i < size_m; i++) { for (int j = 0; j < size_m; j++) { sum += kernel[i, j]; } } // // recalc kernel // int c = size_m >> 1; for (int i = 0; i < size_m; i++) { for (int j = 0; j < size_m; j++) { if ((i == c) && (j == c)) { // // calculate central value // kernel[i, j] = 2 * sum - kernel[i, j]; } else { // // invert value // kernel[i, j] = -kernel[i, j]; } } } // // create filter // filter_m = new Correlation(kernel); } #endregion #region Public Methods // //********************************************************************** /// <summary> /// Apply filter /// </summary> /// <param name="srcImg">The SRC img.</param> /// <returns></returns> //********************************************************************** // public Bitmap Apply(Bitmap srcImg) { return filter_m.Apply(srcImg); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using ExternalProviderAuthentication.Web.Areas.HelpPage.Models; namespace ExternalProviderAuthentication.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Text; using System.Linq; using System.Xml; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks; using Xunit; namespace Microsoft.Build.UnitTests { sealed public class ResolveNonMSBuildProjectOutput_Tests { private const string attributeProject = "Project"; static internal ITaskItem CreateReferenceItem(string itemSpec, string projectGuid, string package, string name) { TaskItem reference = new TaskItem(itemSpec); if (projectGuid != null) reference.SetMetadata(attributeProject, projectGuid); if (package != null) reference.SetMetadata("Package", package); if (name != null) reference.SetMetadata("Name", name); return reference; } private void TestVerifyReferenceAttributesHelper(string itemSpec, string projectGuid, string package, string name, bool expectedResult, string expectedMissingAttribute) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); string missingAttr = null; bool result = rvpo.VerifyReferenceAttributes(reference, out missingAttr); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"], " + "expected result \"{4}\", actual result \"{5}\", expected missing attr \"{6}\", actual missing attr \"{7}\".", itemSpec, projectGuid, package, name, expectedResult, result, expectedMissingAttribute, missingAttr); Assert.Equal(result, expectedResult); if (result == false) { Assert.Equal(missingAttr, expectedMissingAttribute); } else { Assert.Null(missingAttr); } } [Fact] public void TestVerifyReferenceAttributes() { // a correct reference TestVerifyReferenceAttributesHelper("proj1.csproj", "{CFF438C3-51D1-4E61-BECD-D7D3A6193DF7}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", true, null); // incorrect project guid - should not work TestVerifyReferenceAttributesHelper("proj1.csproj", "{invalid guid}", "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", "CSDep", false, "Project"); } static internal string CreatePregeneratedPathDoc(IDictionary projectOutputs) { string xmlString = "<VSIDEResolvedNonMSBuildProjectOutputs>"; foreach (DictionaryEntry entry in projectOutputs) { xmlString += string.Format("<ProjectRef Project=\"{0}\">{1}</ProjectRef>", entry.Key, entry.Value); } xmlString += "</VSIDEResolvedNonMSBuildProjectOutputs>"; return xmlString; } private void TestResolveHelper(string itemSpec, string projectGuid, string package, string name, Hashtable pregenOutputs, bool expectedResult, string expectedPath) { ITaskItem reference = CreateReferenceItem(itemSpec, projectGuid, package, name); string xmlString = CreatePregeneratedPathDoc(pregenOutputs); ITaskItem resolvedPath; ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.CacheProjectElementsFromXml(xmlString); bool result = rvpo.ResolveProject(reference, out resolvedPath); string message = string.Format("Reference \"{0}\" [project \"{1}\", package \"{2}\", name \"{3}\"] Pregen Xml string : \"{4}\"" + "expected result \"{5}\", actual result \"{6}\", expected path \"{7}\", actual path \"{8}\".", itemSpec, projectGuid, package, name, xmlString, expectedResult, result, expectedPath, resolvedPath); Assert.Equal(result, expectedResult); if (result == true) { Assert.Equal(resolvedPath.ItemSpec, expectedPath); } else { Assert.Null(resolvedPath); } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestResolve() { // empty pre-generated string Hashtable projectOutputs = new Hashtable(); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // non matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // matching project in string projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\correct.dll"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"obj\correct.dll"); // multiple non matching projects in string projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, false, null); // multiple non matching projects in string, one matching projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\correct.dll"); TestResolveHelper("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1", projectOutputs, true, @"obj\correct.dll"); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { TestUnresolvedReferencesHelper(projectRefs, pregenOutputs, null, out unresolvedOutputs, out resolvedOutputs); } private void TestUnresolvedReferencesHelper(ArrayList projectRefs, Hashtable pregenOutputs, Func<string, bool> isManaged, out Hashtable unresolvedOutputs, out Hashtable resolvedOutputs) { ResolveNonMSBuildProjectOutput.GetAssemblyNameDelegate pretendGetAssemblyName = path => { if (isManaged != null && isManaged(path)) { return null; // just don't throw an exception } else { throw new BadImageFormatException(); // the hint that the caller takes for an unmanaged binary. } }; string xmlString = CreatePregeneratedPathDoc(pregenOutputs); MockEngine engine = new MockEngine(); ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); rvpo.GetAssemblyName = pretendGetAssemblyName; rvpo.BuildEngine = engine; rvpo.PreresolvedProjectOutputs = xmlString; rvpo.ProjectReferences = (ITaskItem[])projectRefs.ToArray(typeof(ITaskItem)); bool result = rvpo.Execute(); unresolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.UnresolvedProjectReferences.Length; i++) { unresolvedOutputs[rvpo.UnresolvedProjectReferences[i].ItemSpec] = rvpo.UnresolvedProjectReferences[i]; } resolvedOutputs = new Hashtable(); for (int i = 0; i < rvpo.ResolvedOutputPaths.Length; i++) { resolvedOutputs[rvpo.ResolvedOutputPaths[i].ItemSpec] = rvpo.ResolvedOutputPaths[i]; } } [Fact] [Trait("Category", "mono-osx-failing")] public void TestManagedCheck() { Hashtable unresolvedOutputs = null; Hashtable resolvedOutputs = null; Hashtable projectOutputs = null; ArrayList projectRefs = null; projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @"obj\managed.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\unmanaged.dll"); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, path => (path == @"obj\managed.dll"), out unresolvedOutputs, out resolvedOutputs); Assert.NotNull(resolvedOutputs); Assert.True(resolvedOutputs.Contains(@"obj\managed.dll")); Assert.True(resolvedOutputs.Contains(@"obj\unmanaged.dll")); Assert.Equal("true", ((ITaskItem)resolvedOutputs[@"obj\managed.dll"]).GetMetadata("ManagedAssembly")); Assert.NotEqual("true", ((ITaskItem)resolvedOutputs[@"obj\unmanaged.dll"]).GetMetadata("ManagedAssembly")); } /// <summary> /// Verifies that the UnresolvedProjectReferences output parameter is populated correctly. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestUnresolvedReferences() { Hashtable unresolvedOutputs = null; Hashtable resolvedOutputs = null; Hashtable projectOutputs = null; ArrayList projectRefs = null; projectRefs = new ArrayList(); projectRefs.Add(CreateReferenceItem("MCDep1.vcproj", "{2F6BBCC3-7111-4116-A68B-000000000000}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep1")); projectRefs.Add(CreateReferenceItem("MCDep2.vcproj", "{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}", "MCDep2")); // 1. multiple project refs, none resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 1" Assert.Equal(2, unresolvedOutputs.Count); // "Two unresolved refs expected for case 1" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); // 2. multiple project refs, one resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\correct.dll"); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 2" Assert.True(resolvedOutputs.ContainsKey(@"obj\correct.dll")); Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 2" Assert.Equal(unresolvedOutputs["MCDep1.vcproj"], projectRefs[0]); // 3. multiple project refs, all resolvable projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\correct.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @"obj\correct2.dll"); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Equal(2, resolvedOutputs.Count); // "Two resolved refs expected for case 3" Assert.True(resolvedOutputs.ContainsKey(@"obj\correct.dll")); Assert.True(resolvedOutputs.ContainsKey(@"obj\correct2.dll")); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 3" // 4. multiple project refs, all failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @""); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 4" Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 4" // 5. multiple project refs, one resolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-34CFC76F37C5}", @"obj\correct.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Single(resolvedOutputs); // "One resolved ref expected for case 5" Assert.True(resolvedOutputs.ContainsKey(@"obj\correct.dll")); Assert.Empty(unresolvedOutputs); // "No unresolved refs expected for case 5" // 6. multiple project refs, one unresolvable, one failed to resolve projectOutputs = new Hashtable(); projectOutputs.Add("{11111111-1111-1111-1111-111111111111}", @"obj\wrong.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111112}", @"obj\wrong2.dll"); projectOutputs.Add("{11111111-1111-1111-1111-111111111113}", @"obj\wrong3.dll"); projectOutputs.Add("{2F6BBCC3-7111-4116-A68B-000000000000}", @""); TestUnresolvedReferencesHelper(projectRefs, projectOutputs, out unresolvedOutputs, out resolvedOutputs); Assert.Empty(resolvedOutputs); // "No resolved refs expected for case 6" Assert.Single(unresolvedOutputs); // "One unresolved ref expected for case 6" Assert.Equal(unresolvedOutputs["MCDep2.vcproj"], projectRefs[1]); } [Fact] public void TestVerifyProjectReferenceItem() { ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); ITaskItem[] taskItems = new ITaskItem[1]; // bad GUID - this reference is invalid taskItems[0] = new TaskItem("projectReference"); taskItems[0].SetMetadata(attributeProject, "{invalid guid}"); MockEngine engine = new MockEngine(); rvpo.BuildEngine = engine; Assert.True(rvpo.VerifyProjectReferenceItems(taskItems, false /* treat problems as warnings */)); Assert.Equal(1, engine.Warnings); Assert.Equal(0, engine.Errors); engine.AssertLogContains("MSB3107"); engine = new MockEngine(); rvpo.BuildEngine = engine; Assert.False(rvpo.VerifyProjectReferenceItems(taskItems, true /* treat problems as errors */)); Assert.Equal(0, engine.Warnings); Assert.Equal(1, engine.Errors); engine.AssertLogContains("MSB3107"); } } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Core.Templates; using Umbraco.Cms.Core.Web; using Umbraco.Extensions; namespace Umbraco.Cms.Web.Common.Templates { /// <summary> /// This is used purely for the RenderTemplate functionality in Umbraco /// </summary> /// <remarks> /// This allows you to render an MVC template based purely off of a node id and an optional alttemplate id as string output. /// </remarks> internal class TemplateRenderer : ITemplateRenderer { private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly IPublishedRouter _publishedRouter; private readonly IFileService _fileService; private readonly ILocalizationService _languageService; private readonly WebRoutingSettings _webRoutingSettings; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ICompositeViewEngine _viewEngine; private readonly IModelMetadataProvider _modelMetadataProvider; private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory; public TemplateRenderer( IUmbracoContextAccessor umbracoContextAccessor, IPublishedRouter publishedRouter, IFileService fileService, ILocalizationService textService, IOptions<WebRoutingSettings> webRoutingSettings, IHttpContextAccessor httpContextAccessor, ICompositeViewEngine viewEngine, IModelMetadataProvider modelMetadataProvider, ITempDataDictionaryFactory tempDataDictionaryFactory) { _umbracoContextAccessor = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor)); _publishedRouter = publishedRouter ?? throw new ArgumentNullException(nameof(publishedRouter)); _fileService = fileService ?? throw new ArgumentNullException(nameof(fileService)); _languageService = textService ?? throw new ArgumentNullException(nameof(textService)); _webRoutingSettings = webRoutingSettings.Value ?? throw new ArgumentNullException(nameof(webRoutingSettings)); _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); _viewEngine = viewEngine ?? throw new ArgumentNullException(nameof(viewEngine)); _modelMetadataProvider = modelMetadataProvider; _tempDataDictionaryFactory = tempDataDictionaryFactory; } public async Task RenderAsync(int pageId, int? altTemplateId, StringWriter writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // instantiate a request and process // important to use CleanedUmbracoUrl - lowercase path-only version of the current URL, though this isn't going to matter // terribly much for this implementation since we are just creating a doc content request to modify it's properties manually. var requestBuilder = await _publishedRouter.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl); var doc = umbracoContext.Content.GetById(pageId); if (doc == null) { writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", pageId); return; } // in some cases the UmbracoContext will not have a PublishedRequest assigned to it if we are not in the // execution of a front-end rendered page. In this case set the culture to the default. // set the culture to the same as is currently rendering if (umbracoContext.PublishedRequest == null) { var defaultLanguage = _languageService.GetAllLanguages().FirstOrDefault(); requestBuilder.SetCulture(defaultLanguage == null ? CultureInfo.CurrentUICulture.Name : defaultLanguage.CultureInfo.Name); } else { requestBuilder.SetCulture(umbracoContext.PublishedRequest.Culture); } // set the doc that was found by id requestBuilder.SetPublishedContent(doc); // set the template, either based on the AltTemplate found or the standard template of the doc var templateId = _webRoutingSettings.DisableAlternativeTemplates || !altTemplateId.HasValue ? doc.TemplateId : altTemplateId.Value; if (templateId.HasValue) { requestBuilder.SetTemplate(_fileService.GetTemplate(templateId.Value)); } // if there is not template then exit if (requestBuilder.HasTemplate() == false) { if (altTemplateId.HasValue == false) { writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId); } else { writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", altTemplateId); } return; } // First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these // after this page has rendered. SaveExistingItems(out IPublishedRequest oldPublishedRequest); IPublishedRequest contentRequest = requestBuilder.Build(); try { // set the new items on context objects for this templates execution SetNewItemsOnContextObjects(contentRequest); // Render the template ExecuteTemplateRendering(writer, contentRequest); } finally { // restore items on context objects to continuing rendering the parent template RestoreItems(oldPublishedRequest); } } private void ExecuteTemplateRendering(TextWriter sw, IPublishedRequest request) { var httpContext = _httpContextAccessor.GetRequiredHttpContext(); // isMainPage is set to true here to ensure ViewStart(s) found in the view hierarchy are rendered var viewResult = _viewEngine.GetView(null, $"~/Views/{request.GetTemplateAlias()}.cshtml", isMainPage: true); if (viewResult.Success == false) { throw new InvalidOperationException($"A view with the name {request.GetTemplateAlias()} could not be found"); } var viewData = new ViewDataDictionary(_modelMetadataProvider, new ModelStateDictionary()) { Model = request.PublishedContent }; var writer = new StringWriter(); var viewContext = new ViewContext( new ActionContext(httpContext, httpContext.GetRouteData(), new ControllerActionDescriptor()), viewResult.View, viewData, _tempDataDictionaryFactory.GetTempData(httpContext), writer, new HtmlHelperOptions() ); viewResult.View.RenderAsync(viewContext).GetAwaiter().GetResult(); var output = writer.GetStringBuilder().ToString(); sw.Write(output); } // TODO: I feel like we need to do more than this, pretty sure we need to replace the UmbracoRouteValues // HttpRequest feature too while this renders. private void SetNewItemsOnContextObjects(IPublishedRequest request) { var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // now, set the new ones for this page execution umbracoContext.PublishedRequest = request; } /// <summary> /// Save all items that we know are used for rendering execution to variables so we can restore after rendering /// </summary> private void SaveExistingItems(out IPublishedRequest oldPublishedRequest) { var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); // Many objects require that these legacy items are in the http context items... before we render this template we need to first // save the values in them so that we can re-set them after we render so the rest of the execution works as per normal oldPublishedRequest = umbracoContext.PublishedRequest; } /// <summary> /// Restores all items back to their context's to continue normal page rendering execution /// </summary> private void RestoreItems(IPublishedRequest oldPublishedRequest) { var umbracoContext = _umbracoContextAccessor.GetRequiredUmbracoContext(); umbracoContext.PublishedRequest = oldPublishedRequest; } } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Backend/tk2dBaseSprite")] /// <summary> /// Sprite base class. Performs target agnostic functionality and manages state parameters. /// </summary> public abstract class tk2dBaseSprite : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { /// <summary> /// Anchor. /// NOTE: The order in this enum is deliberate, to initialize at LowerLeft for backwards compatibility. /// This is also the reason it is local here. Other Anchor enums are NOT compatbile. Do not cast. /// </summary> public enum Anchor { /// <summary>Lower left</summary> LowerLeft, /// <summary>Lower center</summary> LowerCenter, /// <summary>Lower right</summary> LowerRight, /// <summary>Middle left</summary> MiddleLeft, /// <summary>Middle center</summary> MiddleCenter, /// <summary>Middle right</summary> MiddleRight, /// <summary>Upper left</summary> UpperLeft, /// <summary>Upper center</summary> UpperCenter, /// <summary>Upper right</summary> UpperRight, } /// <summary> /// This is now private. You should use <see cref="tk2dBaseSprite.Collection">Collection</see> if you wish to read this value. /// Use <see cref="tk2dBaseSprite.SwitchCollectionAndSprite">SwitchCollectionAndSprite</see> when you need to switch sprite collection. /// </summary> [SerializeField] private tk2dSpriteCollectionData collection; /// <summary> /// Deprecation warning: the set accessor will be removed in a future version. /// Use <see cref="tk2dBaseSprite.SwitchCollectionAndSprite">SwitchCollectionAndSprite</see> when you need to switch sprite collection. /// </summary> public tk2dSpriteCollectionData Collection { get { return collection; } set { collection = value; collectionInst = collection.inst; } } // This is the active instance of the sprite collection protected tk2dSpriteCollectionData collectionInst; [SerializeField] protected Color _color = Color.white; [SerializeField] protected Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); [SerializeField] protected int _spriteId = 0; /// <summary> /// Specifies if this sprite is kept pixel perfect /// </summary> public bool pixelPerfect = false; /// <summary> /// Internal cached version of the box collider created for this sprite, if present. /// </summary> public BoxCollider boxCollider = null; /// <summary> /// Internal cached version of the mesh collider created for this sprite, if present. /// </summary> public MeshCollider meshCollider = null; public Vector3[] meshColliderPositions = null; public Mesh meshColliderMesh = null; // This is unfortunate, but required due to the unpredictable script execution order in Unity. // The only problem happens in Awake(), where if another class is Awaken before this one, and tries to // modify this instance before it is initialized, very bad things could happen. void InitInstance() { if (collectionInst == null && collection != null) collectionInst = collection.inst; } /// <summary> /// Gets or sets the color. /// </summary> /// <value> /// Please note the range for a Unity Color is 0..1 and not 0..255. /// </value> public Color color { get { return _color; } set { if (value != _color) { _color = value; InitInstance(); UpdateColors(); } } } /// <summary> /// Gets or sets the scale. /// </summary> /// <value> /// Use the sprite scale method as opposed to transform.localScale to avoid breaking dynamic batching. /// </value> public Vector3 scale { get { return _scale; } set { if (value != _scale) { _scale = value; InitInstance(); UpdateVertices(); #if UNITY_EDITOR EditMode__CreateCollider(); #else UpdateCollider(); #endif } } } /// <summary> /// Flips the sprite horizontally. /// </summary> public void FlipX() { scale = new Vector3(-_scale.x, _scale.y, _scale.z); } /// <summary> /// Flips the sprite vertically. /// </summary> public void FlipY() { scale = new Vector3(_scale.x, -_scale.y, _scale.z); } /// <summary> /// Gets or sets the sprite identifier. /// </summary> /// <value> /// The spriteId is a unique number identifying each sprite. /// Use <see cref="tk2dBaseSprite.GetSpriteIdByName">GetSpriteIdByName</see> to resolve an identifier from the current sprite collection. /// </value> public int spriteId { get { return _spriteId; } set { if (value != _spriteId) { InitInstance(); value = Mathf.Clamp(value, 0, collectionInst.spriteDefinitions.Length - 1); if (_spriteId < 0 || _spriteId >= collectionInst.spriteDefinitions.Length || GetCurrentVertexCount() != collectionInst.spriteDefinitions[value].positions.Length || collectionInst.spriteDefinitions[_spriteId].complexGeometry != collectionInst.spriteDefinitions[value].complexGeometry) { _spriteId = value; UpdateGeometry(); } else { _spriteId = value; UpdateVertices(); } UpdateMaterial(); UpdateCollider(); } } } /// <summary> /// Sets the sprite by identifier. /// </summary> public void SetSprite(int newSpriteId) { this.spriteId = newSpriteId; } /// <summary> /// Sets the sprite by name. The sprite will be selected from the current collection. /// </summary> public bool SetSprite(string spriteName) { int spriteId = collection.GetSpriteIdByName(spriteName, -1); if (spriteId != -1) { SetSprite(spriteId); } return spriteId != -1; } /// <summary> /// Sets sprite by identifier from the new collection. /// </summary> public void SetSprite(tk2dSpriteCollectionData newCollection, int spriteId) { SwitchCollectionAndSprite(newCollection, spriteId); } /// <summary> /// Sets sprite by name from the new collection. /// </summary> public bool SetSprite(tk2dSpriteCollectionData newCollection, string spriteName) { return SwitchCollectionAndSprite(newCollection, spriteName); } /// <summary> /// Switches the sprite collection and sprite. /// Simply set the <see cref="tk2dBaseSprite.spriteId">spriteId</see> property when you don't need to switch the sprite collection. /// This will be deprecated in a future release, use SetSprite instead. /// </summary> /// <param name='newCollection'> /// A reference to the sprite collection to switch to. /// </param> /// <param name='newSpriteId'> /// New sprite identifier. /// </param> public void SwitchCollectionAndSprite(tk2dSpriteCollectionData newCollection, int newSpriteId) { bool switchedCollection = false; if (Collection != newCollection) { collection = newCollection; collectionInst = collection.inst; _spriteId = -1; // force an update, but only when the collection has changed switchedCollection = true; } spriteId = newSpriteId; if (switchedCollection) { UpdateMaterial(); } } /// <summary> /// Switches the sprite collection and sprite. /// Simply set the <see cref="tk2dBaseSprite.spriteId">spriteId</see> property when you don't need to switch the sprite collection. /// This will be deprecated in a future release, use SetSprite instead. /// </summary> /// <param name='newCollection'> /// A reference to the sprite collection to switch to. /// </param> /// <param name='spriteName'> /// Sprite name. /// </param> public bool SwitchCollectionAndSprite(tk2dSpriteCollectionData newCollection, string spriteName) { int spriteId = newCollection.GetSpriteIdByName(spriteName, -1); if (spriteId != -1) { SwitchCollectionAndSprite(newCollection, spriteId); } return spriteId != -1; } /// <summary> /// Makes the sprite pixel perfect to the active camera. /// Automatically detects <see cref="tk2dCamera"/> if present /// Otherwise uses Camera.main /// </summary> public void MakePixelPerfect() { float s = 1.0f; tk2dPixelPerfectHelper pph = tk2dPixelPerfectHelper.inst; if (pph) { if (pph.CameraIsOrtho) { s = pph.scaleK; } else { s = pph.scaleK + pph.scaleD * transform.position.z; } } else if (tk2dCamera.inst) { if (Collection.version < 2) { Debug.LogError("Need to rebuild sprite collection."); } s = Collection.halfTargetHeight; } else if (Camera.main) { if (Camera.main.isOrthoGraphic) { s = Camera.main.orthographicSize; } else { float zdist = (transform.position.z - Camera.main.transform.position.z); s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fov, zdist); } } else { Debug.LogError("Main camera not found."); } s *= Collection.invOrthoSize; scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s); } protected abstract void UpdateMaterial(); // update material when switching spritecollection protected abstract void UpdateColors(); // reupload color data only protected abstract void UpdateVertices(); // reupload vertex data only protected abstract void UpdateGeometry(); // update full geometry (including indices) protected abstract int GetCurrentVertexCount(); // return current vertex count /// <summary> /// Rebuilds the mesh data for this sprite. Not usually necessary to call this, unless some internal states are modified. /// </summary> public abstract void Build(); /// <summary> /// Resolves a sprite name and returns a unique id for the sprite. /// Convenience alias of <see cref="tk2dSpriteCollectionData.GetSpriteIdByName"/> /// </summary> /// <returns> /// Unique Sprite Id. /// </returns> /// <param name='name'>Case sensitive sprite name, as defined in the sprite collection. This is usually the source filename excluding the extension</param> public int GetSpriteIdByName(string name) { InitInstance(); return collectionInst.GetSpriteIdByName(name); } /// <summary> /// Adds a tk2dBaseSprite derived class as a component to the gameObject passed in, setting up necessary parameters /// and building geometry. /// </summary> public static T AddComponent<T>(GameObject go, tk2dSpriteCollectionData spriteCollection, int spriteId) where T : tk2dBaseSprite { T sprite = go.AddComponent<T>(); sprite._spriteId = -1; sprite.SetSprite(spriteCollection, spriteId); sprite.Build(); return sprite; } /// <summary> /// Adds a tk2dBaseSprite derived class as a component to the gameObject passed in, setting up necessary parameters /// and building geometry. Shorthand using sprite name /// </summary> public static T AddComponent<T>(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName) where T : tk2dBaseSprite { int spriteId = spriteCollection.GetSpriteIdByName(spriteName, -1); if (spriteId == -1) { Debug.LogError( string.Format("Unable to find sprite named {0} in sprite collection {1}", spriteName, spriteCollection.spriteCollectionName) ); return null; } else { return AddComponent<T>(go, spriteCollection, spriteId); } } protected int GetNumVertices() { InitInstance(); return collectionInst.spriteDefinitions[spriteId].positions.Length; } protected int GetNumIndices() { InitInstance(); return collectionInst.spriteDefinitions[spriteId].indices.Length; } protected void SetPositions(Vector3[] positions, Vector3[] normals, Vector4[] tangents) { var sprite = collectionInst.spriteDefinitions[spriteId]; int numVertices = GetNumVertices(); for (int i = 0; i < numVertices; ++i) { positions[i].x = sprite.positions[i].x * _scale.x; positions[i].y = sprite.positions[i].y * _scale.y; positions[i].z = sprite.positions[i].z * _scale.z; } // The secondary test sprite.normals != null must have been performed prior to this function call if (normals.Length > 0) { for (int i = 0; i < numVertices; ++i) { normals[i] = sprite.normals[i]; } } // The secondary test sprite.tangents != null must have been performed prior to this function call if (tangents.Length > 0) { for (int i = 0; i < numVertices; ++i) { tangents[i] = sprite.tangents[i]; } } } protected void SetColors(Color32[] dest) { Color c = _color; if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; } Color32 c32 = c; int numVertices = GetNumVertices(); for (int i = 0; i < numVertices; ++i) dest[i] = c32; } /// <summary> /// Gets the local space bounds of the sprite. /// </summary> /// <returns> /// Local space bounds /// </returns> public Bounds GetBounds() { InitInstance(); var sprite = collectionInst.spriteDefinitions[_spriteId]; return new Bounds(new Vector3(sprite.boundsData[0].x * _scale.x, sprite.boundsData[0].y * _scale.y, sprite.boundsData[0].z * _scale.z), new Vector3(sprite.boundsData[1].x * _scale.x, sprite.boundsData[1].y * _scale.y, sprite.boundsData[1].z * _scale.z)); } /// <summary> /// Gets untrimmed local space bounds of the sprite. This is the size of the sprite before 2D Toolkit trims away empty space in the sprite. /// Use this when you need to position sprites in a grid, etc, when the trimmed bounds is not sufficient. /// </summary> /// <returns> /// Local space untrimmed bounds /// </returns> public Bounds GetUntrimmedBounds() { InitInstance(); var sprite = collectionInst.spriteDefinitions[_spriteId]; return new Bounds(new Vector3(sprite.untrimmedBoundsData[0].x * _scale.x, sprite.untrimmedBoundsData[0].y * _scale.y, sprite.untrimmedBoundsData[0].z * _scale.z), new Vector3(sprite.untrimmedBoundsData[1].x * _scale.x, sprite.untrimmedBoundsData[1].y * _scale.y, sprite.untrimmedBoundsData[1].z * _scale.z)); } /// <summary> /// Gets the current sprite definition. /// </summary> /// <returns> /// <see cref="tk2dSpriteDefinition"/> for the currently active sprite. /// </returns> public tk2dSpriteDefinition GetCurrentSpriteDef() { InitInstance(); return collectionInst.spriteDefinitions[_spriteId]; } /// <summary> /// Gets the current sprite definition. /// </summary> /// <returns> /// <see cref="tk2dSpriteDefinition"/> for the currently active sprite. /// </returns> public tk2dSpriteDefinition CurrentSprite { get { InitInstance(); return collectionInst.spriteDefinitions[_spriteId]; } } // Unity functions public void Start() { if (pixelPerfect) MakePixelPerfect(); } // Collider setup protected virtual bool NeedBoxCollider() { return false; } protected virtual void UpdateCollider() { var sprite = collectionInst.spriteDefinitions[_spriteId]; if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box && boxCollider == null) { // Has the user created a box collider? boxCollider = gameObject.GetComponent<BoxCollider>(); if (boxCollider == null) { // create box collider at runtime. this won't get removed from the object boxCollider = gameObject.AddComponent<BoxCollider>(); } } if (boxCollider != null) { if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) { boxCollider.center = new Vector3(sprite.colliderVertices[0].x * _scale.x, sprite.colliderVertices[0].y * _scale.y, sprite.colliderVertices[0].z * _scale.z); boxCollider.extents = new Vector3(sprite.colliderVertices[1].x * _scale.x, sprite.colliderVertices[1].y * _scale.y, sprite.colliderVertices[1].z * _scale.z); } else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset) { // Don't do anything here, for backwards compatibility } else // in all cases, if the collider doesn't match is requested, null it out { if (boxCollider != null) { // move the box far far away, boxes with zero extents still collide boxCollider.center = new Vector3(0, 0, -100000.0f); boxCollider.extents = Vector3.zero; } } } } // This is separate to UpdateCollider, as UpdateCollider can only work with BoxColliders, and will NOT create colliders protected virtual void CreateCollider() { var sprite = collectionInst.spriteDefinitions[_spriteId]; if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset) { // do not attempt to create or modify anything if it is Unset return; } // User has created a collider if (collider != null) { boxCollider = GetComponent<BoxCollider>(); meshCollider = GetComponent<MeshCollider>(); } if ((NeedBoxCollider() || sprite.colliderType == tk2dSpriteDefinition.ColliderType.Box) && meshCollider == null) { if (boxCollider == null) { boxCollider = gameObject.AddComponent<BoxCollider>(); } } else if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Mesh && boxCollider == null) { // this should not be updated again (apart from scale changes in the editor, where we force regeneration of colliders) if (meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>(); if (meshColliderMesh == null) meshColliderMesh = new Mesh(); meshColliderMesh.Clear(); meshColliderPositions = new Vector3[sprite.colliderVertices.Length]; for (int i = 0; i < meshColliderPositions.Length; ++i) meshColliderPositions[i] = new Vector3(sprite.colliderVertices[i].x * _scale.x, sprite.colliderVertices[i].y * _scale.y, sprite.colliderVertices[i].z * _scale.z); meshColliderMesh.vertices = meshColliderPositions; float s = _scale.x * _scale.y * _scale.z; meshColliderMesh.triangles = (s >= 0.0f)?sprite.colliderIndicesFwd:sprite.colliderIndicesBack; meshCollider.sharedMesh = meshColliderMesh; meshCollider.convex = sprite.colliderConvex; // this is required so our mesh pivot is at the right point if (rigidbody) rigidbody.centerOfMass = Vector3.zero; } else if (sprite.colliderType != tk2dSpriteDefinition.ColliderType.None) { // This warning is not applicable in the editor if (Application.isPlaying) { Debug.LogError("Invalid mesh collider on sprite, please remove and try again."); } } UpdateCollider(); } #if UNITY_EDITOR public virtual void EditMode__CreateCollider() { // Revert to runtime behaviour when the game is running if (Application.isPlaying) { UpdateCollider(); return; } var sprite = collectionInst.spriteDefinitions[_spriteId]; if (sprite.colliderType == tk2dSpriteDefinition.ColliderType.Unset) return; PhysicMaterial physicsMaterial = collider?collider.sharedMaterial:null; bool isTrigger = collider?collider.isTrigger:false; if (boxCollider) { DestroyImmediate(boxCollider, true); } if (meshCollider) { DestroyImmediate(meshCollider, true); if (meshColliderMesh) DestroyImmediate(meshColliderMesh, true); } CreateCollider(); if (collider) { collider.isTrigger = isTrigger; collider.material = physicsMaterial; } } #endif protected void Awake() { if (collection != null) { collectionInst = collection.inst; } } // tk2dRuntime.ISpriteCollectionEditor public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { return Collection == spriteCollection; } public virtual void ForceBuild() { collectionInst = collection.inst; if (spriteId < 0 || spriteId >= collectionInst.spriteDefinitions.Length) spriteId = 0; Build(); #if UNITY_EDITOR EditMode__CreateCollider(); #endif } /// <summary> /// Create a sprite (and gameObject) displaying the region of the texture specified. /// Use <see cref="tk2dSpriteCollectionData.CreateFromTexture"/> if you need to create a sprite collection /// with multiple sprites. /// </summary> public static GameObject CreateFromTexture<T>(Texture texture, tk2dRuntime.SpriteCollectionSize size, Rect region, Vector2 anchor) where T : tk2dBaseSprite { tk2dSpriteCollectionData data = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(texture, size, region, anchor); if (data == null) return null; GameObject spriteGo = new GameObject(); tk2dBaseSprite.AddComponent<T>(spriteGo, data, 0); return spriteGo; } }
#region License /* * WebSocketServiceManager.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using WebSocketSharp.Net; namespace WebSocketSharp.Server { /// <summary> /// Manages the WebSocket services provided by the <see cref="HttpServer"/> or /// <see cref="WebSocketServer"/>. /// </summary> public class WebSocketServiceManager { #region Private Fields private volatile bool _clean; private Dictionary<string, WebSocketServiceHost> _hosts; private Logger _logger; private volatile ServerState _state; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketServiceManager () : this (new Logger ()) { } internal WebSocketServiceManager (Logger logger) { _logger = logger; _clean = true; _hosts = new Dictionary<string, WebSocketServiceHost> (); _state = ServerState.Ready; _sync = ((ICollection) _hosts).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); } #endregion #region Public Properties /// <summary> /// Gets the number of the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the services. /// </value> public int Count { get { lock (_sync) return _hosts.Count; } } /// <summary> /// Gets the host instances for the Websocket services. /// </summary> /// <value> /// An <c>IEnumerable&lt;WebSocketServiceHost&gt;</c> instance that provides an enumerator /// which supports the iteration over the collection of the host instances for the services. /// </value> public IEnumerable<WebSocketServiceHost> Hosts { get { lock (_sync) return _hosts.Values.ToList (); } } /// <summary> /// Gets the WebSocket service host with the specified <paramref name="path"/>. /// </summary> /// <value> /// A <see cref="WebSocketServiceHost"/> instance that provides the access to /// the information in the service, or <see langword="null"/> if it's not found. /// </value> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to find. /// </param> public WebSocketServiceHost this[string path] { get { WebSocketServiceHost host; TryGetServiceHost (path, out host); return host; } } /// <summary> /// Gets a value indicating whether the manager cleans up the inactive sessions /// in the WebSocket services periodically. /// </summary> /// <value> /// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _clean; } internal set { lock (_sync) { if (!(value ^ _clean)) return; _clean = value; foreach (var host in _hosts.Values) host.KeepClean = value; } } } /// <summary> /// Gets the paths for the WebSocket services. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which supports /// the iteration over the collection of the paths for the services. /// </value> public IEnumerable<string> Paths { get { lock (_sync) return _hosts.Keys.ToList (); } } /// <summary> /// Gets the total number of the sessions in the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the total number of the sessions in the services. /// </value> public int SessionCount { get { var cnt = 0; foreach (var host in Hosts) { if (_state != ServerState.Start) break; cnt += host.Sessions.Count; } return cnt; } } /// <summary> /// Gets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. /// </value> public TimeSpan WaitTime { get { return _waitTime; } internal set { lock (_sync) { if (value == _waitTime) return; _waitTime = value; foreach (var host in _hosts.Values) host.WaitTime = value; } } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary<CompressionMethod, byte[]> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) break; host.Sessions.Broadcast (opcode, data, cache); } if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary<CompressionMethod, Stream> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) break; host.Sessions.Broadcast (opcode, stream, cache); } if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, data, completed)); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, stream, completed)); } private Dictionary<string, Dictionary<string, bool>> broadping ( byte[] frameAsBytes, TimeSpan timeout) { var ret = new Dictionary<string, Dictionary<string, bool>> (); foreach (var host in Hosts) { if (_state != ServerState.Start) break; ret.Add (host.Path, host.Sessions.Broadping (frameAsBytes, timeout)); } return ret; } #endregion #region Internal Methods internal void Add<TBehavior> (string path, Func<TBehavior> initializer) where TBehavior : WebSocketBehavior { lock (_sync) { path = HttpUtility.UrlDecode (path).TrimEndSlash (); WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) { _logger.Error ( "A WebSocket service with the specified path already exists:\n path: " + path); return; } host = new WebSocketServiceHost<TBehavior> (path, initializer, _logger); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } internal bool InternalTryGetServiceHost (string path, out WebSocketServiceHost host) { bool ret; lock (_sync) { path = HttpUtility.UrlDecode (path).TrimEndSlash (); ret = _hosts.TryGetValue (path, out host); } if (!ret) _logger.Error ( "A WebSocket service with the specified path isn't found:\n path: " + path); return ret; } internal bool Remove (string path) { WebSocketServiceHost host; lock (_sync) { path = HttpUtility.UrlDecode (path).TrimEndSlash (); if (!_hosts.TryGetValue (path, out host)) { _logger.Error ( "A WebSocket service with the specified path isn't found:\n path: " + path); return false; } _hosts.Remove (path); } if (host.State == ServerState.Start) host.Stop ((ushort) CloseStatusCode.Away, null); return true; } internal void Start () { lock (_sync) { foreach (var host in _hosts.Values) host.Start (); _state = ServerState.Start; } } internal void Stop (CloseEventArgs e, bool send, bool wait) { lock (_sync) { _state = ServerState.ShuttingDown; var bytes = send ? WebSocketFrame.CreateCloseFrame (e.PayloadData, false).ToArray () : null; var timeout = wait ? _waitTime : TimeSpan.Zero; foreach (var host in _hosts.Values) host.Sessions.Stop (e, bytes, timeout); _hosts.Clear (); _state = ServerState.Stop; } } #endregion #region Public Methods /// <summary> /// Sends binary <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> public void Broadcast (byte[] data) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// <summary> /// Sends text <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> public void Broadcast (string data) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } var bytes = data.UTF8Encode (); if (bytes.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, bytes, null); else broadcast (Opcode.Text, new MemoryStream (bytes), null); } /// <summary> /// Sends binary <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (byte[] data, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// <summary> /// Sends text <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (string data, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } var bytes = data.UTF8Encode (); if (bytes.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, bytes, completed); else broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed); } /// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously to /// every client in the WebSocket services. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (Stream stream, int length, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameters (stream, length); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, completed); else broadcast (Opcode.Binary, new MemoryStream (data), completed); }, ex => _logger.Fatal (ex.ToString ())); } /// <summary> /// Sends a Ping to every client in the WebSocket services. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c> that contains /// a collection of pairs of a service path and a collection of pairs of a session ID /// and a value indicating whether the manager received a Pong from each client in a time, /// or <see langword="null"/> if this method isn't available. /// </returns> public Dictionary<string, Dictionary<string, bool>> Broadping () { var msg = _state.CheckIfAvailable (false, true, false); if (msg != null) { _logger.Error (msg); return null; } return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to every client in /// the WebSocket services. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c> that contains /// a collection of pairs of a service path and a collection of pairs of a session ID /// and a value indicating whether the manager received a Pong from each client in a time, /// or <see langword="null"/> if this method isn't available or <paramref name="message"/> /// is invalid. /// </returns> /// <param name="message"> /// A <see cref="string"/> that represents the message to send. /// </param> public Dictionary<string, Dictionary<string, bool>> Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); byte[] data = null; var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckPingParameter (message, out data); if (msg != null) { _logger.Error (msg); return null; } return broadping (WebSocketFrame.CreatePingFrame (data, false).ToArray (), _waitTime); } /// <summary> /// Tries to get the WebSocket service host with the specified <paramref name="path"/>. /// </summary> /// <returns> /// <c>true</c> if the service is successfully found; otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents the absolute path to the service to find. /// </param> /// <param name="host"> /// When this method returns, a <see cref="WebSocketServiceHost"/> instance that /// provides the access to the information in the service, or <see langword="null"/> /// if it's not found. This parameter is passed uninitialized. /// </param> public bool TryGetServiceHost (string path, out WebSocketServiceHost host) { var msg = _state.CheckIfAvailable (false, true, false) ?? path.CheckIfValidServicePath (); if (msg != null) { _logger.Error (msg); host = null; return false; } return InternalTryGetServiceHost (path, out host); } #endregion } }