context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Web; using System.IO; using Cuyahoga.Core; using Cuyahoga.Core.Domain; using Cuyahoga.Web.Util; namespace Cuyahoga.Web.UI { /// <summary> /// Base class for all module user controls. /// Credits to the DotNetNuke team (http://www.dotnetnuke.com) for the output caching idea! /// </summary> public class BaseModuleControl : LocalizedUserControl { private ModuleBase _module; private PageEngine _pageEngine; private string _cachedOutput; private bool _displaySyndicationIcon; /// <summary> /// Indicator if there is cached content. The derived ModuleControls should determine whether to /// load content or not. /// </summary> protected bool HasCachedOutput { get { return this._cachedOutput != null; } } /// <summary> /// Indicate if the module should display the syndication icon at its current state. /// </summary> protected bool DisplaySyndicationIcon { get { return this._displaySyndicationIcon; } set { this._displaySyndicationIcon = value; } } /// <summary> /// The PageEngine that serves as the context for the module controls. /// </summary> public PageEngine PageEngine { get { return this._pageEngine; } } /// <summary> /// The accompanying ModuleBase business object. Use this property to access /// module properties, sections and nodes from the code-behind of the module user controls. /// </summary> public ModuleBase Module { get { return this._module; } set { this._module = value; } } /// <summary> /// Default constructor. /// </summary> public BaseModuleControl() { // Show the syndication icon by default. It can be set by subclasses. this._displaySyndicationIcon = (this is ISyndicatable); } protected override void OnInit(EventArgs e) { if (this.Module.Section.CacheDuration > 0 && this.Module.CacheKey != null && !this.Page.User.Identity.IsAuthenticated && !this.Page.IsPostBack) { // Get the cached content. Don't use cached output after a postback. if (HttpContext.Current.Cache[this.Module.CacheKey] != null && !this.IsPostBack) { // Found cached content. this._cachedOutput = HttpContext.Current.Cache[this.Module.CacheKey].ToString(); } } if (this.Page is PageEngine) { this._pageEngine = (PageEngine)this.Page; } base.OnInit(e); } /// <summary> /// Wrap the section content in a visual block. /// </summary> /// <param name="writer"></param> protected override void Render(System.Web.UI.HtmlTextWriter writer) { // Rss feed if (this._displaySyndicationIcon) { writer.Write(String.Format("<div class=\"syndicate\"><a href=\"{0}\"><img src=\"{1}\" alt=\"RSS-2.0\"/></a></div>", UrlHelper.GetRssUrlFromSection(this._module.Section) + this._module.ModulePathInfo, UrlHelper.GetApplicationPath() + "Images/feed-icon.png")); } User cuyahogaUser = this.Page.User.Identity as User; if (cuyahogaUser != null && (cuyahogaUser.CanEdit(this._module.Section) || cuyahogaUser.HasPermission(AccessLevel.Administrator))) { writer.Write("<div class=\"moduletools\">"); // added for 1.6.0 bool isPreview = (Request.QueryString["preview"] == null ? false : (Request.QueryString["preview"] == "on")); // Edit button if (!isPreview) // modified for 1.6.0 { if (this._module.Section.ModuleType.EditPath != null && cuyahogaUser.CanEdit(this._module.Section)) { if (this._module.Section.Node != null) { writer.Write(String.Format("&nbsp;<a href=\"{0}?NodeId={1}&amp;SectionId={2}\">Edit</a>" , UrlHelper.GetApplicationPath() + this._module.Section.ModuleType.EditPath , this._module.Section.Node.Id , this._module.Section.Id)); } else { writer.Write(String.Format("&nbsp;<a href=\"{0}?NodeId={1}&amp;SectionId={2}\">Edit</a>" , UrlHelper.GetApplicationPath() + this._module.Section.ModuleType.EditPath , this.PageEngine.ActiveNode.Id , this._module.Section.Id)); } } if (cuyahogaUser.HasPermission(AccessLevel.Administrator)) { if (this._module.Section.Node != null) { writer.Write( String.Format( "&nbsp;<a href=\"{0}Admin/SectionEdit.aspx?NodeId={1}&amp;SectionId={2}\">Section Properties</a>" , UrlHelper.GetApplicationPath() , this._module.Section.Node.Id , this._module.Section.Id)); writer.Write( String.Format( "&nbsp;<a href=\"{0}Admin/NodeEdit.aspx?NodeId={1}\">Page Properties</a>" , UrlHelper.GetApplicationPath() , this._module.Section.Node.Id)); } else { writer.Write(String.Format("&nbsp;<a href=\"{0}Admin/SectionEdit.aspx?SectionId={1}\">Section Properties</a>" , UrlHelper.GetApplicationPath() , this._module.Section.Id)); } } } writer.Write("</div>"); } writer.Write("<div class=\"section\">"); // Section title if (this._module.Section != null && this._module.Section.ShowTitle) { writer.Write("<h3>" + this._module.DisplayTitle + "</h3>"); } // Write module content and handle caching when neccesary. // Don't cache when the user is logged in or after a postback. if (this._module.Section.CacheDuration > 0 && this.Module.CacheKey != null && !this.Page.User.Identity.IsAuthenticated && !this.Page.IsPostBack) { if (this._cachedOutput == null) { StringWriter tempWriter = new StringWriter(); base.Render(new System.Web.UI.HtmlTextWriter(tempWriter)); this._cachedOutput = tempWriter.ToString(); HttpContext.Current.Cache.Insert(this.Module.CacheKey, this._cachedOutput, null , DateTime.Now.AddSeconds(this._module.Section.CacheDuration), TimeSpan.Zero); } // Output the user control's content. writer.Write(_cachedOutput); } else { base.Render(writer); } writer.Write("</div>"); } /// <summary> /// Empty the output cache for the current module state. /// </summary> protected void InvalidateCache() { if (this.Module.CacheKey != null) { HttpContext.Current.Cache.Remove(this.Module.CacheKey); } } /// <summary> /// Register module-specific stylesheets. /// </summary> /// <param name="key">The unique key for the stylesheet. Note that Cuyahoga already uses 'maincss' as key.</param> /// <param name="absoluteCssPath">The path to the css file from the application root (starting with /).</param> protected void RegisterStylesheet(string key, string absoluteCssPath) { this._pageEngine.RegisterStylesheet(key, absoluteCssPath); } /// <summary> /// Register module-specific javascripts. /// </summary> /// <param name="key">The unique key for the script.</param> /// <param name="absoluteJavaScriptPath">The path to the javascript file from the application root.</param> protected void RegisterJavascript(string key, string absoluteJavaScriptPath) { this._pageEngine.RegisterJavaScript(key, absoluteJavaScriptPath); } } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; using System.IO; using System.Text; using System.Collections; using System.Reflection; namespace NUnit.Framework.Constraints { /// <summary> /// EqualConstraint is able to compare an actual value with the /// expected value provided in its constructor. /// </summary> public class EqualConstraint : Constraint { private static IDictionary constraintHelpers = new Hashtable(); private object expected; private ArrayList failurePoints; /// <summary> /// Flag used to indicate whether a tolerance was actually /// used and should be displayed in the message. /// </summary> private bool displayTolerance = false; private static readonly string StringsDiffer_1 = "String lengths are both {0}. Strings differ at index {1}."; private static readonly string StringsDiffer_2 = "Expected string length {0} but was {1}. Strings differ at index {2}."; private static readonly string StreamsDiffer_1 = "Stream lengths are both {0}. Streams differ at offset {1}."; private static readonly string StreamsDiffer_2 = "Expected Stream length {0} but was {1}.";// Streams differ at offset {2}."; private static readonly string CollectionType_1 = "Expected and actual are both {0}"; private static readonly string CollectionType_2 = "Expected is {0}, actual is {1}"; private static readonly string ValuesDiffer_1 = "Values differ at index {0}"; private static readonly string ValuesDiffer_2 = "Values differ at expected index {0}, actual index {1}"; private static readonly int BUFFER_SIZE = 4096; #region Constructor /// <summary> /// Initializes a new instance of the <see cref="T:EqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public EqualConstraint(object expected) { this.expected = expected; } #endregion #region Public Methods /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public override bool Matches(object actual) { this.actual = actual; this.failurePoints = new ArrayList(); return ObjectsEqual( expected, actual ); } /// <summary> /// Write a failure message. Overridden to provide custom /// failure messages for EqualConstraint. /// </summary> /// <param name="writer">The MessageWriter to write to</param> public override void WriteMessageTo(MessageWriter writer) { DisplayDifferences(writer, expected, actual, 0); } /// <summary> /// Write description of this constraint /// </summary> /// <param name="writer">The MessageWriter to write to</param> public override void WriteDescriptionTo(MessageWriter writer) { writer.WriteExpectedValue( expected ); if ( tolerance != null ) { writer.WriteConnector("+/-"); writer.WriteExpectedValue(tolerance); } // if ( this.caseInsensitive ) // writer.WriteModifier("ignoring case"); } private void DisplayDifferences(MessageWriter writer, object expected, object actual, int depth) { if (expected is string && actual is string) DisplayStringDifferences(writer, (string)expected, (string)actual); else if (expected is ICollection && actual is ICollection) DisplayCollectionDifferences(writer, (ICollection)expected, (ICollection)actual, depth); else if (expected is Stream && actual is Stream) DisplayStreamDifferences(writer, (Stream)expected, (Stream)actual, depth); else if ( displayTolerance ) writer.DisplayDifferences( expected, actual, tolerance ); else writer.DisplayDifferences(expected, actual); } #endregion #region ObjectsEqual private bool ObjectsEqual(object expected, object actual) { if (expected == null && actual == null) return true; if (expected == null || actual == null) return false; Type expectedType = expected.GetType(); Type actualType = actual.GetType(); if (expectedType.IsArray && actualType.IsArray && !compareAsCollection) return ArraysEqual((Array)expected, (Array)actual); if (expected is ICollection && actual is ICollection) return CollectionsEqual((ICollection)expected, (ICollection)actual); if (expected is Stream && actual is Stream) return StreamsEqual((Stream)expected, (Stream)actual); if (expected is double && actual is double) { if (double.IsNaN((double)expected) && double.IsNaN((double)actual)) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (double.IsInfinity((double)expected) || double.IsNaN((double)expected) || double.IsNaN((double)actual)) return expected.Equals(actual); // If a tolerance was specified, use that if ( tolerance != null && tolerance is double) { displayTolerance = true; return Math.Abs((double)expected - (double)actual) <= (double)tolerance; } } if (expected is float && actual is float) { if (float.IsNaN((float)expected) && float.IsNaN((float)actual)) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (float.IsInfinity((float)expected) || float.IsNaN((float)expected) || float.IsNaN((float)actual)) return expected.Equals(actual); // If a tolerance was specified, use that if ( tolerance != null && tolerance is float) { displayTolerance = true; return Math.Abs((float)expected - (float)actual) <= (float)tolerance; } } if ( expectedType != actualType && IsNumericType(expected) && IsNumericType(actual)) { // // Convert to strings and compare result to avoid // issues with different types that have the same // expected // string sExpected = expected is decimal ? ((decimal)expected).ToString("G29") : expected.ToString(); string sActual = actual is decimal ? ((decimal)actual).ToString("G29") : actual.ToString(); return sExpected.Equals(sActual); } if (expected is string && actual is string) { return string.Compare((string)expected, (string)actual, caseInsensitive) == 0; } return expected.Equals(actual); } /// <summary> /// Helper method to compare two arrays /// </summary> protected virtual bool ArraysEqual(Array expected, Array actual) { int rank = expected.Rank; if (rank != actual.Rank) return false; for (int r = 1; r < rank; r++) if (expected.GetLength(r) != actual.GetLength(r)) return false; return CollectionsEqual((ICollection)expected, (ICollection)actual); } private bool CollectionsEqual(ICollection expected, ICollection actual) { IEnumerator expectedEnum = expected.GetEnumerator(); IEnumerator actualEnum = actual.GetEnumerator(); int count; for (count = 0; expectedEnum.MoveNext() && actualEnum.MoveNext(); count++) { if (!ObjectsEqual(expectedEnum.Current, actualEnum.Current)) break; } if (count == expected.Count && count == actual.Count) return true; failurePoints.Insert(0, count); return false; } private bool StreamsEqual( Stream expected, Stream actual ) { if (expected.Length != actual.Length) return false; byte[] bufferExpected = new byte[BUFFER_SIZE]; byte[] bufferActual = new byte[BUFFER_SIZE]; BinaryReader binaryReaderExpected = new BinaryReader(expected); BinaryReader binaryReaderActual = new BinaryReader(actual); binaryReaderExpected.BaseStream.Seek(0, SeekOrigin.Begin); binaryReaderActual.BaseStream.Seek(0, SeekOrigin.Begin); for(long readByte = 0; readByte < expected.Length; readByte += BUFFER_SIZE ) { binaryReaderExpected.Read(bufferExpected, 0, BUFFER_SIZE); binaryReaderActual.Read(bufferActual, 0, BUFFER_SIZE); for (int count=0; count < BUFFER_SIZE; ++count) { if (bufferExpected[count] != bufferActual[count]) { failurePoints.Insert( 0, readByte + count ); //FailureMessage.WriteLine("\tIndex : {0}", readByte + count); return false; } } } return true; } /// <summary> /// Checks the type of the object, returning true if /// the object is a numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a numeric type</returns> private bool IsNumericType(Object obj) { if (null != obj) { if (obj is byte) return true; if (obj is sbyte) return true; if (obj is decimal) return true; if (obj is double) return true; if (obj is float) return true; if (obj is int) return true; if (obj is uint) return true; if (obj is long) return true; if (obj is short) return true; if (obj is ushort) return true; if (obj is System.Byte) return true; if (obj is System.SByte) return true; if (obj is System.Decimal) return true; if (obj is System.Double) return true; if (obj is System.Single) return true; if (obj is System.Int32) return true; if (obj is System.UInt32) return true; if (obj is System.Int64) return true; if (obj is System.UInt64) return true; if (obj is System.Int16) return true; if (obj is System.UInt16) return true; } return false; } #endregion #region DisplayStringDifferences private void DisplayStringDifferences(MessageWriter writer, string expected, string actual) { int mismatch = MsgUtils.FindMismatchPosition(expected, actual, 0, this.caseInsensitive); if (expected.Length == actual.Length) writer.WriteMessageLine(StringsDiffer_1, expected.Length, mismatch); else writer.WriteMessageLine(StringsDiffer_2, expected.Length, actual.Length, mismatch); writer.DisplayStringDifferences(expected, actual, mismatch, caseInsensitive); } #endregion #region DisplayStreamDifferences private void DisplayStreamDifferences(MessageWriter writer, Stream expected, Stream actual, int depth) { if ( expected.Length == actual.Length ) { long offset = (long)failurePoints[depth]; writer.WriteMessageLine(StreamsDiffer_1, expected.Length, offset); } else writer.WriteMessageLine(StreamsDiffer_2, expected.Length, actual.Length); } #endregion #region DisplayCollectionDifferences /// <summary> /// Display the failure information for two collections that did not match. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected collection.</param> /// <param name="actual">The actual collection</param> /// <param name="depth">The depth of this failure in a set of nested collections</param> private void DisplayCollectionDifferences(MessageWriter writer, ICollection expected, ICollection actual, int depth) { int failurePoint = failurePoints.Count > depth ? (int)failurePoints[depth] : -1; DisplayCollectionTypesAndSizes(writer, expected, actual, depth); if (failurePoint >= 0) { DisplayFailurePoint(writer, expected, actual, failurePoint, depth); if (failurePoint < expected.Count && failurePoint < actual.Count) DisplayDifferences( writer, GetValueFromCollection(expected, failurePoint), GetValueFromCollection(actual, failurePoint), ++depth); else if (expected.Count < actual.Count) { writer.Write( " Extra: " ); writer.WriteCollectionElements( actual, failurePoint, 3 ); } else { writer.Write( " Missing: " ); writer.WriteCollectionElements( expected, failurePoint, 3 ); } } } /// <summary> /// Displays a single line showing the types and sizes of the expected /// and actual collections or arrays. If both are identical, the value is /// only shown once. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected collection or array</param> /// <param name="actual">The actual collection or array</param> /// <param name="indent">The indentation level for the message line</param> private void DisplayCollectionTypesAndSizes(MessageWriter writer, ICollection expected, ICollection actual, int indent) { string sExpected = MsgUtils.GetTypeRepresentation(expected); if (!(expected is Array)) sExpected += string.Format(" with {0} elements", expected.Count); string sActual = MsgUtils.GetTypeRepresentation(actual); if (!(actual is Array)) sActual += string.Format(" with {0} elements", expected.Count); if (sExpected == sActual) writer.WriteMessageLine(indent, CollectionType_1, sExpected); else writer.WriteMessageLine(indent, CollectionType_2, sExpected, sActual); } /// <summary> /// Displays a single line showing the point in the expected and actual /// arrays at which the comparison failed. If the arrays have different /// structures or dimensions, both values are shown. /// </summary> /// <param name="writer">The MessageWriter on which to display</param> /// <param name="expected">The expected array</param> /// <param name="actual">The actual array</param> /// <param name="failurePoint">Index of the failure point in the underlying collections</param> /// <param name="indent">The indentation level for the message line</param> private void DisplayFailurePoint(MessageWriter writer, ICollection expected, ICollection actual, int failurePoint, int indent) { Array expectedArray = expected as Array; Array actualArray = actual as Array; int expectedRank = expectedArray != null ? expectedArray.Rank : 1; int actualRank = actualArray != null ? actualArray.Rank : 1; bool useOneIndex = expectedRank == actualRank; if (expectedArray != null && actualArray != null) for (int r = 1; r < expectedRank && useOneIndex; r++) if (expectedArray.GetLength(r) != actualArray.GetLength(r)) useOneIndex = false; int[] expectedIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(expected, failurePoint); if (useOneIndex) { writer.WriteMessageLine(indent, ValuesDiffer_1, MsgUtils.GetArrayIndicesAsString(expectedIndices)); } else { int[] actualIndices = MsgUtils.GetArrayIndicesFromCollectionIndex(actual, failurePoint); writer.WriteMessageLine(indent, ValuesDiffer_2, MsgUtils.GetArrayIndicesAsString(expectedIndices), MsgUtils.GetArrayIndicesAsString(actualIndices)); } } private static object GetValueFromCollection(ICollection collection, int index) { Array array = collection as Array; if (array != null && array.Rank > 1) return array.GetValue(MsgUtils.GetArrayIndicesFromCollectionIndex(array, index)); if (collection is IList) return ((IList)collection)[index]; foreach (object obj in collection) if (--index < 0) return obj; return null; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FluentAssertions; using NUnit.Framework; using TestConsole.OutputFormatting.Internal; using TestConsoleLib.Testing; namespace TestConsole.Tests.OutputFormatting.Internal { [TestFixture] public class TestColumnWrapper { [Test] public void StringIsWrappedAtWordBreaks() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four five six seven eight nine ten eleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void NoTrailingSpacesAreIncludedOnLineWrap() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four\t\t\t\t\t\t\t\t five\tsix seven eight nine ten eleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void WordsLongerThanOneLineAreBroken() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four fivesixseveneightnineteneleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void VeryLongInitialWordisBroken() { var c = new ColumnFormat("h", typeof (string)); const string value = "Onetwothreefourfivesixseveneightnineten eleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void LineBreaksArePreserved() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void WordBreaksAreCounted() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four five six seven eight nine ten eleven."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(2)); } [Test] public void TrailingSpacesDoNotCauseAdditionalLineBreaks() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four\t\t\t\t\t\t\t\t five\tsix seven eight nine ten eleven."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine("----+----|----+----|"); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(3)); } [Test] public void BreaksInVeryLongWordsAreCounted() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three four fivesixseveneightnineteneleven."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(2)); } [Test] public void BreaksInVeryLongInitialWordAreCounted() { var c = new ColumnFormat("h", typeof (string)); const string value = "Onetwothreefourfivesixseveneightnineten eleven."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(2)); } [Test] public void DataLineBreaksAreNotCounted() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(1)); } [Test] public void SingleLineDataAddsNoLineBreaks() { var c = new ColumnFormat("h", typeof (string)); const string value = "One two three."; var addedBreaks = ColumnWrapper.CountWordwrapLineBreaks(value, c, 20); Console.WriteLine(string.Join("\r\n", ColumnWrapper.WrapValue(value, c, 20))); Assert.That(addedBreaks, Is.EqualTo(0)); } [Test] public void LinesAreExpandedToCorrectLength() { var c = new ColumnFormat("h", typeof (string)); c.SetActualWidth(20); var value = "Line" + Environment.NewLine + "Data" + Environment.NewLine + "More"; var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--"); var result = FormatResult(value, wrapped, 20, 3); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void RightAlignedLinesAreExpandedToCorrectLength() { var c = new ColumnFormat("h", typeof (string), ColumnAlign.Right); c.SetActualWidth(20); var value = "Line" + Environment.NewLine + "Data" + Environment.NewLine + "More"; var wrapped = ColumnWrapper.WrapValue(value, c, 20).Select(l => "-->" + l + "<--"); var result = FormatResult(value, wrapped, 20, 3); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void FirstLineIndentShortensFirstLine() { var c = new ColumnFormat("h", typeof(string)); const string value = "One two three four five six seven eight nine ten eleven."; var wrapped = ColumnWrapper.WrapValue(value, c, 20, firstLineHangingIndent: 10); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void LeadingSpacesArePreserved() { var c = new ColumnFormat("h", typeof(string)); const string value = " One two three."; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void TrailingSpacesArePreserved() { var c = new ColumnFormat("h", typeof(string)); const string value = "One two three. "; var wrapped = ColumnWrapper.WrapValue(value, c, 20); var result = FormatResult(value, wrapped, 20); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void WrapAndMeasureWordsCanWorkWithSplitData() { //Arrange var c = new ColumnFormat("h", typeof(string)); const string value = "One two three four five six seven eight nine ten eleven."; var words = WordSplitter.SplitToList(value, 4); //Act int wrappedLines; var wrapped = ColumnWrapper.WrapAndMeasureWords(words, c, 20, 0, out wrappedLines); //Assert var result = FormatResult(value, wrapped, 20) + Environment.NewLine + string.Format("Added line breaks = {0}", wrappedLines); Console.WriteLine(result); Approvals.Verify(result); } [Test] public void LongestLineIsComputed() { //Arrange var c = new ColumnFormat("h", typeof (string)); const string value = "One two three\r\nfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven."; //Act var longest = ColumnWrapper.GetLongestLineLength(value, c); //Assert longest.Should().Be(25); } [Test] public void LongestLineCanBeEven() { //Arrange var c = new ColumnFormat("h", typeof (string)); const string value = "One two three\r\nXfour five six seven eight\r\n\r\n\r\nnine\r\nten\r\neleven."; //Act var longest = ColumnWrapper.GetLongestLineLength(value, c); //Assert longest.Should().Be(26); } [Test] public void LongestLineWhenTextIsEmptyIsOne() { //Arrange var c = new ColumnFormat("h", typeof (string)); //Act var longest = ColumnWrapper.GetLongestLineLength(string.Empty, c); //Assert longest.Should().Be(1); } private string FormatResult(string value, IEnumerable<string> wrapped, int guideWidth, int indent = 0) { var indentString = new string(' ', indent); var sb = new StringBuilder(); sb.AppendLine(TestContext.CurrentContext.Test.Name); sb.AppendLine(); sb.AppendLine("Original:"); sb.AppendLine(value); sb.AppendLine(); sb.AppendLine("Wrapped:"); var guide = Enumerable.Range(0, guideWidth) .Select(i => ((i + 1)%10).ToString()) .Aggregate((t, i) => t + i); var divide = Enumerable.Range(0, guideWidth) .Select(i => ((i + 1) % 10) == 0 ? "+" : "-") .Aggregate((t, i) => t + i); sb.AppendLine(indentString + guide); sb.AppendLine(indentString + divide); foreach (var line in wrapped) { sb.AppendLine(line); } return sb.ToString(); } } }
/* * 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.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula; /** * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; * This Is the base class for all excel function evaluator * classes that take variable number of operands, and * where the order of operands does not matter */ public abstract class MultiOperandNumericFunction : Function { static double[] EMPTY_DOUBLE_ARRAY = { }; private bool _isReferenceBoolCounted; private bool _isBlankCounted; protected MultiOperandNumericFunction(bool isReferenceBoolCounted, bool isBlankCounted) { _isReferenceBoolCounted = isReferenceBoolCounted; _isBlankCounted = isBlankCounted; } protected internal abstract double Evaluate(double[] values); public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { double d; try { double[] values = GetNumberArray(args); d = Evaluate(values); } catch (EvaluationException e) { return e.GetErrorEval(); } if (Double.IsNaN(d) || Double.IsInfinity(d)) return ErrorEval.NUM_ERROR; return new NumberEval(d); } private class DoubleList { private double[] _array; private int _Count; public DoubleList() { _array = new double[8]; _Count = 0; } public double[] ToArray() { if (_Count < 1) { return EMPTY_DOUBLE_ARRAY; } double[] result = new double[_Count]; Array.Copy(_array, 0, result, 0, _Count); return result; } public void Add(double[] values) { int AddLen = values.Length; EnsureCapacity(_Count + AddLen); Array.Copy(values, 0, _array, _Count, AddLen); _Count += AddLen; } private void EnsureCapacity(int reqSize) { if (reqSize > _array.Length) { int newSize = reqSize * 3 / 2; // grow with 50% extra double[] newArr = new double[newSize]; Array.Copy(_array, 0, newArr, 0, _Count); _array = newArr; } } public void Add(double value) { EnsureCapacity(_Count + 1); _array[_Count] = value; _Count++; } } private const int DEFAULT_MAX_NUM_OPERANDS = 30; /** * Maximum number of operands accepted by this function. * Subclasses may override to Change default value. */ protected virtual int MaxNumOperands { get { return DEFAULT_MAX_NUM_OPERANDS; } } /** * Whether to count nested subtotals. */ public virtual bool IsSubtotalCounted { get { return true; } } /** * Collects values from a single argument */ private void CollectValues(ValueEval operand, DoubleList temp) { if (operand is ThreeDEval) { ThreeDEval ae = (ThreeDEval)operand; for (int sIx = ae.FirstSheetIndex; sIx <= ae.LastSheetIndex; sIx++) { int width = ae.Width; int height = ae.Height; for (int rrIx = 0; rrIx < height; rrIx++) { for (int rcIx = 0; rcIx < width; rcIx++) { ValueEval ve = ae.GetValue(sIx, rrIx, rcIx); if (!IsSubtotalCounted && ae.IsSubTotal(rrIx, rcIx)) continue; CollectValue(ve, true, temp); } } } return; } if (operand is TwoDEval) { TwoDEval ae = (TwoDEval)operand; int width = ae.Width; int height = ae.Height; for (int rrIx = 0; rrIx < height; rrIx++) { for (int rcIx = 0; rcIx < width; rcIx++) { ValueEval ve = ae.GetValue(rrIx, rcIx); if (!IsSubtotalCounted && ae.IsSubTotal(rrIx, rcIx)) continue; CollectValue(ve, true, temp); } } return; } if (operand is RefEval) { RefEval re = (RefEval)operand; for (int sIx = re.FirstSheetIndex; sIx <= re.LastSheetIndex; sIx++) { CollectValue(re.GetInnerValueEval(sIx), true, temp); } return; } CollectValue((ValueEval)operand, false, temp); } private void CollectValue(ValueEval ve, bool isViaReference, DoubleList temp) { if (ve == null) { throw new ArgumentException("ve must not be null"); } if (ve is BoolEval) { if (!isViaReference || _isReferenceBoolCounted) { BoolEval boolEval = (BoolEval)ve; temp.Add(boolEval.NumberValue); } return; } if (ve is NumberEval) { NumberEval ne = (NumberEval)ve; temp.Add(ne.NumberValue); return; } if (ve is StringEval) { if (isViaReference) { // ignore all ref strings return; } String s = ((StringEval)ve).StringValue; Double d = OperandResolver.ParseDouble(s); if (double.IsNaN(d)) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } temp.Add(d); return; } if (ve is ErrorEval) { throw new EvaluationException((ErrorEval)ve); } if (ve == BlankEval.instance) { if (_isBlankCounted) { temp.Add(0.0); } return; } throw new InvalidOperationException("Invalid ValueEval type passed for conversion: (" + ve.GetType() + ")"); } /** * Returns a double array that contains values for the numeric cells * from among the list of operands. Blanks and Blank equivalent cells * are ignored. Error operands or cells containing operands of type * that are considered invalid and would result in #VALUE! error in * excel cause this function to return <c>null</c>. * * @return never <c>null</c> */ protected double[] GetNumberArray(ValueEval[] operands) { if (operands.Length > MaxNumOperands) { throw EvaluationException.InvalidValue(); } DoubleList retval = new DoubleList(); for (int i = 0, iSize = operands.Length; i < iSize; i++) { CollectValues(operands[i], retval); } return retval.ToArray(); } /** * Ensures that a two dimensional array has all sub-arrays present and the same Length * @return <c>false</c> if any sub-array Is missing, or Is of different Length */ protected static bool AreSubArraysConsistent(double[][] values) { if (values == null || values.Length < 1) { // TODO this doesn't seem right. Fix or Add comment. return true; } if (values[0] == null) { return false; } int outerMax = values.Length; int innerMax = values[0].Length; for (int i = 1; i < outerMax; i++) { // note - 'i=1' start at second sub-array double[] subArr = values[i]; if (subArr == null) { return false; } if (innerMax != subArr.Length) { return false; } } return true; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ArcGIS.Core.CIM; using ArcGIS.Desktop.Editing.Attributes; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; using Mil2525.Fields; namespace DictionarySymbolPreview.UI { /// <summary> /// Interaction logic for DictionarySymbolView.xaml /// </summary> public partial class DictionarySymbolView : UserControl, INotifyPropertyChanged { private SymbolSet _currentSet = null; private string _codeSource = ""; private BitmapImage _img = null; private BasicFeatureLayer _selectedLayer = null; private long _selectedOid = -1; private bool _ignoreEvents = false; public DictionarySymbolView() { InitializeComponent(); (this.Content as FrameworkElement).DataContext = this; this.PropertyChanged += DictionarySymbolView_PropertyChanged; CurrentSymbolSet = SymbolSet.SymbolSets["Air"]; this.SymbolSetPropertyGrid.PropertyValueChanged += SymbolSetPropertyGrid_PropertyValueChanged; this.SymbolSetPropertyGrid.SelectedObjectChanged += SymbolSetPropertyGrid_SelectedObjectChanged; this.SymbolSetPropertyGrid.ShowTitle = true; } public IReadOnlyList<SymbolSet> SymbolSets => SymbolSet.SymbolSets.Select(k => k.Value).ToList(); public SymbolSet CurrentSymbolSet { get { return _currentSet; } set { _currentSet = value; OnPropertyChanged(); } } public string CodeSource { get { return _codeSource; } set { _codeSource = value; OnPropertyChanged(); } } public ImageSource ImageSource { get { return _img; } set { _img = (BitmapImage)value; OnPropertyChanged(); } } public Tuple<BasicFeatureLayer, long> SelectedFeature { get { return new Tuple<BasicFeatureLayer, long>(_selectedLayer, _selectedOid); } set { _selectedLayer = value.Item1; _selectedOid = value.Item2; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; protected virtual void OnPropertyChanged([CallerMemberName] string propName = "") { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } private async void SymbolSetPropertyGrid_SelectedObjectChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { this.CodeSource = ""; if (SymbolSetPropertyGrid.SelectedObject is Fields_Base) { var fldsBase = (Fields_Base)SymbolSetPropertyGrid.SelectedObject; this.ImageSource = await GenerateBitmapImageAsync(fldsBase.ChangedAttributeValues); } else { this.ImageSource = null; } } private void SymbolSetPropertyGrid_PropertyValueChanged(object sender, Xceed.Wpf.Toolkit.PropertyGrid.PropertyValueChangedEventArgs e) { if (this.SymbolSetPropertyGrid.SelectedObject is Fields_Base && !_ignoreEvents) { UpdateSymbolAndCode(); } } private string ConvertAttributesToCode(Dictionary<string, object> formattedAttributes) { StringBuilder sb = new StringBuilder(); sb.AppendLine(""); string indent = "\t"; sb.AppendLine(string.Format( "{0}Dictionary <string, object> values = new Dictionary<string, object>();", indent)); foreach (var kvp in formattedAttributes) { sb.AppendLine(string.Format("{0}values.Add({1}, {2});", indent, kvp.Key, kvp.Value)); } sb.AppendLine(string.Format("\r\n{0}CIMSymbol symbol = await QueuedTask.Run(() => ", indent)); sb.AppendLine(string.Format("{0}ArcGIS.Desktop.Mapping.SymbolFactory.GetDictionarySymbol(\"mil2525d\",values));", indent)); return sb.ToString(); } private Task<ImageSource> GenerateBitmapImageAsync(Dictionary<string, object> attributes) { return QueuedTask.Run(() => { CIMSymbol symbol = ArcGIS.Desktop.Mapping.SymbolFactory.Instance.GetDictionarySymbol("mil2525d", attributes); //At 1.3, 64 is the max pixel size we can scale to. This will be enhanced at 1.4 to support //scaling (eg up to 256, the preferred review size for military symbols) var si = new SymbolStyleItem() { Symbol = symbol, PatchHeight = 64, PatchWidth = 64 }; return si.PreviewImage; }); } private async void DictionarySymbolView_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "CurrentSymbolSet" && !_ignoreEvents) { UpdatePropertyGridSelectedObject(); } else if (e.PropertyName == "SelectedFeature" && !_ignoreEvents) { _ignoreEvents = true; if (this._selectedLayer == null || this._selectedOid == -1) return; Inspector inspector = new Inspector(); await inspector.LoadAsync(this._selectedLayer, this._selectedOid); var attributes = inspector.ToDictionary(a => a.FieldName.ToLower(), a => a.CurrentValue.GetType() != typeof(System.DBNull) ? a.CurrentValue : null); //change the symbology combobox var symbolSetID = Convert.ToInt32(attributes["symbolset"]); var symbolSets = SymbolSet.SymbolSets.Where( kvp => kvp.Value.SymbolSetID == symbolSetID).Select(kvp => kvp.Value).ToList(); if (symbolSets.Count() > 1) { //There is more than one choice if (this._selectedLayer.ShapeType == esriGeometryType.esriGeometryPoint) { this.CurrentSymbolSet = symbolSets.First(s => s.SchemaNameAlias.Contains("Points")); } else if (this._selectedLayer.ShapeType == esriGeometryType.esriGeometryPolyline) { this.CurrentSymbolSet = symbolSets.First(s => s.SchemaNameAlias.Contains("Lines")); } else { //Must be poly this.CurrentSymbolSet = symbolSets.First(s => s.SchemaNameAlias.Contains("Areas")); } } else { this.CurrentSymbolSet = symbolSets[0]; } UpdatePropertyGridSelectedObject(); if (SymbolSetPropertyGrid.SelectedObject != null) { ((Fields_Base)SymbolSetPropertyGrid.SelectedObject).ChangeAttributeValues(attributes); } UpdateSymbolAndCode(); _ignoreEvents = false; } } private void UpdatePropertyGridSelectedObject() { if (CurrentSymbolSet != null) { var fieldsClass = Fields_Base.FieldClasses[CurrentSymbolSet.SchemaName]; SymbolSetPropertyGrid.SelectedObject = fieldsClass; SymbolSetPropertyGrid.SelectedObjectTypeName = string.Format("{0}:", fieldsClass.SchemaName); SymbolSetPropertyGrid.SelectedObjectName = fieldsClass.SymbolSetName; } } private async void UpdateSymbolAndCode() { var fldsBase = (Fields_Base)this.SymbolSetPropertyGrid.SelectedObject; this.CodeSource = ConvertAttributesToCode(fldsBase.ChangedAttributeFormattedValues); this.ImageSource = await GenerateBitmapImageAsync(fldsBase.ChangedAttributeValues); } } }
using System; using System.Drawing; using System.Drawing.Printing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace HelperFramework.WinForms { /// <summary> /// DataGridView RichTextBox Column /// </summary> public class DataGridViewRichTextBoxColumn : DataGridViewColumn { /// <summary> /// Initializes a new instance of the <see cref="DataGridViewRichTextBoxColumn"/> class. /// </summary> public DataGridViewRichTextBoxColumn() : base(new DataGridViewRichTextBoxCell()) { } /// <summary> /// Gets or sets CellTemplate. /// </summary> /// <exception cref="InvalidCastException"> /// CellTemplate must be a DataGridViewRichTextBoxCell /// </exception> public override DataGridViewCell CellTemplate { get { return base.CellTemplate; } set { if (!(value is DataGridViewRichTextBoxCell)) { throw new InvalidCastException("CellTemplate must be a DataGridViewRichTextBoxCell"); } base.CellTemplate = value; } } } /// <summary> /// DataGridView RichTextBox Cell /// </summary> public class DataGridViewRichTextBoxCell : DataGridViewTextBoxCell { /// <summary> /// Editing Control /// </summary> private static readonly RichTextBox EditingControl = new RichTextBox(); /// <summary> /// Edit Type /// </summary> public override Type EditType { get { return typeof(DataGridViewRichTextBoxEditingControl); } } /// <summary> /// Value Type /// </summary> public override Type ValueType { get { return typeof(string); } set { base.ValueType = value; } } /// <summary> /// Formatted Value Type /// </summary> public override Type FormattedValueType { get { return typeof(string); } } /// <summary> /// Get Inherited Style /// </summary> /// <param name="inheritedCellStyle">inherited Cell Style</param> /// <param name="rowIndex">row Index</param> /// <param name="includeColors">include Colors</param> /// <returns>inherited cell style</returns> public override DataGridViewCellStyle GetInheritedStyle( DataGridViewCellStyle inheritedCellStyle, Int32 rowIndex, Boolean includeColors) { DataGridViewCellStyle inheritedStyle = base.GetInheritedStyle(inheritedCellStyle, rowIndex, includeColors); inheritedStyle.Padding = new Padding(5); return inheritedStyle; } /// <summary> /// Initialize Editing Control /// </summary> /// <param name="rowIndex"> /// The row index. /// </param> /// <param name="initialFormattedValue"> /// The initial formatted value. /// </param> /// <param name="dataGridViewCellStyle"> /// The data grid view cell style. /// </param> public override void InitializeEditingControl( Int32 rowIndex, Object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle) { base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle); RichTextBox ctl = DataGridView.EditingControl as RichTextBox; if (ctl != null) { SetRichTextBoxText(ctl, Convert.ToString(initialFormattedValue)); } } /// <summary> /// Paint method /// </summary> /// <param name="graphics"> /// The graphics. /// </param> /// <param name="clipBounds"> /// The clip bounds. /// </param> /// <param name="cellBounds"> /// The cell bounds. /// </param> /// <param name="rowIndex"> /// The row index. /// </param> /// <param name="cellState"> /// The cell state. /// </param> /// <param name="value"> /// The value. /// </param> /// <param name="formattedValue"> /// The formatted value. /// </param> /// <param name="errorText"> /// The error text. /// </param> /// <param name="cellStyle"> /// The cell style. /// </param> /// <param name="advancedBorderStyle"> /// The advanced border style. /// </param> /// <param name="paintParts"> /// The paint parts. /// </param> protected override void Paint( Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, Int32 rowIndex, DataGridViewElementStates cellState, Object value, Object formattedValue, String errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint( graphics, clipBounds, cellBounds, rowIndex, cellState, null, null, errorText, cellStyle, advancedBorderStyle, paintParts); Image img = GetRtfImage(rowIndex, formattedValue ?? value, this.Selected, cellStyle); if (img != null) { graphics.DrawImage(img, cellBounds.Left, cellBounds.Top); } } /// <summary> /// Set RichTextBox Text /// </summary> /// <param name="ctl"> /// The ctl. /// </param> /// <param name="text"> /// The text. /// </param> private void SetRichTextBoxText(RichTextBox ctl, String text) { try { ctl.Rtf = text; } catch (ArgumentException) { ctl.Text = text; } ToolTipText = ctl.Text; } /// <summary> /// Get Rtf Image /// </summary> /// <param name="rowIndex"> /// The row index. /// </param> /// <param name="value"> /// The value. /// </param> /// <param name="selected"> /// The selected. /// </param> /// <param name="cellStyle"> /// The cell style. /// </param> /// <returns> /// Image of the Rtf /// </returns> private Image GetRtfImage(Int32 rowIndex, Object value, Boolean selected, DataGridViewCellStyle cellStyle) { Size cellSize = GetSize(rowIndex); if (cellSize.Width < 1 || cellSize.Height < 1) { return null; } RichTextBox ctl = EditingControl; ctl.Size = GetSize(rowIndex); ctl.Padding = cellStyle.Padding; ctl.Multiline = false; SetRichTextBoxText(ctl, Convert.ToString(value)); // Print the content of RichTextBox to an image. Size imgSize = new Size(cellSize.Width - 1, cellSize.Height - 1); Image rtfImg; if (selected) { // Selected cell state ctl.BackColor = cellStyle.SelectionBackColor; ctl.ForeColor = cellStyle.SelectionForeColor; // Print image rtfImg = RichTextBoxPrinter.Print(ctl, imgSize.Width, imgSize.Height, ctl.Padding); // Restore RichTextBox ctl.BackColor = cellStyle.BackColor; ctl.ForeColor = cellStyle.ForeColor; } else { rtfImg = RichTextBoxPrinter.Print(ctl, imgSize.Width, imgSize.Height, ctl.Padding); } return rtfImg; } } /// <summary> /// DataGridView RichTextBox Editing Control /// </summary> public class DataGridViewRichTextBoxEditingControl : RichTextBox, IDataGridViewEditingControl { /// <summary> /// Value Changed /// </summary> private Boolean _valueChanged; /// <summary> /// Initializes a new instance of the <see cref="DataGridViewRichTextBoxEditingControl"/> class. /// </summary> public DataGridViewRichTextBoxEditingControl() { BorderStyle = BorderStyle.None; } /// <summary> /// Gets a value indicating whether RepositionEditingControlOnValueChange. /// </summary> public Boolean RepositionEditingControlOnValueChange { get { return false; } } /// <summary> /// Gets or sets EditingControlFormattedValue. /// </summary> public Object EditingControlFormattedValue { get { return Rtf; } set { if (value is string) { Text = value as string; } } } /// <summary> /// Gets or sets EditingControlRowIndex. /// </summary> public Int32 EditingControlRowIndex { get; set; } /// <summary> /// Gets or sets a value indicating whether EditingControlValueChanged. /// </summary> Boolean IDataGridViewEditingControl.EditingControlValueChanged { get { return _valueChanged; } set { _valueChanged = value; } } /// <summary> /// Gets the cursor used when the mouse pointer is over the <see cref="P:System.Windows.Forms.DataGridView.EditingPanel"/> but not over the editing control. /// </summary> /// <returns> /// A <see cref="T:System.Windows.Forms.Cursor"/> that represents the mouse pointer used for the editing panel. /// </returns> Cursor IDataGridViewEditingControl.EditingPanelCursor { get { return Cursor; } } /// <summary> /// Gets or sets the <see cref="T:System.Windows.Forms.DataGridView"/> that contains the cell. /// </summary> /// <returns> /// The <see cref="T:System.Windows.Forms.DataGridView"/> that contains the <see cref="T:System.Windows.Forms.DataGridViewCell"/> that is being edited; null if there is no associated <see cref="T:System.Windows.Forms.DataGridView"/>. /// </returns> public DataGridView EditingControlDataGridView { get; set; } /// <summary> /// Changes the control's user interface (UI) to be consistent with the specified cell style. /// </summary> /// <param name="dataGridViewCellStyle">The <see cref="T:System.Windows.Forms.DataGridViewCellStyle"/> to use as the model for the UI.</param> void IDataGridViewEditingControl.ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle) { Font = dataGridViewCellStyle.Font; } /// <summary> /// Determines whether the specified key is a regular input key that the editing control should process or a special key that the <see cref="T:System.Windows.Forms.DataGridView"/> should process. /// </summary> /// <returns> /// true if the specified key is a regular input key that should be handled by the editing control; otherwise, false. /// </returns> /// <param name="keyData">A <see cref="T:System.Windows.Forms.Keys"/> that represents the key that was pressed.</param><param name="dataGridViewWantsInputKey">true when the <see cref="T:System.Windows.Forms.DataGridView"/> wants to process the <see cref="T:System.Windows.Forms.Keys"/> in <paramref name="keyData"/>; otherwise, false.</param> Boolean IDataGridViewEditingControl.EditingControlWantsInputKey(Keys keyData, Boolean dataGridViewWantsInputKey) { switch (keyData & Keys.KeyCode) { case Keys.Return: if (((keyData & (Keys.Alt | Keys.Control | Keys.Shift)) == Keys.Shift) && Multiline) { return true; } break; case Keys.Left: case Keys.Right: case Keys.Up: case Keys.Down: return true; } return !dataGridViewWantsInputKey; } /// <summary> /// Get Editing Control Formatted Value /// </summary> /// <param name="context"> /// The context. /// </param> /// <returns> /// Editing Control Formatted Value /// </returns> Object IDataGridViewEditingControl.GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) { return Rtf; } /// <summary> /// Prepares the currently selected cell for editing. /// </summary> /// <param name="selectAll">true to select all of the cell's content; otherwise, false.</param> void IDataGridViewEditingControl.PrepareEditingControlForEdit(Boolean selectAll) { } /// <summary> /// On Text Changed /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data. </param> protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); _valueChanged = true; EditingControlDataGridView.NotifyCurrentCellDirty(true); } /// <summary> /// Determines whether the specified key is an input key or a special key that requires preprocessing. /// </summary> /// <param name="keyData">One of the Keys value.</param> /// <returns> /// true if the specified key is an input key; otherwise, false. /// </returns> protected override Boolean IsInputKey(Keys keyData) { Keys keys = keyData & Keys.KeyCode; return keys == Keys.Return ? this.Multiline : base.IsInputKey(keyData); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.KeyEventArgs"/> that contains the event data. </param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Control) { switch (e.KeyCode) { // Control + B = Bold case Keys.B: SelectionFont = SelectionFont.Bold ? new Font(Font.FontFamily, Font.Size, ~FontStyle.Bold & Font.Style) : new Font(Font.FontFamily, Font.Size, FontStyle.Bold | Font.Style); break; // Control + U = Underline case Keys.U: SelectionFont = SelectionFont.Underline ? new Font(Font.FontFamily, Font.Size, ~FontStyle.Underline & Font.Style) : new Font(Font.FontFamily, Font.Size, FontStyle.Underline | Font.Style); break; // Control + I = Italic // Conflicts with the default shortcut // case Keys.I: // if (SelectionFont.Italic) // { // SelectionFont = new Font(Font.FontFamily, Font.Size, ~FontStyle.Italic & Font.Style); // } // else // SelectionFont = new Font(Font.FontFamily, Font.Size, FontStyle.Italic | Font.Style); // break; } } } } /// <summary> /// RichTextBox Printer /// </summary> /// <remarks> /// http://support.microsoft.com/default.aspx?scid=kb;en-us;812425 /// The RichTextBox control does not provide any method to print the content of the RichTextBox. /// You can extend the RichTextBox class to use EM_FORMATRANGE message /// to send the content of a RichTextBox control to an output device such as printer. /// </remarks> public class RichTextBoxPrinter { /// <summary> /// Convert the unit used by the .NET framework (1/100 inch) /// and the unit used by Win32 API calls (twips 1/1440 inch) /// </summary> private const Double AN_INCH = 14.4; /// <summary> /// RECT /// </summary> [StructLayout(LayoutKind.Sequential)] private struct Rect { /// <summary> /// Left /// </summary> public Int32 Left; /// <summary> /// Top /// </summary> public Int32 Top; /// <summary> /// Right /// </summary> public Int32 Right; /// <summary> /// Bottom /// </summary> public Int32 Bottom; } /// <summary> /// CHARRANGE /// </summary> [StructLayout(LayoutKind.Sequential)] private struct Charrange { /// <summary> /// First character of range (0 for start of doc) /// </summary> public Int32 cpMin; /// <summary> /// Last character of range (-1 for end of doc) /// </summary> public Int32 cpMax; } /// <summary> /// FORMAT RANGE /// </summary> [StructLayout(LayoutKind.Sequential)] private struct Formatrange { /// <summary> /// Actual DC to draw on /// </summary> public IntPtr hdc; /// <summary> /// Target DC for determining text formatting /// </summary> public IntPtr hdcTarget; /// <summary> /// Region of the DC to draw to (in twips) /// </summary> public Rect rc; /// <summary> /// Region of the whole DC (page size) (in twips) /// </summary> public Rect rcPage; /// <summary> /// Range of text to draw (see earlier declaration) /// </summary> public Charrange chrg; } /// <summary> /// WM USER /// </summary> private const Int32 WM_USER = 0x0400; /// <summary> /// EM FORMATRANGE /// </summary> private const Int32 EM_FORMATRANGE = WM_USER + 57; [DllImport("USER32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, Int32 msg, IntPtr wp, IntPtr lp); /// <summary> /// Render the contents of the RichTextBox for printing /// </summary> /// <param name="richTextBoxHandle"> /// The rich text box handle. /// </param> /// <param name="charFrom"> /// The char from. /// </param> /// <param name="charTo"> /// The char to. /// </param> /// <param name="e"> /// The e. /// </param> /// <returns> /// Return the last character printed + 1 (printing start from this point for next page) /// </returns> public static Int32 Print(IntPtr richTextBoxHandle, Int32 charFrom, Int32 charTo, PrintPageEventArgs e) { // Calculate the area to render and print Rect rectToPrint; rectToPrint.Top = (int)(e.MarginBounds.Top * AN_INCH); rectToPrint.Bottom = (int)(e.MarginBounds.Bottom * AN_INCH); rectToPrint.Left = (int)(e.MarginBounds.Left * AN_INCH); rectToPrint.Right = (int)(e.MarginBounds.Right * AN_INCH); // Calculate the size of the page Rect rectPage; rectPage.Top = (int)(e.PageBounds.Top * AN_INCH); rectPage.Bottom = (int)(e.PageBounds.Bottom * AN_INCH); rectPage.Left = (int)(e.PageBounds.Left * AN_INCH); rectPage.Right = (int)(e.PageBounds.Right * AN_INCH); IntPtr hdc = e.Graphics.GetHdc(); Formatrange fmtRange; fmtRange.chrg.cpMax = charTo; // Indicate character from to character to fmtRange.chrg.cpMin = charFrom; fmtRange.hdc = hdc; // Use the same DC for measuring and rendering fmtRange.hdcTarget = hdc; // Point at printer hDC fmtRange.rc = rectToPrint; // Indicate the area on page to print fmtRange.rcPage = rectPage; // Indicate size of page IntPtr wparam = new IntPtr(1); // Get the pointer to the FORMATRANGE structure in memory IntPtr lparam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange)); Marshal.StructureToPtr(fmtRange, lparam, false); // Send the rendered data for printing IntPtr res = SendMessage(richTextBoxHandle, EM_FORMATRANGE, wparam, lparam); // Free the block of memory allocated Marshal.FreeCoTaskMem(lparam); // Release the device context handle obtained by a previous call e.Graphics.ReleaseHdc(hdc); // Release and cached info SendMessage(richTextBoxHandle, EM_FORMATRANGE, (IntPtr)0, (IntPtr)0); // Return last + 1 character printer return res.ToInt32(); } /// <summary> /// Print control to image /// </summary> /// <param name="ctl"> /// The ctl. /// </param> /// <param name="width"> /// The width. /// </param> /// <param name="height"> /// The height. /// </param> /// <param name="padding"> /// The padding. /// </param> /// <returns> /// Image from control /// </returns> public static Image Print(RichTextBox ctl, Int32 width, Int32 height, Padding padding) { Image img = new Bitmap(width, height); using (Graphics g = Graphics.FromImage(img)) { // HorizontalResolution is measured in pix/inch float scale = width * 100 / img.HorizontalResolution; width = (int)scale; // VerticalResolution is measured in pix/inch scale = height * 100 / img.VerticalResolution; height = (int)scale; Rectangle marginBounds = new Rectangle(padding.Left, padding.Top, width - padding.Right, height - padding.Bottom); Rectangle pageBounds = new Rectangle(0, 0, width, height); PrintPageEventArgs args = new PrintPageEventArgs(g, marginBounds, pageBounds, null); Print(ctl.Handle, 0, ctl.Text.Length, args); } return img; } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation. All Rights Reserved. // // File: BitmapImage.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Internal.PresentationCore; using MS.Win32; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Markup; using System.Net.Cache; namespace System.Windows.Media.Imaging { #region BitmapImage /// <summary> /// BitmapImage provides caching functionality for a BitmapSource. /// </summary> public sealed partial class BitmapImage : Imaging.BitmapSource, ISupportInitialize, IUriContext { /// <summary> /// BitmapImage constructor /// </summary> public BitmapImage() : base(true) // Use base class virtuals { } /// <summary> /// Construct a BitmapImage with the given Uri /// </summary> /// <param name="uriSource">Uri of the source Bitmap</param> public BitmapImage(Uri uriSource) : this(uriSource, null) { } /// <summary> /// Construct a BitmapImage with the given Uri and RequestCachePolicy /// </summary> /// <param name="uriSource">Uri of the source Bitmap</param> /// <param name="uriCachePolicy">Optional web request cache policy</param> public BitmapImage(Uri uriSource, RequestCachePolicy uriCachePolicy) : base(true) // Use base class virtuals { if (uriSource == null) { throw new ArgumentNullException("uriSource"); } BeginInit(); UriSource = uriSource; UriCachePolicy = uriCachePolicy; EndInit(); } #region ISupportInitialize /// <summary> /// Prepare the bitmap to accept initialize paramters. /// </summary> public void BeginInit() { WritePreamble(); _bitmapInit.BeginInit(); } /// <summary> /// Prevent the bitmap from accepting any further initialize paramters. /// </summary> public void EndInit() { WritePreamble(); _bitmapInit.EndInit(); if (UriSource == null && StreamSource == null) { throw new InvalidOperationException(SR.Get(SRID.Image_NeitherArgument, "UriSource", "StreamSource")); } // If the Uri is relative, use delay creation as the BaseUri could be set at a later point if (UriSource != null && !UriSource.IsAbsoluteUri && CacheOption != BitmapCacheOption.OnLoad) { DelayCreation = true; } if (!DelayCreation && !CreationCompleted) FinalizeCreation(); } #endregion #region IUriContext /// <summary> /// Provides the base uri of the current context. /// </summary> public Uri BaseUri { get { ReadPreamble(); return _baseUri; } set { WritePreamble(); if (!CreationCompleted && _baseUri != value) { _baseUri = value; WritePostscript(); } } } #endregion #region Properties /// <summary> /// Returns if the BitmapFrame is downloading content /// </summary> public override bool IsDownloading { get { ReadPreamble(); return _isDownloading; } } /// <summary> /// Get the Metadata of the bitmap /// </summary> public override ImageMetadata Metadata { get { throw new System.NotSupportedException(SR.Get(SRID.Image_MetadataNotSupported)); } } #endregion #region ToString /// <summary> /// Can serialze "this" to a string /// </summary> internal override bool CanSerializeToString() { ReadPreamble(); return ( // UriSource not null UriSource != null && // But rest are defaults StreamSource == null && SourceRect.IsEmpty && DecodePixelWidth == 0 && DecodePixelHeight == 0 && Rotation == Rotation.Rotate0 && CreateOptions == BitmapCreateOptions.None && CacheOption == BitmapCacheOption.Default && UriCachePolicy == null ); } /// <summary> /// Creates a string representation of this object based on the format string /// and IFormatProvider passed in. /// If the provider is null, the CurrentCulture is used. /// See the documentation for IFormattable for more information. /// </summary> /// <returns> /// A string representation of this object. /// </returns> internal override string ConvertToString(string format, IFormatProvider provider) { ReadPreamble(); if (UriSource != null) { if (_baseUri != null) { return BindUriHelper.UriToString(new Uri(_baseUri, UriSource)); } else { return BindUriHelper.UriToString(UriSource); } } return base.ConvertToString(format, provider); } #endregion private void ClonePrequel(BitmapImage otherBitmapImage) { BeginInit(); _isDownloading = otherBitmapImage._isDownloading; _decoder = otherBitmapImage._decoder; _baseUri = otherBitmapImage._baseUri; } private void ClonePostscript(BitmapImage otherBitmapImage) { // // If the previous BitmapImage is downloading, we need to listen for those // events as our state will change based on when the download is done. // // NOTE -- This cannot happen in ClonePrequel as CopyCommon on BitmapSource // is called after ClonePrequel which clones the event handlers, // which will cause a reference onto itself and cause a Stack Overflow. // if (_isDownloading) { Debug.Assert(_decoder != null); _decoder.DownloadProgress += OnDownloadProgress; _decoder.DownloadCompleted += OnDownloadCompleted; _decoder.DownloadFailed += OnDownloadFailed; } EndInit(); } /// Check the cache for an existing BitmapImage private BitmapImage CheckCache(Uri uri) { if (uri != null) { WeakReference bitmapWeakReference = ImagingCache.CheckImageCache(uri) as WeakReference; if (bitmapWeakReference != null) { BitmapImage bitmapImage = (bitmapWeakReference.Target as BitmapImage); // See if this bitmap was already in the image cache. if (bitmapImage != null) { return bitmapImage; } else { ImagingCache.RemoveFromImageCache(uri); } } } return null; } /// Insert BitmapImage in cache private void InsertInCache(Uri uri) { if (uri != null) { // // Keeping the image bits alive in the cache can bloat working set by 40-50mb in // common scenarios. So, keep weak refereances in the cache so that we don't keep // bits around indefinitely. // // We currently get cache benefits if: // // 1. We have multiple references to the same bitmap on the same page // 2. A bitmap is referenced before a GC and the object is still alive // 3. The user explicit holds onto the bitmap object and keeps the cache alive // // Note that this cache is the in-memory cache for bitmap loads from disk. If we miss, // we will likely hit the disk cache, so cache misses can be reasonable. Downloads off the // network are cached to disk at another level and are unaffected by the weak references. // ImagingCache.AddToImageCache(uri, new WeakReference(this)); } } /// /// Create the unmanaged resources /// /// <SecurityNote> /// Critical - eventually accesss critical resources /// TreatAsSafe - All inputs verified /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal override void FinalizeCreation() { _bitmapInit.EnsureInitializedComplete(); Uri uri = UriSource; if (_baseUri != null) uri = new Uri(_baseUri, UriSource); if ((CreateOptions & BitmapCreateOptions.IgnoreImageCache) != 0) { ImagingCache.RemoveFromImageCache(uri); } BitmapImage bitmapImage = CheckCache(uri); if (bitmapImage != null && bitmapImage.CheckAccess() && bitmapImage.SourceRect.Equals(SourceRect) && bitmapImage.DecodePixelWidth == DecodePixelWidth && bitmapImage.DecodePixelHeight == DecodePixelHeight && bitmapImage.Rotation == Rotation && (bitmapImage.CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == (CreateOptions & BitmapCreateOptions.IgnoreColorProfile) ) { _syncObject = bitmapImage.SyncObject; lock (_syncObject) { WicSourceHandle = bitmapImage.WicSourceHandle; IsSourceCached = bitmapImage.IsSourceCached; _convertedDUCEPtr = bitmapImage._convertedDUCEPtr; // // We nee d to keep the strong reference to the cached image for a few reasons: // // The application may release the original cached image and then keep a // reference to this image only, in which case, the cache can be collected. // This will cause a few undesirable results: // 1. The application may choose to decode the same URI again in which case // we will not retrieve it from the cache even though we have a copy already // decoded. // 2. The original cached image holds onto the file stream indirectly which if // collected can cause bad behavior if the entire image is not loaded into // memory. // _cachedBitmapImage = bitmapImage; } UpdateCachedSettings(); return; } BitmapDecoder decoder = null; if (_decoder == null) { // Note: We do not want to insert in the cache if there is a chance that // the decode pixel width/height may cause the decoder LOD to change decoder = BitmapDecoder.CreateFromUriOrStream( _baseUri, UriSource, StreamSource, CreateOptions & ~BitmapCreateOptions.DelayCreation, BitmapCacheOption.None, // do not cache the frames since we will do that here _uriCachePolicy, false ); if (decoder.IsDownloading) { _isDownloading = true; _decoder = decoder; decoder.DownloadProgress += OnDownloadProgress; decoder.DownloadCompleted += OnDownloadCompleted; decoder.DownloadFailed += OnDownloadFailed; } else { Debug.Assert(decoder.SyncObject != null); } } else { // We already had a decoder, meaning we were downloading Debug.Assert(!_decoder.IsDownloading); decoder = _decoder; _decoder = null; } if (decoder.Frames.Count == 0) { throw new System.ArgumentException(SR.Get(SRID.Image_NoDecodeFrames)); } BitmapFrame frame = decoder.Frames[0]; BitmapSource source = frame; Int32Rect sourceRect = SourceRect; if (sourceRect.X == 0 && sourceRect.Y == 0 && sourceRect.Width == source.PixelWidth && sourceRect.Height == source.PixelHeight) { sourceRect = Int32Rect.Empty; } if (!sourceRect.IsEmpty) { CroppedBitmap croppedSource = new CroppedBitmap(); croppedSource.BeginInit(); croppedSource.Source = source; croppedSource.SourceRect = sourceRect; croppedSource.EndInit(); source = croppedSource; if (_isDownloading) { // Unregister the download events because this is a dummy image. See comment below. source.UnregisterDownloadEventSource(); } } int finalWidth = DecodePixelWidth; int finalHeight = DecodePixelHeight; if (finalWidth == 0 && finalHeight == 0) { finalWidth = source.PixelWidth; finalHeight = source.PixelHeight; } else if (finalWidth == 0) { finalWidth = (source.PixelWidth * finalHeight) / source.PixelHeight; } else if (finalHeight == 0) { finalHeight = (source.PixelHeight * finalWidth) / source.PixelWidth; } if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight || Rotation != Rotation.Rotate0) { TransformedBitmap transformedSource = new TransformedBitmap(); transformedSource.BeginInit(); transformedSource.Source = source; TransformGroup transformGroup = new TransformGroup(); if (finalWidth != source.PixelWidth || finalHeight != source.PixelHeight) { int oldWidth = source.PixelWidth; int oldHeight = source.PixelHeight; Debug.Assert(oldWidth > 0 && oldHeight > 0); transformGroup.Children.Add( new ScaleTransform( (1.0*finalWidth)/ oldWidth, (1.0*finalHeight)/oldHeight)); } if (Rotation != Rotation.Rotate0) { double rotation = 0.0; switch (Rotation) { case Rotation.Rotate0: rotation = 0.0; break; case Rotation.Rotate90: rotation = 90.0; break; case Rotation.Rotate180: rotation = 180.0; break; case Rotation.Rotate270: rotation = 270.0; break; default: Debug.Assert(false); break; } transformGroup.Children.Add(new RotateTransform(rotation)); } transformedSource.Transform = transformGroup; transformedSource.EndInit(); source = transformedSource; if (_isDownloading) { // // If we're currently downloading, then the BitmapFrameDecode isn't actually // the image, it's just a 1x1 placeholder. The chain we're currently building // will be replaced with another chain once download completes, so there's no // need to have this chain handle DownloadCompleted. // // Having this chain handle DownloadCompleted is actually a bad thing. Because // the dummy is just 1x1, the TransformedBitmap we're building here will have // a large scaling factor (to scale the image from 1x1 up to whatever // DecodePixelWidth/Height specifies). When the TransformedBitmap receives // DownloadCompleted from the BFD, it will call into WIC to create a new // bitmap scaler using the same large scaling factor, which can produce a huge // bitmap (since the BFD is now no longer 1x1). This problem is made worse if // this BitmapImage has BitmapCacheOption.OnLoad, since that will put a // CachedBitmap after the TransformedBitmap. When DownloadCompleted propagates // from the TransformedBitmap down to the CachedBitmap, the CachedBitmap will // call CreateBitmapFromSource using the TransformedBitmap, which calls // CopyPixels on the huge TransformedBitmap. We want to avoid chewing up the // CPU and the memory, so we unregister the download event handlers here. // source.UnregisterDownloadEventSource(); } } // // If the original image has a color profile and IgnoreColorProfile is not one of the create options, // apply the profile so bits are color-corrected. // if ((CreateOptions & BitmapCreateOptions.IgnoreColorProfile) == 0 && frame.ColorContexts != null && frame.ColorContexts[0] != null && frame.ColorContexts[0].IsValid && source.Format.Format != PixelFormatEnum.Extended ) { // NOTE: Never do this for a non-MIL pixel format, because the format converter has // special knowledge to deal with the profile PixelFormat duceFormat = BitmapSource.GetClosestDUCEFormat(source.Format, source.Palette); bool changeFormat = (source.Format != duceFormat); ColorContext destinationColorContext; // We need to make sure, we can actually create the ColorContext for the destination duceFormat // If the duceFormat is gray or scRGB, the following is not supported, so we cannot // create the ColorConvertedBitmap try { destinationColorContext= new ColorContext(duceFormat); } catch (NotSupportedException) { destinationColorContext = null; } if (destinationColorContext != null) { bool conversionSuccess = false; bool badColorContext = false; // First try if the color converter can handle the source format directly // Its possible that the color converter does not support certain pixelformats, so put a try/catch here. try { ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap( source, frame.ColorContexts[0], destinationColorContext, duceFormat ); source = colorConvertedBitmap; if (_isDownloading) { // Unregister the download events because this is a dummy image. See comment above. source.UnregisterDownloadEventSource(); } conversionSuccess = true; } catch (NotSupportedException) { } catch (FileFormatException) { // If the file contains a bad color context, we catch the exception here // and don't bother trying the color conversion below, since color transform isn't possible // with the given color context. badColorContext = true; } if (!conversionSuccess && !badColorContext && changeFormat) { // If the conversion failed, we first use // a FormatConvertedBitmap, and then Color Convert that one... FormatConvertedBitmap formatConvertedBitmap = new FormatConvertedBitmap(source, duceFormat, source.Palette, 0.0); ColorConvertedBitmap colorConvertedBitmap = new ColorConvertedBitmap( formatConvertedBitmap, frame.ColorContexts[0], destinationColorContext, duceFormat ); source = colorConvertedBitmap; if (_isDownloading) { // Unregister the download events because this is a dummy image. See comment above. source.UnregisterDownloadEventSource(); } } } } if (CacheOption != BitmapCacheOption.None) { try { // The bitmaps bits could be corrupt, and this will cause an exception if the CachedBitmap forces a decode. CachedBitmap cachedSource = new CachedBitmap(source, CreateOptions & ~BitmapCreateOptions.DelayCreation, CacheOption); source = cachedSource; if (_isDownloading) { // Unregister the download events because this is a dummy image. See comment above. source.UnregisterDownloadEventSource(); } } catch (Exception e) { RecoverFromDecodeFailure(e); CreationCompleted = true; // we're bailing out because the decode failed return; } } // If CacheOption == OnLoad, no need to keep the stream around if (decoder != null && CacheOption == BitmapCacheOption.OnLoad) { decoder.CloseStream(); } else if (CacheOption != BitmapCacheOption.OnLoad) { //ensure that we don't GC the source _finalSource = source; } WicSourceHandle = source.WicSourceHandle; IsSourceCached = source.IsSourceCached; CreationCompleted = true; UpdateCachedSettings(); // Only insert in the imaging cache if download is complete if (!IsDownloading) { InsertInCache(uri); } } private void UriCachePolicyPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _uriCachePolicy = e.NewValue as RequestCachePolicy; } } private void UriSourcePropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _uriSource = e.NewValue as Uri; } } private void StreamSourcePropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _streamSource = e.NewValue as Stream; } } private void DecodePixelWidthPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _decodePixelWidth = (Int32)e.NewValue; } } private void DecodePixelHeightPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _decodePixelHeight = (Int32)e.NewValue; } } private void RotationPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _rotation = (Rotation)e.NewValue; } } private void SourceRectPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _sourceRect = (Int32Rect)e.NewValue; } } private void CreateOptionsPropertyChangedHook(DependencyPropertyChangedEventArgs e) { BitmapCreateOptions options = (BitmapCreateOptions)e.NewValue; _createOptions = options; DelayCreation = ((options & BitmapCreateOptions.DelayCreation) != 0); } private void CacheOptionPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _cacheOption = (BitmapCacheOption)e.NewValue; } } /// <summary> /// Coerce UriCachePolicy /// </summary> private static object CoerceUriCachePolicy(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._uriCachePolicy; } else { return value; } } /// <summary> /// Coerce UriSource /// </summary> private static object CoerceUriSource(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._uriSource; } else { return value; } } /// <summary> /// Coerce StreamSource /// </summary> private static object CoerceStreamSource(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._streamSource; } else { return value; } } /// <summary> /// Coerce DecodePixelWidth /// </summary> private static object CoerceDecodePixelWidth(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._decodePixelWidth; } else { return value; } } /// <summary> /// Coerce DecodePixelHeight /// </summary> private static object CoerceDecodePixelHeight(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._decodePixelHeight; } else { return value; } } /// <summary> /// Coerce Rotation /// </summary> private static object CoerceRotation(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._rotation; } else { return value; } } /// <summary> /// Coerce SourceRect /// </summary> private static object CoerceSourceRect(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._sourceRect; } else { return value; } } /// <summary> /// Coerce CreateOptions /// </summary> private static object CoerceCreateOptions(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._createOptions; } else { return value; } } /// <summary> /// Coerce CacheOption /// </summary> private static object CoerceCacheOption(DependencyObject d, object value) { BitmapImage image = (BitmapImage)d; if (!image._bitmapInit.IsInInit) { return image._cacheOption; } else { return value; } } /// Called when decoder finishes download private void OnDownloadCompleted(object sender, EventArgs e) { _isDownloading = false; // // Unhook the decoders download events // _decoder.DownloadProgress -= OnDownloadProgress; _decoder.DownloadCompleted -= OnDownloadCompleted; _decoder.DownloadFailed -= OnDownloadFailed; if ((CreateOptions & BitmapCreateOptions.DelayCreation) != 0) { DelayCreation = true; } else { FinalizeCreation(); // Trigger a update of the UCE resource _needsUpdate = true; RegisterForAsyncUpdateResource(); FireChanged(); } _downloadEvent.InvokeEvents(this, null); } /// Called when download progress is made private void OnDownloadProgress(object sender, DownloadProgressEventArgs e) { _progressEvent.InvokeEvents(this, e); } /// Called when download fails private void OnDownloadFailed(object sender, ExceptionEventArgs e) { _isDownloading = false; // // Unhook the decoders download events // _decoder.DownloadProgress -= OnDownloadProgress; _decoder.DownloadCompleted -= OnDownloadCompleted; _decoder.DownloadFailed -= OnDownloadFailed; _failedEvent.InvokeEvents(this, e); } #region Data Members // Base Uri from IUriContext private Uri _baseUri; /// Is downloading content private bool _isDownloading; /// Bitmap Decoder private BitmapDecoder _decoder; private RequestCachePolicy _uriCachePolicy; private Uri _uriSource; private Stream _streamSource; private Int32 _decodePixelWidth; private Int32 _decodePixelHeight; private Rotation _rotation; private Int32Rect _sourceRect; private BitmapCreateOptions _createOptions; private BitmapCacheOption _cacheOption; // used to ensure the source isn't GC'd private BitmapSource _finalSource; private BitmapImage _cachedBitmapImage; #endregion } #endregion // BitmapImage }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Management.Automation; using System.Net; using System.Net.Security; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using XenAPI; namespace Citrix.XenServer.Commands { [Cmdlet("Connect", "XenServer")] public class ConnectXenServerCommand : PSCmdlet { public ConnectXenServerCommand() { Port = 443; } #region Cmdlet Parameters [Parameter(ParameterSetName = "Url", Mandatory = true, Position = 0)] public string[] Url { get; set; } [Parameter(ParameterSetName = "ServerPort", Mandatory = true, Position = 0)] [Alias("svr")] public string[] Server { get; set; } [Parameter(ParameterSetName = "ServerPort")] public int Port { get; set; } [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [Alias("cred")] public PSCredential Creds { get; set; } [Parameter(Position = 1)] [Alias("user")] public string UserName { get; set; } [Parameter(Position = 2)] [Alias("pwd")] public string Password { get; set; } [Parameter] public string[] OpaqueRef { get; set; } [Parameter] public SwitchParameter PassThru { get; set; } [Parameter] public SwitchParameter NoWarnNewCertificates { get; set; } [Parameter] public SwitchParameter NoWarnCertificates { get; set; } [Parameter] public SwitchParameter SetDefaultSession { get; set; } [Parameter] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { if ((Url == null || Url.Length == 0) && (Server == null || Server.Length == 0)) { ThrowTerminatingError(new ErrorRecord( new Exception("You must provide a URL, Name or IP Address for the XenServer."), "", ErrorCategory.InvalidArgument, null)); } if (Creds == null && (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) && (OpaqueRef == null || OpaqueRef.Length == 0)) { Creds = Host.UI.PromptForCredential("XenServer Credential Request", "", string.IsNullOrEmpty(UserName) ? "root" : UserName, ""); if (Creds == null) { // Just bail out at this point, they've clicked cancel on the credentials pop up dialog ThrowTerminatingError(new ErrorRecord( new Exception("Credentials must be supplied when connecting to the XenServer."), "", ErrorCategory.InvalidArgument, null)); } } string connUser = ""; string connPassword = ""; if (OpaqueRef == null || OpaqueRef.Length == 0) { if (Creds == null) { connUser = UserName; connPassword = Password; SecureString secPwd = new SecureString(); foreach (char ch in connPassword) secPwd.AppendChar(ch); Creds = new PSCredential(UserName, secPwd); } else { connUser = Creds.UserName.StartsWith("\\") ? Creds.GetNetworkCredential().UserName : Creds.UserName; IntPtr ptrPassword = Marshal.SecureStringToBSTR(Creds.Password); connPassword = Marshal.PtrToStringBSTR(ptrPassword); Marshal.FreeBSTR(ptrPassword); } } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); if (Url == null || Url.Length == 0) { Url = new string[Server.Length]; for (int i = 0; i < Server.Length; i++) Url[i] = CommonCmdletFunctions.GetUrl(Server[i], Port); } if (OpaqueRef == null) { OpaqueRef = new string[Url.Length]; } else { if (OpaqueRef.Length != Url.Length) ThrowTerminatingError(new ErrorRecord( new Exception("The number of opaque references provided should be the same as the number of xenservers."), "", ErrorCategory.InvalidArgument, null)); } Dictionary<string, Session> sessions = CommonCmdletFunctions.GetAllSessions(this); Dictionary<string, Session> newSessions = new Dictionary<string, Session>(); for (int i = 0; i < Url.Length; i++) { Session session; if (string.IsNullOrEmpty(OpaqueRef[i])) { session = new Session(Url[i]); session.login_with_password(connUser, connPassword); } else { session = new Session(Url[i], OpaqueRef[i]); } session.Tag = Creds; session.opaque_ref = session.uuid; sessions[session.opaque_ref] = session; newSessions[session.opaque_ref] = session; if (i > 0) continue; //set the first of the specified connections as default if (SetDefaultSession) { WriteVerbose(string.Format("Setting connection {0} ({1}) as default.", session.Url, session.opaque_ref)); CommonCmdletFunctions.SetDefaultXenSession(this, session); } } CommonCmdletFunctions.SetAllSessions(this, sessions); if (PassThru) WriteObject(newSessions.Values, true); } #region Messages const string CERT_HAS_CHANGED_CAPTION = "Security Certificate Changed"; const string CERT_CHANGED = "The certificate fingerprint of the server you have connected to is:\n{0}\nBut was expected to be:\n{1}\n{2}\nDo you wish to continue?"; const string CERT_FOUND_CAPTION = "New Security Certificate"; const string CERT_FOUND = "The certificate fingerprint of the server you have connected to is :\n{0}\n{1}\nDo you wish to continue?"; const string CERT_TRUSTED = "The certificate on this server is trusted. It is recommended you re-issue this server's certificate."; const string CERT_NOT_TRUSTED = "The certificate on this server is not trusted."; #endregion private readonly object certificateValidationLock = new object(); private bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; lock(certificateValidationLock) { bool ignoreChanged = NoWarnCertificates || (bool)GetVariableValue("NoWarnCertificates", false); bool ignoreNew = ignoreChanged || NoWarnNewCertificates || (bool)GetVariableValue("NoWarnNewCertificates", false); HttpWebRequest webreq = (HttpWebRequest)sender; string hostname = webreq.Address.Host; string fingerprint = CommonCmdletFunctions.FingerprintPrettyString(certificate.GetCertHashString()); string trusted = VerifyInAllStores(new X509Certificate2(certificate)) ? CERT_TRUSTED : CERT_NOT_TRUSTED; var certificates = CommonCmdletFunctions.LoadCertificates(); bool ok; if (certificates.ContainsKey(hostname)) { string fingerprint_old = certificates[hostname]; if (fingerprint_old == fingerprint) return true; ok = Force || ignoreChanged || ShouldContinue(string.Format(CERT_CHANGED, fingerprint, fingerprint_old, trusted), CERT_HAS_CHANGED_CAPTION); } else { ok = Force || ignoreNew || ShouldContinue(string.Format(CERT_FOUND, fingerprint, trusted), CERT_FOUND_CAPTION); } if (ok) { certificates[hostname] = fingerprint; CommonCmdletFunctions.SaveCertificates(certificates); } return ok; } } private bool VerifyInAllStores(X509Certificate2 certificate2) { try { X509Chain chain = new X509Chain(true); return chain.Build(certificate2) || certificate2.Verify(); } catch (CryptographicException) { return false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal static class ContainedLanguageCodeSupport { public static bool IsValidId(Document document, string identifier) { var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); return syntaxFacts.IsValidIdentifier(identifier); } public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName) { baseClassName = null; var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); if (type == null || type.BaseType == null) { return false; } baseClassName = type.BaseType.ToDisplayString(); return true; } public static string CreateUniqueEventName( Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var name = objectName + "_" + nameOfEvent; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var tree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First(); var codeModel = document.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var point = codeModel.GetStartPoint(typeNode, EnvDTE.vsCMPart.vsCMPartBody); var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name); return NameGenerator.EnsureUniqueness(name, reservedNames, document.Project.LanguageServices.GetService<ISyntaxFactsService>().IsCaseSensitive); } /// <summary> /// Determine what methods of <paramref name=" className"/> could possibly be used as event /// handlers. /// </summary> /// <param name="document">The document containing <paramref name="className"/>.</param> /// <param name="className">The name of the type whose methods should be considered.</param> /// <param name="objectTypeName">The fully qualified name of the type containing a member /// that is an event. (E.g. "System.Web.Forms.Button")</param> /// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/> /// that is the event (E.g. "Clicked")</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The display name of the method, and a unique to for the method.</returns> public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers( Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = compilation.GetTypeByMetadataName(className); if (type == null) { throw new InvalidOperationException(); } var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType)); return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken) { var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName); return nameAndId == null ? null : nameAndId.Item2; } /// <summary> /// Ensure that an event handler exists for a given event. /// </summary> /// <param name="thisDocument">The document corresponding to this operation.</param> /// <param name="targetDocument">The document to generate the event handler in if it doesn't /// exist.</param> /// <param name="className">The name of the type to generate the event handler in.</param> /// <param name="objectName">The name of the event member (if <paramref /// name="useHandlesClause"/> is true)</param> /// <param name="objectTypeName">The name of the type containing the event.</param> /// <param name="nameOfEvent">The name of the event member in <paramref /// name="objectTypeName"/></param> /// <param name="eventHandlerName">The name of the method to be hooked up to the /// event.</param> /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event /// handler in.</param> /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the /// handler.</param> /// <param name="additionalFormattingRule">An additional formatting rule that can be used to /// format the newly inserted method</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Either the unique id of the method if it already exists, or the unique id of /// the to be generated method, the text of the to be generated method, and the position in /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns> public static Tuple<string, string, VsTextSpan> EnsureEventHandler( Document thisDocument, Document targetDocument, string className, string objectName, string objectTypeName, string nameOfEvent, string eventHandlerName, uint itemidInsertionPoint, bool useHandlesClause, IFormattingRule additionalFormattingRule, CancellationToken cancellationToken) { var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = thisCompilation.GetTypeByMetadataName(className); var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken); var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName); if (existingHandler != null) { return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan)); } // Okay, it doesn't exist yet. Let's create it. var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>(); var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>(); var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var handlesExpressions = useHandlesClause ? new[] { syntaxFactory.MemberAccessExpression( objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(), syntaxFactory.IdentifierName(nameOfEvent)) } : null; var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod; var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: null, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(), returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSpecialType(SpecialType.System_Void), explicitInterfaceSymbol: null, name: eventHandlerName, typeParameters: null, parameters: invokeMethod.Parameters.ToArray(), statements: null, handlesExpressions: handlesExpressions); var annotation = new SyntaxAnnotation(); newMethod = annotation.AddAnnotationToSymbol(newMethod); var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>(); var targetSyntaxTree = targetDocument.GetSyntaxTreeSynchronously(cancellationToken); var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start; var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position); var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody); if (insertionPoint == null) { throw new InvalidOperationException(ServicesVSResources.Can_t_find_where_to_insert_member); } var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); newRoot = Simplifier.ReduceAsync( targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); newRoot = Formatter.FormatAsync( newRoot, Formatter.Annotation, targetDocument.Project.Solution.Workspace, targetDocument.Options, formattingRules, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); // In VB, the final newline is likely a statement terminator in the parent - just add // one on so that things don't get messed. if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { newMemberText += Environment.NewLine; } return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan()); } public static bool TryGetMemberNavigationPoint( Document thisDocument, string className, string uniqueMemberID, out VsTextSpan textSpan, out Document targetDocument, CancellationToken cancellationToken) { targetDocument = null; textSpan = default(VsTextSpan); var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var member = LookupMemberId(type, uniqueMemberID); if (member == null) { return false; } var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (memberNode != null) { var navigationPoint = codeModel.GetStartPoint(memberNode, EnvDTE.vsCMPart.vsCMPartNavigate); if (navigationPoint != null) { targetDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree); textSpan = navigationPoint.Value.ToVsTextSpan(); return true; } } return false; } /// <summary> /// Get the display names and unique ids of all the members of the given type in <paramref /// name="className"/>. /// </summary> public static IEnumerable<Tuple<string, string>> GetMembers( Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ? semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) : type.GetMembers(); var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation)); return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } /// <summary> /// Try to do a symbolic rename the specified symbol. /// </summary> /// <returns>False ONLY if it can't resolve the name. Other errors result in the normal /// exception being propagated.</returns> public static bool TryRenameElement( Document document, ContainedLanguageRenameType clrt, string oldFullyQualifiedName, string newFullyQualifiedName, IEnumerable<IRefactorNotifyService> refactorNotifyServices, CancellationToken cancellationToken) { var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken); if (symbol == null) { return false; } Workspace workspace; if (Workspace.TryGetWorkspace(document.GetTextAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).Container, out workspace)) { var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1); var optionSet = document.Project.Solution.Workspace.Options; var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution); var undoTitle = string.Format(EditorFeaturesResources.Rename_0_to_1, symbol.Name, newName); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle)) { // Notify third parties about the coming rename operation on the workspace, and let // any exceptions propagate through refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); if (!workspace.TryApplyChanges(newSolution)) { Exceptions.ThrowEFail(); } // Notify third parties about the completed rename operation on the workspace, and // let any exceptions propagate through refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); workspaceUndoTransaction.Commit(); } RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } else { return false; } } private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation) { if (!member.CanBeReferencedByName) { return false; } switch (memberType) { case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS: // NOTE: the Dev10 C# codebase just returned if (member.Kind != SymbolKind.Method) { return false; } var method = (IMethodSymbol)member; if (!method.ReturnsVoid) { return false; } if (method.Parameters.Length != 2) { return false; } if (!method.Parameters[0].Type.Equals(compilation.ObjectType)) { return false; } if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType())) { return false; } return true; case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS: return member.Kind == SymbolKind.Event; case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS: return member.Kind == SymbolKind.Method; default: throw new ArgumentException("InvalidValue", nameof(memberType)); } } private static ISymbol FindSymbol( Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken) { switch (renameType) { case ContainedLanguageRenameType.CLRT_CLASS: return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(fullyQualifiedName); case ContainedLanguageRenameType.CLRT_CLASSMEMBER: var lastDot = fullyQualifiedName.LastIndexOf('.'); var typeName = fullyQualifiedName.Substring(0, lastDot); var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1); var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(typeName); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var membersOfName = type.GetMembers(memberName); return membersOfName.SingleOrDefault(); case ContainedLanguageRenameType.CLRT_NAMESPACE: var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GlobalNamespace; var parts = fullyQualifiedName.Split('.'); for (int i = 0; i < parts.Length && ns != null; i++) { ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]); } return ns; case ContainedLanguageRenameType.CLRT_OTHER: throw new NotSupportedException(ServicesVSResources.Can_t_rename_other_elements); default: throw new InvalidOperationException(ServicesVSResources.Unknown_rename_type); } } internal static string ConstructMemberId(ISymbol member) { if (member.Kind == SymbolKind.Method) { return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString()))); } else if (member.Kind == SymbolKind.Event) { return member.Name + "(EVENT)"; } else { throw new NotSupportedException(ServicesVSResources.IDs_are_not_supported_for_this_symbol_type); } } internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID) { var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('(')); var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method); foreach (var m in members) { if (ConstructMemberId(m) == uniqueMemberID) { return m; } } return null; } private static ISymbol GetEventSymbol( Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var objectType = compilation.GetTypeByMetadataName(objectTypeName); if (objectType == null) { throw new InvalidOperationException(); } var containingTree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree); if (typeLocation == null) { throw new InvalidOperationException(); } return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event); } } }
using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.Configuration; 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.IO; using System.Xml; using umbraco.cms.businesslogic.template; using umbraco.cms.businesslogic.web; using umbraco.cms.businesslogic.macro; using ICSharpCode.SharpZipLib.Zip; using Umbraco.Core.IO; namespace umbraco.cms.businesslogic.packager { /// <summary> /// A utillity class for working with packager data. /// It provides basic methods for adding new items to a package manifest, moving files and other misc. /// </summary> public class utill { /// <summary> /// Creates a package manifest containing name, license, version and other meta data. /// </summary> /// <param name="pack">The packinstance.</param> /// <param name="doc">The xml document.</param> /// <returns></returns> public static XmlNode PackageInfo(PackageInstance pack, XmlDocument doc) { XmlNode info = doc.CreateElement("info"); //Package info XmlNode package = doc.CreateElement("package"); package.AppendChild(_node("name", pack.Name, doc)); package.AppendChild(_node("version", pack.Version, doc)); XmlNode license = _node("license", pack.License, doc); license.Attributes.Append(_attribute("url", pack.LicenseUrl, doc)); package.AppendChild(license); package.AppendChild(_node("url", pack.Url, doc)); XmlNode Requirements = doc.CreateElement("requirements"); Requirements.AppendChild(_node("major", "3", doc)); Requirements.AppendChild(_node("minor", "0", doc)); Requirements.AppendChild(_node("patch", "0", doc)); package.AppendChild(Requirements); info.AppendChild(package); //Author XmlNode author = _node("author", "", doc); author.AppendChild(_node("name", pack.Author, doc)); author.AppendChild(_node("website", pack.AuthorUrl, doc)); info.AppendChild(author); info.AppendChild(_node("readme", "<![CDATA[" + pack.Readme + "]]>", doc)); return info; } /// <summary> /// Converts an umbraco template to a package xml node /// </summary> /// <param name="templateId">The template id.</param> /// <param name="doc">The xml doc.</param> /// <returns></returns> public static XmlNode Template(int templateId, XmlDocument doc) { Template tmpl = new Template(templateId); XmlNode template = doc.CreateElement("Template"); template.AppendChild(_node("Name", tmpl.Text, doc)); template.AppendChild(_node("Alias", tmpl.Alias, doc)); if (tmpl.MasterTemplate != 0) { template.AppendChild(_node("Master", new Template(tmpl.MasterTemplate).Alias, doc)); } template.AppendChild(_node("Design", "<![CDATA[" + tmpl.Design + "]]>", doc)); return template; } /// <summary> /// Converts a umbraco stylesheet to a package xml node /// </summary> /// <param name="ssId">The ss id.</param> /// <param name="incluceProperties">if set to <c>true</c> [incluce properties].</param> /// <param name="doc">The doc.</param> /// <returns></returns> public static XmlNode Stylesheet(int ssId, bool incluceProperties, XmlDocument doc) { StyleSheet sts = new StyleSheet(ssId); XmlNode stylesheet = doc.CreateElement("Stylesheet"); stylesheet.AppendChild(_node("Name", sts.Text, doc)); stylesheet.AppendChild(_node("FileName", sts.Filename, doc)); stylesheet.AppendChild(_node("Content", "<![CDATA[" + sts.Content + "]]>", doc)); if (incluceProperties) { XmlNode properties = doc.CreateElement("Properties"); foreach (StylesheetProperty ssP in sts.Properties) { XmlNode property = doc.CreateElement("Property"); property.AppendChild(_node("Name", ssP.Text, doc)); property.AppendChild(_node("Alias", ssP.Alias, doc)); property.AppendChild(_node("Value", ssP.value, doc)); //xnode += "<Property><Name>" + ssP.Text + "</Name><Alias>" + ssP.Alias + "</Alias><Value>" + ssP.value + "</Value></Property>\n"; } stylesheet.AppendChild(properties); } return stylesheet; } /// <summary> /// Converts a macro to a package xml node /// </summary> /// <param name="macroId">The macro id.</param> /// <param name="appendFile">if set to <c>true</c> [append file].</param> /// <param name="packageDirectory">The package directory.</param> /// <param name="doc">The doc.</param> /// <returns></returns> public static XmlNode Macro(int macroId, bool appendFile, string packageDirectory, XmlDocument doc) { Macro mcr = new Macro(macroId); if (appendFile) { if (!string.IsNullOrEmpty(mcr.Xslt)) AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.Xslt) + "/" + mcr.Xslt, packageDirectory, doc); if (!string.IsNullOrEmpty(mcr.ScriptingFile)) AppendFileToManifest(IOHelper.ResolveUrl(SystemDirectories.MacroScripts) + "/" + mcr.ScriptingFile, packageDirectory, doc); if (!string.IsNullOrEmpty(mcr.Type)) AppendFileToManifest(mcr.Type, packageDirectory, doc); } return mcr.ToXml(doc); } /// <summary> /// Appends a file to package manifest and copies the file to the correct folder. /// </summary> /// <param name="path">The path.</param> /// <param name="packageDirectory">The package directory.</param> /// <param name="doc">The doc.</param> public static void AppendFileToManifest(string path, string packageDirectory, XmlDocument doc) { if (!path.StartsWith("~/") && !path.StartsWith("/")) path = "~/" + path; string serverPath = IOHelper.MapPath(path); if (System.IO.File.Exists(serverPath)) { AppendFileXml(path, packageDirectory, doc); } else if(System.IO.Directory.Exists(serverPath)){ ProcessDirectory(path, packageDirectory, doc); } } //Process files in directory and add them to package private static void ProcessDirectory(string path, string packageDirectory, XmlDocument doc) { string serverPath = IOHelper.MapPath(path); if (System.IO.Directory.Exists(serverPath)) { System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(serverPath); foreach (System.IO.FileInfo file in di.GetFiles()) { AppendFileXml(path + "/" + file.Name, packageDirectory, doc); } foreach (System.IO.DirectoryInfo dir in di.GetDirectories()) { ProcessDirectory(path + "/" + dir.Name, packageDirectory, doc); } } } private static void AppendFileXml(string path, string packageDirectory, XmlDocument doc) { string serverPath = IOHelper.MapPath(path); string orgPath = path.Substring(0, (path.LastIndexOf('/'))); string orgName = path.Substring((path.LastIndexOf('/') + 1)); string newFileName = orgName; if (System.IO.File.Exists(packageDirectory + "/" + orgName)) { string fileGuid = System.Guid.NewGuid().ToString(); newFileName = fileGuid + "_" + newFileName; } //Copy file to directory for zipping... System.IO.File.Copy(serverPath, packageDirectory + "/" + newFileName, true); //Append file info to files xml node XmlNode files = doc.SelectSingleNode("/umbPackage/files"); XmlNode file = doc.CreateElement("file"); file.AppendChild(_node("guid", newFileName, doc)); file.AppendChild(_node("orgPath", orgPath == "" ? "/" : orgPath, doc)); file.AppendChild(_node("orgName", orgName, doc)); files.AppendChild(file); } /// <summary> /// Determines whether the file is in the package manifest /// </summary> /// <param name="guid">The GUID.</param> /// <param name="doc">The doc.</param> /// <returns> /// <c>true</c> if [is file in manifest]; otherwise, <c>false</c>. /// </returns> public static bool IsFileInManifest(string guid, XmlDocument doc) { return false; } private static XmlNode _node(string name, string value, XmlDocument doc) { XmlNode node = doc.CreateElement(name); node.InnerXml = value; return node; } private static XmlAttribute _attribute(string name, string value, XmlDocument doc) { XmlAttribute attribute = doc.CreateAttribute(name); attribute.Value = value; return attribute; } /// <summary> /// Zips the package. /// </summary> /// <param name="Path">The path.</param> /// <param name="savePath">The save path.</param> public static void ZipPackage(string Path, string savePath) { string OutPath = savePath; ArrayList ar = GenerateFileList(Path); // generate file list // find number of chars to remove from orginal file path int TrimLength = (Directory.GetParent(Path)).ToString().Length; TrimLength += 1; //remove '\' FileStream ostream; byte[] obuffer; ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath)); // create zip stream oZipStream.SetLevel(9); // 9 = maximum compression level ZipEntry oZipEntry; foreach (string Fil in ar) // for each file, generate a zipentry { oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipStream.PutNextEntry(oZipEntry); if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; // byte buffer ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); ostream.Close(); } } oZipStream.Finish(); oZipStream.Close(); oZipStream.Dispose(); oZipStream = null; oZipEntry = null; ostream = null; ar.Clear(); ar = null; } private static ArrayList GenerateFileList(string Dir) { ArrayList mid = new ArrayList(); bool Empty = true; foreach (string file in Directory.GetFiles(Dir)) // add each file in directory { mid.Add(file); Empty = false; } if (Empty) { if (Directory.GetDirectories(Dir).Length == 0) // if directory is completely empty, add it { mid.Add(Dir + @"/"); } } foreach (string dirs in Directory.GetDirectories(Dir)) // do this recursively { foreach (object obj in GenerateFileList(dirs)) { mid.Add(obj); } } return mid; // return file list } } }
/* * 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.Market; using QuantConnect.Indicators; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Constructs a displaced moving average ribbon and buys when all are lined up, liquidates when they all line down /// Ribbons are great for visualizing trends /// Signals are generated when they all line up in a paricular direction /// A buy signal is when the values of the indicators are increasing (from slowest to fastest). /// A sell signal is when the values of the indicators are decreasing (from slowest to fastest). /// </summary> public class DisplacedMovingAverageRibbon : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); private IndicatorBase<IndicatorDataPoint>[] _ribbon; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <meta name="tag" content="charting" /> /// <meta name="tag" content="plotting indicators" /> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { SetStartDate(2009, 01, 01); SetEndDate(2015, 01, 01); AddSecurity(SecurityType.Equity, "SPY", Resolution.Daily); const int count = 6; const int offset = 5; const int period = 15; // define our sma as the base of the ribbon var sma = new SimpleMovingAverage(period); _ribbon = Enumerable.Range(0, count).Select(x => { // define our offset to the zero sma, these various offsets will create our 'displaced' ribbon var delay = new Delay(offset*(x+1)); // define an indicator that takes the output of the sma and pipes it into our delay indicator var delayedSma = delay.Of(sma); // register our new 'delayedSma' for automaic updates on a daily resolution RegisterIndicator(_spy, delayedSma, Resolution.Daily, data => data.Value); return delayedSma; }).ToArray(); } private DateTime _previous; /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">TradeBars IDictionary object with your stock data</param> public void OnData(TradeBars data) { // wait for our entire ribbon to be ready if (!_ribbon.All(x => x.IsReady)) return; // only once per day if (_previous.Date == Time.Date) return; Plot("Ribbon", "Price", data[_spy].Price); Plot("Ribbon", _ribbon); // check for a buy signal var values = _ribbon.Select(x => x.Current.Value).ToArray(); var holding = Portfolio[_spy]; if (holding.Quantity <= 0 && IsAscending(values)) { SetHoldings(_spy, 1.0); } else if (holding.Quantity > 0 && IsDescending(values)) { Liquidate(_spy); } _previous = Time; } /// <summary> /// Returns true if the specified values are in ascending order /// </summary> private bool IsAscending(IEnumerable<decimal> values) { decimal? last = null; foreach (var val in values) { if (last == null) { last = val; continue; } if (last.Value < val) { return false; } last = val; } return true; } /// <summary> /// Returns true if the specified values are in descending order /// </summary> private bool IsDescending(IEnumerable<decimal> values) { decimal? last = null; foreach (var val in values) { if (last == null) { last = val; continue; } if (last.Value > val) { return false; } last = val; } return true; } /// <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", "7"}, {"Average Win", "19.18%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "16.740%"}, {"Drawdown", "12.400%"}, {"Expectancy", "0"}, {"Net Profit", "153.224%"}, {"Sharpe Ratio", "1.233"}, {"Probabilistic Sharpe Ratio", "65.906%"}, {"Loss Rate", "0%"}, {"Win Rate", "100%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.146"}, {"Beta", "-0.016"}, {"Annual Standard Deviation", "0.117"}, {"Annual Variance", "0.014"}, {"Information Ratio", "-0.052"}, {"Tracking Error", "0.204"}, {"Treynor Ratio", "-8.847"}, {"Total Fees", "$49.43"}, {"Estimated Strategy Capacity", "$740000000.00"}, {"Lowest Capacity Asset", "SPY R735QTJ8XC9X"}, {"Fitness Score", "0.002"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "1.609"}, {"Return Over Maximum Drawdown", "1.351"}, {"Portfolio Turnover", "0.003"}, {"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", "44481c3d7eeb5acd5e3bccfec501a132"} }; } }
// dnlib: See LICENSE.txt for more info using System.IO; using dnlib.IO; using dnlib.PE; using dnlib.DotNet.MD; namespace dnlib.DotNet.Writer { /// <summary> /// <see cref="TablesHeap"/> options /// </summary> public sealed class TablesHeapOptions { /// <summary> /// Should be 0 /// </summary> public uint? Reserved1; /// <summary> /// Major version number. Default is 2. Valid versions are v1.0 (no generics), /// v1.1 (generics are supported), or v2.0 (recommended). /// </summary> public byte? MajorVersion; /// <summary> /// Minor version number. Default is 0. /// </summary> public byte? MinorVersion; /// <summary> /// Force #- or #~ stream. Default value is <c>null</c> and recommended because the correct /// tables stream will be used. <c>true</c> will force <c>#-</c> (Edit N' Continue) /// stream, and <c>false</c> will force <c>#~</c> (normal compressed) stream. /// </summary> public bool? UseENC; /// <summary> /// Extra data to write /// </summary> public uint? ExtraData; /// <summary> /// <c>true</c> if there are deleted <see cref="TypeDef"/>s, <see cref="ExportedType"/>s, /// <see cref="FieldDef"/>s, <see cref="MethodDef"/>s, <see cref="EventDef"/>s and/or /// <see cref="PropertyDef"/>s. /// </summary> public bool? HasDeletedRows; } /// <summary> /// Contains all .NET tables /// </summary> public sealed class TablesHeap : IHeap { uint length; byte majorVersion; byte minorVersion; bool bigStrings; bool bigGuid; bool bigBlob; bool hasDeletedRows; readonly TablesHeapOptions options; FileOffset offset; RVA rva; /// <inheritdoc/> public FileOffset FileOffset { get { return offset; } } /// <inheritdoc/> public RVA RVA { get { return rva; } } #pragma warning disable 1591 // XML doc comment public readonly MDTable<RawModuleRow> ModuleTable = new MDTable<RawModuleRow>(Table.Module, RawRowEqualityComparer.Instance); public readonly MDTable<RawTypeRefRow> TypeRefTable = new MDTable<RawTypeRefRow>(Table.TypeRef, RawRowEqualityComparer.Instance); public readonly MDTable<RawTypeDefRow> TypeDefTable = new MDTable<RawTypeDefRow>(Table.TypeDef, RawRowEqualityComparer.Instance); public readonly MDTable<RawFieldPtrRow> FieldPtrTable = new MDTable<RawFieldPtrRow>(Table.FieldPtr, RawRowEqualityComparer.Instance); public readonly MDTable<RawFieldRow> FieldTable = new MDTable<RawFieldRow>(Table.Field, RawRowEqualityComparer.Instance); public readonly MDTable<RawMethodPtrRow> MethodPtrTable = new MDTable<RawMethodPtrRow>(Table.MethodPtr, RawRowEqualityComparer.Instance); public readonly MDTable<RawMethodRow> MethodTable = new MDTable<RawMethodRow>(Table.Method, RawRowEqualityComparer.Instance); public readonly MDTable<RawParamPtrRow> ParamPtrTable = new MDTable<RawParamPtrRow>(Table.ParamPtr, RawRowEqualityComparer.Instance); public readonly MDTable<RawParamRow> ParamTable = new MDTable<RawParamRow>(Table.Param, RawRowEqualityComparer.Instance); public readonly MDTable<RawInterfaceImplRow> InterfaceImplTable = new MDTable<RawInterfaceImplRow>(Table.InterfaceImpl, RawRowEqualityComparer.Instance); public readonly MDTable<RawMemberRefRow> MemberRefTable = new MDTable<RawMemberRefRow>(Table.MemberRef, RawRowEqualityComparer.Instance); public readonly MDTable<RawConstantRow> ConstantTable = new MDTable<RawConstantRow>(Table.Constant, RawRowEqualityComparer.Instance); public readonly MDTable<RawCustomAttributeRow> CustomAttributeTable = new MDTable<RawCustomAttributeRow>(Table.CustomAttribute, RawRowEqualityComparer.Instance); public readonly MDTable<RawFieldMarshalRow> FieldMarshalTable = new MDTable<RawFieldMarshalRow>(Table.FieldMarshal, RawRowEqualityComparer.Instance); public readonly MDTable<RawDeclSecurityRow> DeclSecurityTable = new MDTable<RawDeclSecurityRow>(Table.DeclSecurity, RawRowEqualityComparer.Instance); public readonly MDTable<RawClassLayoutRow> ClassLayoutTable = new MDTable<RawClassLayoutRow>(Table.ClassLayout, RawRowEqualityComparer.Instance); public readonly MDTable<RawFieldLayoutRow> FieldLayoutTable = new MDTable<RawFieldLayoutRow>(Table.FieldLayout, RawRowEqualityComparer.Instance); public readonly MDTable<RawStandAloneSigRow> StandAloneSigTable = new MDTable<RawStandAloneSigRow>(Table.StandAloneSig, RawRowEqualityComparer.Instance); public readonly MDTable<RawEventMapRow> EventMapTable = new MDTable<RawEventMapRow>(Table.EventMap, RawRowEqualityComparer.Instance); public readonly MDTable<RawEventPtrRow> EventPtrTable = new MDTable<RawEventPtrRow>(Table.EventPtr, RawRowEqualityComparer.Instance); public readonly MDTable<RawEventRow> EventTable = new MDTable<RawEventRow>(Table.Event, RawRowEqualityComparer.Instance); public readonly MDTable<RawPropertyMapRow> PropertyMapTable = new MDTable<RawPropertyMapRow>(Table.PropertyMap, RawRowEqualityComparer.Instance); public readonly MDTable<RawPropertyPtrRow> PropertyPtrTable = new MDTable<RawPropertyPtrRow>(Table.PropertyPtr, RawRowEqualityComparer.Instance); public readonly MDTable<RawPropertyRow> PropertyTable = new MDTable<RawPropertyRow>(Table.Property, RawRowEqualityComparer.Instance); public readonly MDTable<RawMethodSemanticsRow> MethodSemanticsTable = new MDTable<RawMethodSemanticsRow>(Table.MethodSemantics, RawRowEqualityComparer.Instance); public readonly MDTable<RawMethodImplRow> MethodImplTable = new MDTable<RawMethodImplRow>(Table.MethodImpl, RawRowEqualityComparer.Instance); public readonly MDTable<RawModuleRefRow> ModuleRefTable = new MDTable<RawModuleRefRow>(Table.ModuleRef, RawRowEqualityComparer.Instance); public readonly MDTable<RawTypeSpecRow> TypeSpecTable = new MDTable<RawTypeSpecRow>(Table.TypeSpec, RawRowEqualityComparer.Instance); public readonly MDTable<RawImplMapRow> ImplMapTable = new MDTable<RawImplMapRow>(Table.ImplMap, RawRowEqualityComparer.Instance); public readonly MDTable<RawFieldRVARow> FieldRVATable = new MDTable<RawFieldRVARow>(Table.FieldRVA, RawRowEqualityComparer.Instance); public readonly MDTable<RawENCLogRow> ENCLogTable = new MDTable<RawENCLogRow>(Table.ENCLog, RawRowEqualityComparer.Instance); public readonly MDTable<RawENCMapRow> ENCMapTable = new MDTable<RawENCMapRow>(Table.ENCMap, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyRow> AssemblyTable = new MDTable<RawAssemblyRow>(Table.Assembly, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyProcessorRow> AssemblyProcessorTable = new MDTable<RawAssemblyProcessorRow>(Table.AssemblyProcessor, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyOSRow> AssemblyOSTable = new MDTable<RawAssemblyOSRow>(Table.AssemblyOS, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyRefRow> AssemblyRefTable = new MDTable<RawAssemblyRefRow>(Table.AssemblyRef, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyRefProcessorRow> AssemblyRefProcessorTable = new MDTable<RawAssemblyRefProcessorRow>(Table.AssemblyRefProcessor, RawRowEqualityComparer.Instance); public readonly MDTable<RawAssemblyRefOSRow> AssemblyRefOSTable = new MDTable<RawAssemblyRefOSRow>(Table.AssemblyRefOS, RawRowEqualityComparer.Instance); public readonly MDTable<RawFileRow> FileTable = new MDTable<RawFileRow>(Table.File, RawRowEqualityComparer.Instance); public readonly MDTable<RawExportedTypeRow> ExportedTypeTable = new MDTable<RawExportedTypeRow>(Table.ExportedType, RawRowEqualityComparer.Instance); public readonly MDTable<RawManifestResourceRow> ManifestResourceTable = new MDTable<RawManifestResourceRow>(Table.ManifestResource, RawRowEqualityComparer.Instance); public readonly MDTable<RawNestedClassRow> NestedClassTable = new MDTable<RawNestedClassRow>(Table.NestedClass, RawRowEqualityComparer.Instance); public readonly MDTable<RawGenericParamRow> GenericParamTable = new MDTable<RawGenericParamRow>(Table.GenericParam, RawRowEqualityComparer.Instance); public readonly MDTable<RawMethodSpecRow> MethodSpecTable = new MDTable<RawMethodSpecRow>(Table.MethodSpec, RawRowEqualityComparer.Instance); public readonly MDTable<RawGenericParamConstraintRow> GenericParamConstraintTable = new MDTable<RawGenericParamConstraintRow>(Table.GenericParamConstraint, RawRowEqualityComparer.Instance); #pragma warning restore /// <summary> /// All tables /// </summary> public readonly IMDTable[] Tables; /// <inheritdoc/> public string Name { get { return IsENC ? "#-" : "#~"; } } /// <inheritdoc/> public bool IsEmpty { get { return false; } } /// <summary> /// <c>true</c> if the Edit 'N Continue name will be used (#-) /// </summary> public bool IsENC { get { if (options.UseENC.HasValue) return options.UseENC.Value; return hasDeletedRows || !FieldPtrTable.IsEmpty || !MethodPtrTable.IsEmpty || !ParamPtrTable.IsEmpty || !EventPtrTable.IsEmpty || !PropertyPtrTable.IsEmpty || !(InterfaceImplTable.IsEmpty || InterfaceImplTable.IsSorted) || !(ConstantTable.IsEmpty || ConstantTable.IsSorted) || !(CustomAttributeTable.IsEmpty || CustomAttributeTable.IsSorted) || !(FieldMarshalTable.IsEmpty || FieldMarshalTable.IsSorted) || !(DeclSecurityTable.IsEmpty || DeclSecurityTable.IsSorted) || !(ClassLayoutTable.IsEmpty || ClassLayoutTable.IsSorted) || !(FieldLayoutTable.IsEmpty || FieldLayoutTable.IsSorted) || !(EventMapTable.IsEmpty || EventMapTable.IsSorted) || !(PropertyMapTable.IsEmpty || PropertyMapTable.IsSorted) || !(MethodSemanticsTable.IsEmpty || MethodSemanticsTable.IsSorted) || !(MethodImplTable.IsEmpty || MethodImplTable.IsSorted) || !(ImplMapTable.IsEmpty || ImplMapTable.IsSorted) || !(FieldRVATable.IsEmpty || FieldRVATable.IsSorted) || !(NestedClassTable.IsEmpty || NestedClassTable.IsSorted) || !(GenericParamTable.IsEmpty || GenericParamTable.IsSorted) || !(GenericParamConstraintTable.IsEmpty || GenericParamConstraintTable.IsSorted); } } /// <summary> /// <c>true</c> if any rows have been deleted (eg. a deleted TypeDef, Method, Field, etc. /// Its name has been renamed to _Deleted). /// </summary> public bool HasDeletedRows { get { return hasDeletedRows; } set { hasDeletedRows = value; } } /// <summary> /// <c>true</c> if #Strings heap size > <c>0xFFFF</c> /// </summary> public bool BigStrings { get { return bigStrings; } set { bigStrings = value; } } /// <summary> /// <c>true</c> if #GUID heap size > <c>0xFFFF</c> /// </summary> public bool BigGuid { get { return bigGuid; } set { bigGuid = value; } } /// <summary> /// <c>true</c> if #Blob heap size > <c>0xFFFF</c> /// </summary> public bool BigBlob { get { return bigBlob; } set { bigBlob = value; } } /// <summary> /// Default constructor /// </summary> public TablesHeap() : this(null) { } /// <summary> /// Constructor /// </summary> /// <param name="options">Options</param> public TablesHeap(TablesHeapOptions options) { this.options = options ?? new TablesHeapOptions(); this.hasDeletedRows = this.options.HasDeletedRows ?? false; this.Tables = new IMDTable[] { ModuleTable, TypeRefTable, TypeDefTable, FieldPtrTable, FieldTable, MethodPtrTable, MethodTable, ParamPtrTable, ParamTable, InterfaceImplTable, MemberRefTable, ConstantTable, CustomAttributeTable, FieldMarshalTable, DeclSecurityTable, ClassLayoutTable, FieldLayoutTable, StandAloneSigTable, EventMapTable, EventPtrTable, EventTable, PropertyMapTable, PropertyPtrTable, PropertyTable, MethodSemanticsTable, MethodImplTable, ModuleRefTable, TypeSpecTable, ImplMapTable, FieldRVATable, ENCLogTable, ENCMapTable, AssemblyTable, AssemblyProcessorTable, AssemblyOSTable, AssemblyRefTable, AssemblyRefProcessorTable, AssemblyRefOSTable, FileTable, ExportedTypeTable, ManifestResourceTable, NestedClassTable, GenericParamTable, MethodSpecTable, GenericParamConstraintTable, }; } /// <inheritdoc/> public void SetReadOnly() { foreach (var mdt in Tables) mdt.SetReadOnly(); } /// <inheritdoc/> public void SetOffset(FileOffset offset, RVA rva) { this.offset = offset; this.rva = rva; } /// <inheritdoc/> public uint GetFileLength() { if (length == 0) CalculateLength(); return Utils.AlignUp(length, HeapBase.ALIGNMENT); } /// <inheritdoc/> public uint GetVirtualSize() { return GetFileLength(); } /// <summary> /// Calculates the length. This will set all MD tables to read-only. /// </summary> public void CalculateLength() { if (length != 0) return; SetReadOnly(); majorVersion = options.MajorVersion ?? 2; minorVersion = options.MinorVersion ?? 0; if (((majorVersion << 8) | minorVersion) <= 0x100) { if (!GenericParamTable.IsEmpty || !MethodSpecTable.IsEmpty || !GenericParamConstraintTable.IsEmpty) throw new ModuleWriterException("Tables heap version <= v1.0 but generic tables are not empty"); } var dnTableSizes = new DotNetTableSizes(); var tableInfos = dnTableSizes.CreateTables(majorVersion, minorVersion); dnTableSizes.InitializeSizes(bigStrings, bigGuid, bigBlob, GetRowCounts()); for (int i = 0; i < Tables.Length; i++) Tables[i].TableInfo = tableInfos[i]; length = 24; foreach (var mdt in Tables) { if (mdt.IsEmpty) continue; length += (uint)(4 + mdt.TableInfo.RowSize * mdt.Rows); } if (options.ExtraData.HasValue) length += 4; } uint[] GetRowCounts() { var sizes = new uint[Tables.Length]; for (int i = 0; i < sizes.Length; i++) sizes[i] = (uint)Tables[i].Rows; return sizes; } /// <inheritdoc/> public void WriteTo(BinaryWriter writer) { writer.Write(options.Reserved1 ?? 0); writer.Write(majorVersion); writer.Write(minorVersion); writer.Write((byte)GetMDStreamFlags()); writer.Write(GetLog2Rid()); writer.Write(GetValidMask()); writer.Write(GetSortedMask()); foreach (var mdt in Tables) { if (!mdt.IsEmpty) writer.Write(mdt.Rows); } if (options.ExtraData.HasValue) writer.Write(options.ExtraData.Value); writer.Write(ModuleTable); writer.Write(TypeRefTable); writer.Write(TypeDefTable); writer.Write(FieldPtrTable); writer.Write(FieldTable); writer.Write(MethodPtrTable); writer.Write(MethodTable); writer.Write(ParamPtrTable); writer.Write(ParamTable); writer.Write(InterfaceImplTable); writer.Write(MemberRefTable); writer.Write(ConstantTable); writer.Write(CustomAttributeTable); writer.Write(FieldMarshalTable); writer.Write(DeclSecurityTable); writer.Write(ClassLayoutTable); writer.Write(FieldLayoutTable); writer.Write(StandAloneSigTable); writer.Write(EventMapTable); writer.Write(EventPtrTable); writer.Write(EventTable); writer.Write(PropertyMapTable); writer.Write(PropertyPtrTable); writer.Write(PropertyTable); writer.Write(MethodSemanticsTable); writer.Write(MethodImplTable); writer.Write(ModuleRefTable); writer.Write(TypeSpecTable); writer.Write(ImplMapTable); writer.Write(FieldRVATable); writer.Write(ENCLogTable); writer.Write(ENCMapTable); writer.Write(AssemblyTable); writer.Write(AssemblyProcessorTable); writer.Write(AssemblyOSTable); writer.Write(AssemblyRefTable); writer.Write(AssemblyRefProcessorTable); writer.Write(AssemblyRefOSTable); writer.Write(FileTable); writer.Write(ExportedTypeTable); writer.Write(ManifestResourceTable); writer.Write(NestedClassTable); writer.Write(GenericParamTable); writer.Write(MethodSpecTable); writer.Write(GenericParamConstraintTable); writer.WriteZeros((int)(Utils.AlignUp(length, HeapBase.ALIGNMENT) - length)); } MDStreamFlags GetMDStreamFlags() { MDStreamFlags flags = 0; if (bigStrings) flags |= MDStreamFlags.BigStrings; if (bigGuid) flags |= MDStreamFlags.BigGUID; if (bigBlob) flags |= MDStreamFlags.BigBlob; if (options.ExtraData.HasValue) flags |= MDStreamFlags.ExtraData; if (hasDeletedRows) flags |= MDStreamFlags.HasDelete; return flags; } byte GetLog2Rid() { //TODO: Sometimes this is 16. Probably when at least one of the table indexes requires 4 bytes. return 1; } ulong GetValidMask() { ulong mask = 0; foreach (var mdt in Tables) { if (!mdt.IsEmpty) mask |= 1UL << (int)mdt.Table; } return mask; } ulong GetSortedMask() { ulong mask = 0; foreach (var mdt in Tables) { if (mdt.IsSorted) mask |= 1UL << (int)mdt.Table; } return mask; } /// <inheritdoc/> public override string ToString() { return Name; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections; using System.Collections.Specialized; using System.Web; using fyiReporting.RDL; namespace fyiReporting.RdlDesktop { class ConnectionThread { private string _WorkingDir; // subdirectory name under server root to place generated reports string serverRoot; // directory we start with public TcpListener myListener; private RdlDesktop _server; // Some statics used for statistics private static int connections = 0; private static int peakConnections = 0; private static int requests = 0; private static double totalts = 0; public ConnectionThread(RdlDesktop rs, TcpListener l, string sr, string wd) { _server = rs; serverRoot = sr; _WorkingDir = wd; myListener = l; } private void AccumTimeSpan(TimeSpan ts) { totalts += ts.TotalSeconds; return; } static public void ClearStatistics() { // Clear out the statistics; not connections, though!!! peakConnections=0; requests=0; totalts=0; return; } static public double GetTotalRequestTime() { return totalts; } static public int GetConnectionCount() { return connections; } static public int GetPeakConnectionCount() { return peakConnections; } static public int GetRequestCount() { return requests; } public string WorkingDir { get { return _WorkingDir; } } // Build an HTML page for directories public string ProcessDirectory(string directory) { StringWriter sw = new StringWriter(); DirectoryInfo di; FileSystemInfo[] afsi; // Check to see of there is an index.html or index.rdl file StreamReader sr=null; string result=null; try { string filename = serverRoot + directory + "index.html"; FileInfo fi = new FileInfo(filename); if (fi.Exists) { sr = new StreamReader(filename); result = sr.ReadToEnd(); sr.Close(); sr = null; } else { filename = serverRoot + directory + "index.rdl"; fi = new FileInfo(filename); if (fi.Exists) { string mimeType; byte[] ba = ProcessReportFile(directory + "index.rdl", filename, null, fi.LastWriteTime, out mimeType); result = Encoding.ASCII.GetString(ba); } } } catch { // clean up a little if (sr != null) sr.Close(); } if (result != null) return result; try { di = new DirectoryInfo(serverRoot + directory); afsi = di.GetFileSystemInfos(); } catch { sw.WriteLine("<html><Body>Illegal File or directory.</body></html>"); return sw.ToString(); } sw.WriteLine("<html>" + "<style type='text/css'>" + "a:link img {border-style:none;}" + "</style>" + "<title>Directory of " + directory + "</title><body><h3>Reports in " + directory + "</h3><table>"); foreach (FileSystemInfo fsi in afsi) { if (fsi.Name == WorkingDir) // never show the working directory continue; if ((fsi.Attributes & FileAttributes.Directory) == 0 && fsi.Extension.ToLower() != ".rdl") // only show report files continue; string name = directory.Replace(" ", "%20"); if (directory[directory.Length-1] != '/') name += "/"; name += fsi.Name.Replace(" ", "%20"); if ((fsi.Attributes & FileAttributes.Directory) == 0) // handle files { sw.WriteLine("<tr><td>{0}</td>"+ "<td><a href=\"{1}?rs:Format=HTML\">HTML</a></td>"+ "<td><a href=\"{1}?rs:Format=PDF\">PDF</a></td>"+ "<td><a href=\"{1}?rs:Format=XML\">XML</a></td></tr>", Path.GetFileNameWithoutExtension(fsi.Name), name); } else // handle directories sw.WriteLine("<tr><td><a href=\"{1}\">{0}<a></td><td></td><td></td></tr>", fsi.Name, name); } sw.WriteLine("</table></body></html>"); return sw.ToString(); } // Handle the processing of a report private byte[] ProcessReportFile(string url, string file, string parms, DateTime lastUpdateTime, out string mimeType) { byte[] result=null; string source; mimeType = "text/html"; // set the default // try finding report in the server cache! IList il = _server.Cache.Find(url + (parms==null?"":parms), lastUpdateTime); if (il != null) { try { string cfile = (string) il[il.Count-1]; result = _server.ReadCache.Read(cfile); mimeType = GetMimeType(cfile); // set mimetype based on file's extension } catch (Exception ex) { if (_server.TraceLevel >= 0) Console.WriteLine("Cache read exception in ProcessReportFile: {0} {1}", il[0], ex.Message); } return result; } // Obtain the source if (!ProcessReportGetSource(file, out source)) { return Encoding.ASCII.GetBytes(source); // we got an error opening file; source contains html error text } // Compile the report string msgs=""; Report report = ProcessReportCompile(file, source, out msgs); if (report == null) { mimeType = "text/html"; // force to html return Encoding.ASCII.GetBytes(String.Format("<H2>Report '{0}' has the following syntax errors.</H2><p>{1}", url, msgs)); } // Obtain the result HTML from running the report string dbgFilename=""; try { ListDictionary ld = ProcessReportGetParms(parms); // split parms into dictionary OutputPresentationType type; string stype = (string) ld["rs:Format"]; if (stype == null) stype = "html"; else stype = stype.ToLower(); switch (stype) { case "pdf": type = OutputPresentationType.PDF; break; case "xml": type = OutputPresentationType.XML; string ext = (string) ld["rs:FileExtension"]; if (ext != null) stype = ext; break; case "html": type = OutputPresentationType.HTML; break; default: type = OutputPresentationType.HTML; stype = "html"; break; } StreamGen sg = new StreamGen(serverRoot, WorkingDir, stype); ProcessReport pr = new ProcessReport(report, sg); pr.Run(ld, type); // handle any error messages if (report.ErrorMaxSeverity > 0) { string errs=null; if (report.ErrorMaxSeverity > 4) { mimeType = "text/html"; // force to html errs = "<H2>Severe errors encountered when running report.</H2>"; } foreach (String emsg in report.ErrorItems) { if (report.ErrorMaxSeverity > 4) errs += ("<p>" + emsg + "</p>"); else { if (_server.TraceLevel > 0) Console.WriteLine(emsg); // output message to console } } if (errs != null) result = Encoding.ASCII.GetBytes(errs); report.ErrorReset(); } // Only read the result if significant errors didn't occur if (result == null) { ReportRender rr = new ReportRender(report); rr.ActionUrl = "/" + url; string p = rr.ParameterHtml(ld); // put this into a file. string parmUrl; StreamWriter sw=null; try { sw = new StreamWriter(sg.GetIOStream(out parmUrl, "html")); sw.Write(p); } finally { if (sw != null) sw.Close(); } // Add it to the file list IList newlist = _server.Cache.Add(url + (parms==null?"":parms), sg.FileList); dbgFilename = (string) newlist[0]; // this is the first fully qualified name FileInfo fi = new FileInfo(dbgFilename); string mHtml = rr.MainHtml(report, parmUrl, sg.RelativeDirectory+fi.Name); string mUrl; sw=null; try { sw = new StreamWriter(sg.GetIOStream(out mUrl, "html")); sw.Write(mHtml); } finally { if (sw != null) sw.Close(); } result = Encoding.ASCII.GetBytes(mHtml); } } catch (Exception ex) { if (_server.TraceLevel >= 0) Console.WriteLine("Exception in ProcessReportFile: {0} {1}", file, ex.Message); result = Encoding.ASCII.GetBytes(string.Format("<H2>{0}</H2><p>{1}</p>", ex.Message, ex.StackTrace)); mimeType = "text/html"; // force to html } return result; } private ListDictionary ProcessReportGetParms(string parms) { ListDictionary ld= new ListDictionary(); if (parms == null) return ld; // dictionary will be empty in this case // parms are separated by & char[] breakChars = new char[] {'&'}; string[] ps = parms.Split(breakChars); foreach (string p in ps) { int iEq = p.IndexOf("="); if (iEq > 0) { string name = p.Substring(0, iEq); string val = p.Substring(iEq+1); ld.Add(HttpUtility.UrlDecode(name), HttpUtility.UrlDecode(val)); } } return ld; } private bool ProcessReportGetSource(string file, out string source) { StreamReader fs=null; string prog=null; try { fs = new StreamReader(file); prog = fs.ReadToEnd(); } catch (Exception ae) { source = string.Format("<H2>{0}</H2>", ae.Message); return false; } finally { if (fs != null) fs.Close(); } source = prog; return true; } private Report ProcessReportCompile(string file, string prog, out string msgs) { // Now parse the file RDLParser rdlp; Report r; msgs = ""; try { rdlp = new RDLParser(prog); rdlp.Folder = Path.GetDirectoryName(file); rdlp.DataSourceReferencePassword = new NeedPassword(this.GetPassword); r = rdlp.Parse(); if (r.ErrorMaxSeverity > 0) { // have errors fill out the msgs foreach (String emsg in r.ErrorItems) { if (_server.TraceLevel > 0) Console.WriteLine(emsg); // output message to console msgs += (emsg + "<p>"); } int severity = r.ErrorMaxSeverity; r.ErrorReset(); if (severity > 4) r = null; // don't return when severe errors } // If we've loaded the report; we should tell it where it got loaded from if (r != null) { r.Folder = Path.GetDirectoryName(file); r.Name = Path.GetFileNameWithoutExtension(file); r.GetDataSourceReferencePassword = new RDL.NeedPassword(GetPassword); } } catch (Exception ex) { msgs = string.Format("<H2>{0}</H2>", ex.Message); r = null; } return r; } private string GetPassword() { return _server.DataSourceReferencePassword; } /// <summary> /// This function takes a File Name as Input and returns the mime type. /// </summary> /// <param name="sRequestedFile">To indentify the Mime Type</param> /// <returns>Mime Type</returns> private string GetMimeType(string file) { String mimeType; String fileExt; int startPos = file.IndexOf(".") + 1; fileExt = file.Substring(startPos).ToLower(); mimeType = (string) ( this._server.Mimes[fileExt]); return mimeType; } /// <summary> /// This function send the Header Information to the client (Browser) /// </summary> /// <param name="sHttpVersion">HTTP Version</param> /// <param name="sMIMEHeader">Mime Type</param> /// <param name="iTotBytes">Total Bytes to be sent in the body</param> /// <param name="mySocket">Socket reference</param> /// <returns></returns> public void SendHeader(string sHttpVersion, string sMIMEHeader, int iTotBytes, string sStatusCode, string modifiedTime, ref Socket mySocket) { StringBuilder buffer = new StringBuilder(); // if Mime type is not provided set default to text/html if (sMIMEHeader == null || sMIMEHeader.Length == 0 ) { sMIMEHeader = "text/html"; // Default Mime Type is text/html } buffer.Append(sHttpVersion); buffer.Append(sStatusCode); buffer.Append("\r\n"); buffer.Append("Server: RdlDesktop\r\n"); buffer.Append("Cache-Control: must-revalidate\r\n"); buffer.AppendFormat("Content-Type: {0}\r\n", sMIMEHeader); if (modifiedTime != null) buffer.AppendFormat("Last-Modifed: {0}\r\n", modifiedTime); buffer.Append("Accept-Ranges: bytes\r\n"); buffer.AppendFormat("Content-Length: {0}\r\n\r\n", iTotBytes); Byte[] data = Encoding.ASCII.GetBytes(buffer.ToString()); SendToBrowser( data, ref mySocket); } /// <summary> /// Overloaded Function, takes string, convert to bytes and calls /// overloaded sendToBrowserFunction. /// </summary> /// <param name="sData">The data to be sent to the browser(client)</param> /// <param name="mySocket">Socket reference</param> public void SendToBrowser(String sData, ref Socket mySocket) { SendToBrowser (Encoding.ASCII.GetBytes(sData), ref mySocket); } /// <summary> /// Sends data to the browser (client) /// </summary> /// <param name="bSendData">Byte Array</param> /// <param name="mySocket">Socket reference</param> public void SendToBrowser(Byte[] bSendData, ref Socket mySocket) { int numBytes = 0; try { if (mySocket.Connected) { if (( numBytes = mySocket.Send(bSendData, bSendData.Length,0)) == -1) { if (_server.TraceLevel >= 0) Console.WriteLine("Socket Error cannot Send Packet"); } } else { if (_server.TraceLevel >= 4) Console.WriteLine("Connection Dropped...."); } } catch (Exception e) { if (_server.TraceLevel >= 0) Console.WriteLine("Error Occurred : {0} ", e ); } } //This method Accepts new connection public void HandleConnection(object state) { DateTime sDateTime; // start date time int iStartPos = 0; string sRequest; string sDirName; string sRequestedFile; string sErrorMessage; string sPhysicalFilePath = ""; string sParameters=null; //Accept a new connection Socket mySocket = myListener.AcceptSocket() ; if(!mySocket.Connected) return; sDateTime = DateTime.Now; connections++; // current number of connections requests++; // total requests made if (connections > peakConnections) peakConnections = connections; // peak connections if (_server.TraceLevel >= 4) { Console.WriteLine("\nClient connected IP={0} -- {1} active connection{2}", mySocket.RemoteEndPoint, connections, connections > 1? "s": "") ; } //make a byte array and receive data from the client Byte[] data = new Byte[1024] ; try { int i = mySocket.Receive(data,data.Length,0) ; } catch (Exception e) { connections--; mySocket.Close(); if (_server.TraceLevel >= 0) Console.WriteLine("Error Occurred : {0} ", e ); this.AccumTimeSpan(DateTime.Now - sDateTime); return; } //Convert Byte to String string sBuffer = Encoding.ASCII.GetString(data); //At present we will only deal with GET type if (sBuffer.Substring(0,3) != "GET" ) { string req = sBuffer.Substring(0,30); if (_server.TraceLevel >= 0) Console.WriteLine("{0} not supported. Only Get Method is supported.", req); mySocket.Close(); connections--; this.AccumTimeSpan(DateTime.Now - sDateTime); return; } // Look for HTTP request iStartPos = sBuffer.IndexOf("HTTP",1); // Get the HTTP text and version e.g. it will return "HTTP/1.1" string sHttpVersion = sBuffer.Substring(iStartPos,8); // Extract the Requested Type and Requested file/directory sRequest = sBuffer.Substring(0,iStartPos - 1); if (_server.TraceLevel >= 4) Console.WriteLine("Request=" + UnescapeRequest(sRequest)); int iStartParm = sRequest.IndexOf("?"); if (iStartParm >= 0) { sParameters = sRequest.Substring(iStartParm+1); sRequest = sRequest.Substring(0, iStartParm); } sRequest = UnescapeRequest(sRequest); // can't do this to parameters until they've been separated //If file name is not supplied add forward slash to indicate //that it is a directory and then we will look for the //default file name.. if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/"))) { sRequest = sRequest + "/"; } //Extract the requested file name iStartPos = sRequest.LastIndexOf("/") + 1; sRequestedFile = sRequest.Substring(iStartPos); //Extract The directory Name sDirName = sRequest.Substring(sRequest.IndexOf("/"), sRequest.LastIndexOf("/")-3); if ( sDirName == "") sDirName = "/"; // When directory output the index if (sRequestedFile.Length == 0 ) { string directoryHTML; directoryHTML = ProcessDirectory(sDirName); SendHeader(sHttpVersion, "text/html", directoryHTML.Length, " 200 OK", null, ref mySocket); SendToBrowser(directoryHTML, ref mySocket); mySocket.Close(); connections--; this.AccumTimeSpan(DateTime.Now - sDateTime); return; } // Handle files String mimeType = GetMimeType(sRequestedFile); // get mime type //Build the physical path sPhysicalFilePath = serverRoot + sDirName + sRequestedFile; bool bFail= mimeType == null? true: false; // mime type can be null if extension isn't in config.xml FileInfo fi=null; if (!bFail) { try { fi = new FileInfo(sPhysicalFilePath); if (fi == null || fi.Exists == false) bFail = true; } catch { bFail = true; } } if (bFail) { sErrorMessage = "<H2>404 File Not Found</H2>"; SendHeader(sHttpVersion, "text/html", sErrorMessage.Length, " 404 Not Found", null, ref mySocket); SendToBrowser( sErrorMessage, ref mySocket); mySocket.Close(); connections--; this.AccumTimeSpan(DateTime.Now - sDateTime); return; } string fileTime = string.Format("{0:r}", fi.LastWriteTime); // Handle the primary file type of this server if (mimeType == "application/rdl") { // Get the url of the request int uStart = sRequest.IndexOf("/"); // "Get /" precedes the url name string url; if (uStart >= 0) url = sRequest.Substring(uStart+1); else url = sRequest; string mtype; byte[] ba = ProcessReportFile(url, sPhysicalFilePath, sParameters, fi.LastWriteTime, out mtype); SendHeader(sHttpVersion, mtype, ba.Length, " 200 OK", fileTime, ref mySocket); SendToBrowser(ba, ref mySocket); mySocket.Close(); connections--; this.AccumTimeSpan(DateTime.Now - sDateTime); return; } // Handle any other kind of file try { byte[] bytes = _server.ReadCache.Read(sPhysicalFilePath); SendHeader(sHttpVersion, mimeType, bytes.Length, " 200 OK", fileTime, ref mySocket); SendToBrowser(bytes, ref mySocket); } catch (Exception ex) { sErrorMessage = string.Format("<H2>{0}</H2><p>{1}</p>", ex.Message, ex.StackTrace); SendHeader(sHttpVersion, "text/html", sErrorMessage.Length, " 200 OK", null, ref mySocket); SendToBrowser( sErrorMessage, ref mySocket); } mySocket.Close(); connections--; this.AccumTimeSpan(DateTime.Now - sDateTime); return; } string UnescapeRequest(string req) { req = req.Replace("\\","/"); //Replace backslash with Forward Slash, if Any return HttpUtility.UrlDecode(req); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MetadataApiServer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using MS.Utility; using System; using System.ComponentModel; // InvalidEnumArgumentException using System.Windows.Data; // UpdateSourceTrigger namespace System.Windows { /// <summary> /// </summary> [Flags] public enum FrameworkPropertyMetadataOptions: int { /// <summary>No flags</summary> None = 0x000, /// <summary>This property affects measurement</summary> AffectsMeasure = 0x001, /// <summary>This property affects arragement</summary> AffectsArrange = 0x002, /// <summary>This property affects parent's measurement</summary> AffectsParentMeasure = 0x004, /// <summary>This property affects parent's arrangement</summary> AffectsParentArrange = 0x008, /// <summary>This property affects rendering</summary> AffectsRender = 0x010, /// <summary>This property inherits to children</summary> Inherits = 0x020, /// <summary> /// This property causes inheritance and resource lookup to override values /// of InheritanceBehavior that may be set on any FE in the path of lookup /// </summary> OverridesInheritanceBehavior = 0x040, /// <summary>This property does not support data binding</summary> NotDataBindable = 0x080, /// <summary>Data bindings on this property default to two-way</summary> BindsTwoWayByDefault = 0x100, /// <summary>This property should be saved/restored when journaling/navigating by URI</summary> Journal = 0x400, /// <summary> /// This property's subproperties do not affect rendering. /// For instance, a property X may have a subproperty Y. /// Changing X.Y does not require rendering to be updated. /// </summary> SubPropertiesDoNotAffectRender = 0x800, } /// <summary> /// Metadata for supported Framework features /// </summary> public class FrameworkPropertyMetadata : UIPropertyMetadata { /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata() : base() { Initialize(); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue) : base(defaultValue) { Initialize(); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="propertyChangedCallback">Called when the property has been changed</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(PropertyChangedCallback propertyChangedCallback) : base(propertyChangedCallback) { Initialize(); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="propertyChangedCallback">Called when the property has been changed</param> /// <param name="coerceValueCallback">Called on update of value</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) : base(propertyChangedCallback) { Initialize(); CoerceValueCallback = coerceValueCallback; } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, PropertyChangedCallback propertyChangedCallback) : base(defaultValue, propertyChangedCallback) { Initialize(); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> /// <param name="coerceValueCallback">Called on update of value</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) : base(defaultValue, propertyChangedCallback, coerceValueCallback) { Initialize(); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="flags">Metadata option flags</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, FrameworkPropertyMetadataOptions flags) : base(defaultValue) { TranslateFlags(flags); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="flags">Metadata option flags</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback) : base(defaultValue, propertyChangedCallback) { TranslateFlags(flags); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="flags">Metadata option flags</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> /// <param name="coerceValueCallback">Called on update of value</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback) : base(defaultValue, propertyChangedCallback, coerceValueCallback) { TranslateFlags(flags); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="flags">Metadata option flags</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> /// <param name="coerceValueCallback">Called on update of value</param> /// <param name="isAnimationProhibited">Should animation of this property be prohibited?</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback, bool isAnimationProhibited) : base(defaultValue, propertyChangedCallback, coerceValueCallback, isAnimationProhibited) { TranslateFlags(flags); } /// <summary> /// Framework type metadata construction. Marked as no inline to reduce code size. /// </summary> /// <param name="defaultValue">Default value of property</param> /// <param name="flags">Metadata option flags</param> /// <param name="propertyChangedCallback">Called when the property has been changed</param> /// <param name="coerceValueCallback">Called on update of value</param> /// <param name="isAnimationProhibited">Should animation of this property be prohibited?</param> /// <param name="defaultUpdateSourceTrigger">The UpdateSourceTrigger to use for bindings that have UpdateSourceTriger=Default.</param> [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public FrameworkPropertyMetadata(object defaultValue, FrameworkPropertyMetadataOptions flags, PropertyChangedCallback propertyChangedCallback, CoerceValueCallback coerceValueCallback, bool isAnimationProhibited, UpdateSourceTrigger defaultUpdateSourceTrigger) : base(defaultValue, propertyChangedCallback, coerceValueCallback, isAnimationProhibited) { if (!BindingOperations.IsValidUpdateSourceTrigger(defaultUpdateSourceTrigger)) throw new InvalidEnumArgumentException("defaultUpdateSourceTrigger", (int) defaultUpdateSourceTrigger, typeof(UpdateSourceTrigger)); if (defaultUpdateSourceTrigger == UpdateSourceTrigger.Default) throw new ArgumentException(SR.Get(SRID.NoDefaultUpdateSourceTrigger), "defaultUpdateSourceTrigger"); TranslateFlags(flags); DefaultUpdateSourceTrigger = defaultUpdateSourceTrigger; } private void Initialize() { // FW_DefaultUpdateSourceTriggerEnumBit1 = 0x40000000, // FW_DefaultUpdateSourceTriggerEnumBit2 = 0x80000000, _flags = (MetadataFlags)(((uint)_flags & 0x3FFFFFFF) | ((uint) UpdateSourceTrigger.PropertyChanged) << 30); } private static bool IsFlagSet(FrameworkPropertyMetadataOptions flag, FrameworkPropertyMetadataOptions flags) { return (flags & flag) != 0; } private void TranslateFlags(FrameworkPropertyMetadataOptions flags) { Initialize(); // Convert flags to state sets. If a flag is set, then, // the value is set on the respective property. Otherwise, // the state remains unset // This means that state is cumulative across base classes // on a merge where appropriate if (IsFlagSet(FrameworkPropertyMetadataOptions.AffectsMeasure, flags)) { AffectsMeasure = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.AffectsArrange, flags)) { AffectsArrange = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.AffectsParentMeasure, flags)) { AffectsParentMeasure = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.AffectsParentArrange, flags)) { AffectsParentArrange = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.AffectsRender, flags)) { AffectsRender = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.Inherits, flags)) { IsInherited = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.OverridesInheritanceBehavior, flags)) { OverridesInheritanceBehavior = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.NotDataBindable, flags)) { IsNotDataBindable = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, flags)) { BindsTwoWayByDefault = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.Journal, flags)) { Journal = true; } if (IsFlagSet(FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender, flags)) { SubPropertiesDoNotAffectRender = true; } } /// <summary> /// Property affects measurement /// </summary> public bool AffectsMeasure { get { return ReadFlag(MetadataFlags.FW_AffectsMeasureID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_AffectsMeasureID, value); } } /// <summary> /// Property affects arragement /// </summary> public bool AffectsArrange { get { return ReadFlag(MetadataFlags.FW_AffectsArrangeID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_AffectsArrangeID, value); } } /// <summary> /// Property affects parent's measurement /// </summary> public bool AffectsParentMeasure { get { return ReadFlag(MetadataFlags.FW_AffectsParentMeasureID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_AffectsParentMeasureID, value); } } /// <summary> /// Property affects parent's arrangement /// </summary> public bool AffectsParentArrange { get { return ReadFlag(MetadataFlags.FW_AffectsParentArrangeID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_AffectsParentArrangeID, value); } } /// <summary> /// Property affects rendering /// </summary> public bool AffectsRender { get { return ReadFlag(MetadataFlags.FW_AffectsRenderID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_AffectsRenderID, value); } } /// <summary> /// Property is inheritable /// </summary> public bool Inherits { get { return IsInherited; } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } IsInherited = value; SetModified(MetadataFlags.FW_InheritsModifiedID); } } /// <summary> /// Property evaluation must span separated trees /// </summary> public bool OverridesInheritanceBehavior { get { return ReadFlag(MetadataFlags.FW_OverridesInheritanceBehaviorID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_OverridesInheritanceBehaviorID, value); SetModified(MetadataFlags.FW_OverridesInheritanceBehaviorModifiedID); } } /// <summary> /// Property cannot be data-bound /// </summary> public bool IsNotDataBindable { get { return ReadFlag(MetadataFlags.FW_IsNotDataBindableID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_IsNotDataBindableID, value); } } /// <summary> /// Data bindings on this property default to two-way /// </summary> public bool BindsTwoWayByDefault { get { return ReadFlag(MetadataFlags.FW_BindsTwoWayByDefaultID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_BindsTwoWayByDefaultID, value); } } /// <summary> /// The default UpdateSourceTrigger for two-way data bindings on this property. /// </summary> public UpdateSourceTrigger DefaultUpdateSourceTrigger { // FW_DefaultUpdateSourceTriggerEnumBit1 = 0x40000000, // FW_DefaultUpdateSourceTriggerEnumBit2 = 0x80000000, get { return (UpdateSourceTrigger) (((uint) _flags >> 30) & 0x3); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } if (!BindingOperations.IsValidUpdateSourceTrigger(value)) throw new InvalidEnumArgumentException("value", (int) value, typeof(UpdateSourceTrigger)); if (value == UpdateSourceTrigger.Default) throw new ArgumentException(SR.Get(SRID.NoDefaultUpdateSourceTrigger), "value"); // FW_DefaultUpdateSourceTriggerEnumBit1 = 0x40000000, // FW_DefaultUpdateSourceTriggerEnumBit2 = 0x80000000, _flags = (MetadataFlags)(((uint) _flags & 0x3FFFFFFF) | ((uint) value) << 30); SetModified(MetadataFlags.FW_DefaultUpdateSourceTriggerModifiedID); } } /// <summary> /// The value of this property should be saved/restored when journaling by URI /// </summary> public bool Journal { get { return ReadFlag(MetadataFlags.FW_ShouldBeJournaledID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_ShouldBeJournaledID, value); SetModified(MetadataFlags.FW_ShouldBeJournaledModifiedID); } } /// <summary> /// This property's subproperties do not affect rendering. /// For instance, a property X may have a subproperty Y. /// Changing X.Y does not require rendering to be updated. /// </summary> public bool SubPropertiesDoNotAffectRender { get { return ReadFlag(MetadataFlags.FW_SubPropertiesDoNotAffectRenderID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_SubPropertiesDoNotAffectRenderID, value); SetModified(MetadataFlags.FW_SubPropertiesDoNotAffectRenderModifiedID); } } /// <summary> /// Does the represent the metadata for a ReadOnly property /// </summary> private bool ReadOnly { get { return ReadFlag(MetadataFlags.FW_ReadOnlyID); } set { if (IsSealed) { throw new InvalidOperationException(SR.Get(SRID.TypeMetadataCannotChangeAfterUse)); } WriteFlag(MetadataFlags.FW_ReadOnlyID, value); } } /// <summary> /// Creates a new instance of this property metadata. This method is used /// when metadata needs to be cloned. After CreateInstance is called the /// framework will call Merge to merge metadata into the new instance. /// Deriving classes must override this and return a new instance of /// themselves. /// </summary> internal override PropertyMetadata CreateInstance() { return new FrameworkPropertyMetadata(); } /// <summary> /// Merge set source state into this /// </summary> /// <remarks> /// Used when overriding metadata /// </remarks> /// <param name="baseMetadata">Base metadata to merge</param> /// <param name="dp">DependencyProperty that this metadata is being applied to</param> protected override void Merge(PropertyMetadata baseMetadata, DependencyProperty dp) { // Does parameter validation base.Merge(baseMetadata, dp); // Source type is guaranteed to be the same type or base type FrameworkPropertyMetadata fbaseMetadata = baseMetadata as FrameworkPropertyMetadata; if (fbaseMetadata != null) { // Merge source metadata into this // Modify metadata merge state fields directly (not through accessors // so that "modified" bits remain intact // Merge state // Defaults to false, derived classes can only enable WriteFlag(MetadataFlags.FW_AffectsMeasureID, ReadFlag(MetadataFlags.FW_AffectsMeasureID) | fbaseMetadata.AffectsMeasure); WriteFlag(MetadataFlags.FW_AffectsArrangeID, ReadFlag(MetadataFlags.FW_AffectsArrangeID) | fbaseMetadata.AffectsArrange); WriteFlag(MetadataFlags.FW_AffectsParentMeasureID, ReadFlag(MetadataFlags.FW_AffectsParentMeasureID) | fbaseMetadata.AffectsParentMeasure); WriteFlag(MetadataFlags.FW_AffectsParentArrangeID, ReadFlag(MetadataFlags.FW_AffectsParentArrangeID) | fbaseMetadata.AffectsParentArrange); WriteFlag(MetadataFlags.FW_AffectsRenderID, ReadFlag(MetadataFlags.FW_AffectsRenderID) | fbaseMetadata.AffectsRender); WriteFlag(MetadataFlags.FW_BindsTwoWayByDefaultID, ReadFlag(MetadataFlags.FW_BindsTwoWayByDefaultID) | fbaseMetadata.BindsTwoWayByDefault); WriteFlag(MetadataFlags.FW_IsNotDataBindableID, ReadFlag(MetadataFlags.FW_IsNotDataBindableID) | fbaseMetadata.IsNotDataBindable); // Override state if (!IsModified(MetadataFlags.FW_SubPropertiesDoNotAffectRenderModifiedID)) { WriteFlag(MetadataFlags.FW_SubPropertiesDoNotAffectRenderID, fbaseMetadata.SubPropertiesDoNotAffectRender); } if (!IsModified(MetadataFlags.FW_InheritsModifiedID)) { IsInherited = fbaseMetadata.Inherits; } if (!IsModified(MetadataFlags.FW_OverridesInheritanceBehaviorModifiedID)) { WriteFlag(MetadataFlags.FW_OverridesInheritanceBehaviorID, fbaseMetadata.OverridesInheritanceBehavior); } if (!IsModified(MetadataFlags.FW_ShouldBeJournaledModifiedID)) { WriteFlag(MetadataFlags.FW_ShouldBeJournaledID, fbaseMetadata.Journal); } if (!IsModified(MetadataFlags.FW_DefaultUpdateSourceTriggerModifiedID)) { // FW_DefaultUpdateSourceTriggerEnumBit1 = 0x40000000, // FW_DefaultUpdateSourceTriggerEnumBit2 = 0x80000000, _flags = (MetadataFlags)(((uint)_flags & 0x3FFFFFFF) | ((uint) fbaseMetadata.DefaultUpdateSourceTrigger) << 30); } } } /// <summary> /// Notification that this metadata has been applied to a property /// and the metadata is being sealed /// </summary> /// <remarks> /// Normally, any mutability of the data structure should be marked /// as immutable at this point /// </remarks> /// <param name="dp">DependencyProperty</param> /// <param name="targetType">Type associating metadata (null if default metadata)</param> protected override void OnApply(DependencyProperty dp, Type targetType) { // Remember if this is the metadata for a ReadOnly property ReadOnly = dp.ReadOnly; base.OnApply(dp, targetType); } /// <summary> /// Determines if data binding is supported /// </summary> /// <remarks> /// Data binding is not allowed if a property read-only, regardless /// of the value of the IsNotDataBindable flag /// </remarks> public bool IsDataBindingAllowed { get { return !ReadFlag(MetadataFlags.FW_IsNotDataBindableID) && !ReadOnly; } } internal void SetModified(MetadataFlags id) { WriteFlag(id, true); } internal bool IsModified(MetadataFlags id) { return ReadFlag(id); } } }
// 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.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal sealed class LogicalExpr : ValueQuery { private Operator.Op _op; private Query _opnd1; private Query _opnd2; public LogicalExpr(Operator.Op op, Query opnd1, Query opnd2) { Debug.Assert( Operator.Op.LT == op || Operator.Op.GT == op || Operator.Op.LE == op || Operator.Op.GE == op || Operator.Op.EQ == op || Operator.Op.NE == op ); _op = op; _opnd1 = opnd1; _opnd2 = opnd2; } private LogicalExpr(LogicalExpr other) : base(other) { _op = other._op; _opnd1 = Clone(other._opnd1); _opnd2 = Clone(other._opnd2); } public override void SetXsltContext(XsltContext context) { _opnd1.SetXsltContext(context); _opnd2.SetXsltContext(context); } public override object Evaluate(XPathNodeIterator nodeIterator) { Operator.Op op = _op; object val1 = _opnd1.Evaluate(nodeIterator); object val2 = _opnd2.Evaluate(nodeIterator); int type1 = (int)GetXPathType(val1); int type2 = (int)GetXPathType(val2); if (type1 < type2) { op = Operator.InvertOperator(op); object valTemp = val1; val1 = val2; val2 = valTemp; int typeTmp = type1; type1 = type2; type2 = typeTmp; } if (op == Operator.Op.EQ || op == Operator.Op.NE) { return s_CompXsltE[type1][type2](op, val1, val2); } else { return s_CompXsltO[type1][type2](op, val1, val2); } } private delegate bool cmpXslt(Operator.Op op, object val1, object val2); // Number, String, Boolean, NodeSet, Navigator private static readonly cmpXslt[][] s_CompXsltE = { new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null }, new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringE), null , null , null }, new cmpXslt[] { new cmpXslt(cmpBoolNumberE ), new cmpXslt(cmpBoolStringE ), new cmpXslt(cmpBoolBoolE ), null , null }, new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringE ), new cmpXslt(cmpQueryBoolE ), new cmpXslt(cmpQueryQueryE ), null }, new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringE ), new cmpXslt(cmpRtfBoolE ), new cmpXslt(cmpRtfQueryE ), new cmpXslt(cmpRtfRtfE) }, }; private static readonly cmpXslt[][] s_CompXsltO = { new cmpXslt[] { new cmpXslt(cmpNumberNumber), null , null , null , null }, new cmpXslt[] { new cmpXslt(cmpStringNumber), new cmpXslt(cmpStringStringO), null , null , null }, new cmpXslt[] { new cmpXslt(cmpBoolNumberO ), new cmpXslt(cmpBoolStringO ), new cmpXslt(cmpBoolBoolO ), null , null }, new cmpXslt[] { new cmpXslt(cmpQueryNumber ), new cmpXslt(cmpQueryStringO ), new cmpXslt(cmpQueryBoolO ), new cmpXslt(cmpQueryQueryO ), null }, new cmpXslt[] { new cmpXslt(cmpRtfNumber ), new cmpXslt(cmpRtfStringO ), new cmpXslt(cmpRtfBoolO ), new cmpXslt(cmpRtfQueryO ), new cmpXslt(cmpRtfRtfO) }, }; /*cmpXslt:*/ private static bool cmpQueryQueryE(Operator.Op op, object val1, object val2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE); bool isEQ = (op == Operator.Op.EQ); NodeSet n1 = new NodeSet(val1); NodeSet n2 = new NodeSet(val2); while (true) { if (!n1.MoveNext()) { return false; } if (!n2.MoveNext()) { return false; } string str1 = n1.Value; do { if ((str1 == n2.Value) == isEQ) { return true; } } while (n2.MoveNext()); n2.Reset(); } } /*cmpXslt:*/ private static bool cmpQueryQueryO(Operator.Op op, object val1, object val2) { Debug.Assert( op == Operator.Op.LT || op == Operator.Op.GT || op == Operator.Op.LE || op == Operator.Op.GE ); NodeSet n1 = new NodeSet(val1); NodeSet n2 = new NodeSet(val2); while (true) { if (!n1.MoveNext()) { return false; } if (!n2.MoveNext()) { return false; } double num1 = NumberFunctions.Number(n1.Value); do { if (cmpNumberNumber(op, num1, NumberFunctions.Number(n2.Value))) { return true; } } while (n2.MoveNext()); n2.Reset(); } } private static bool cmpQueryNumber(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double n2 = (double)val2; while (n1.MoveNext()) { if (cmpNumberNumber(op, NumberFunctions.Number(n1.Value), n2)) { return true; } } return false; } private static bool cmpQueryStringE(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); string n2 = (string)val2; while (n1.MoveNext()) { if (cmpStringStringE(op, n1.Value, n2)) { return true; } } return false; } private static bool cmpQueryStringO(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double n2 = NumberFunctions.Number((string)val2); while (n1.MoveNext()) { if (cmpNumberNumberO(op, NumberFunctions.Number(n1.Value), n2)) { return true; } } return false; } private static bool cmpRtfQueryE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); NodeSet n2 = new NodeSet(val2); while (n2.MoveNext()) { if (cmpStringStringE(op, n1, n2.Value)) { return true; } } return false; } private static bool cmpRtfQueryO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); NodeSet n2 = new NodeSet(val2); while (n2.MoveNext()) { if (cmpNumberNumberO(op, n1, NumberFunctions.Number(n2.Value))) { return true; } } return false; } private static bool cmpQueryBoolE(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); bool b1 = n1.MoveNext(); bool b2 = (bool)val2; return cmpBoolBoolE(op, b1, b2); } private static bool cmpQueryBoolO(Operator.Op op, object val1, object val2) { NodeSet n1 = new NodeSet(val1); double d1 = n1.MoveNext() ? 1.0 : 0; double d2 = NumberFunctions.Number((bool)val2); return cmpNumberNumberO(op, d1, d2); } private static bool cmpBoolBoolE(Operator.Op op, bool n1, bool n2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE, "Unexpected Operator.op code in cmpBoolBoolE()" ); return (op == Operator.Op.EQ) == (n1 == n2); } private static bool cmpBoolBoolE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = (bool)val2; return cmpBoolBoolE(op, n1, n2); } private static bool cmpBoolBoolO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((bool)val1); double n2 = NumberFunctions.Number((bool)val2); return cmpNumberNumberO(op, n1, n2); } private static bool cmpBoolNumberE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = BooleanFunctions.toBoolean((double)val2); return cmpBoolBoolE(op, n1, n2); } private static bool cmpBoolNumberO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((bool)val1); double n2 = (double)val2; return cmpNumberNumberO(op, n1, n2); } private static bool cmpBoolStringE(Operator.Op op, object val1, object val2) { bool n1 = (bool)val1; bool n2 = BooleanFunctions.toBoolean((string)val2); return cmpBoolBoolE(op, n1, n2); } private static bool cmpRtfBoolE(Operator.Op op, object val1, object val2) { bool n1 = BooleanFunctions.toBoolean(Rtf(val1)); bool n2 = (bool)val2; return cmpBoolBoolE(op, n1, n2); } private static bool cmpBoolStringO(Operator.Op op, object val1, object val2) { return cmpNumberNumberO(op, NumberFunctions.Number((bool)val1), NumberFunctions.Number((string)val2) ); } private static bool cmpRtfBoolO(Operator.Op op, object val1, object val2) { return cmpNumberNumberO(op, NumberFunctions.Number(Rtf(val1)), NumberFunctions.Number((bool)val2) ); } private static bool cmpNumberNumber(Operator.Op op, double n1, double n2) { switch (op) { case Operator.Op.LT: return (n1 < n2); case Operator.Op.GT: return (n1 > n2); case Operator.Op.LE: return (n1 <= n2); case Operator.Op.GE: return (n1 >= n2); case Operator.Op.EQ: return (n1 == n2); case Operator.Op.NE: return (n1 != n2); } Debug.Fail("Unexpected Operator.op code in cmpNumberNumber()"); return false; } private static bool cmpNumberNumberO(Operator.Op op, double n1, double n2) { switch (op) { case Operator.Op.LT: return (n1 < n2); case Operator.Op.GT: return (n1 > n2); case Operator.Op.LE: return (n1 <= n2); case Operator.Op.GE: return (n1 >= n2); } Debug.Fail("Unexpected Operator.op code in cmpNumberNumber()"); return false; } private static bool cmpNumberNumber(Operator.Op op, object val1, object val2) { double n1 = (double)val1; double n2 = (double)val2; return cmpNumberNumber(op, n1, n2); } private static bool cmpStringNumber(Operator.Op op, object val1, object val2) { double n2 = (double)val2; double n1 = NumberFunctions.Number((string)val1); return cmpNumberNumber(op, n1, n2); } private static bool cmpRtfNumber(Operator.Op op, object val1, object val2) { double n2 = (double)val2; double n1 = NumberFunctions.Number(Rtf(val1)); return cmpNumberNumber(op, n1, n2); } private static bool cmpStringStringE(Operator.Op op, string n1, string n2) { Debug.Assert(op == Operator.Op.EQ || op == Operator.Op.NE, "Unexpected Operator.op code in cmpStringStringE()" ); return (op == Operator.Op.EQ) == (n1 == n2); } private static bool cmpStringStringE(Operator.Op op, object val1, object val2) { string n1 = (string)val1; string n2 = (string)val2; return cmpStringStringE(op, n1, n2); } private static bool cmpRtfStringE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); string n2 = (string)val2; return cmpStringStringE(op, n1, n2); } private static bool cmpRtfRtfE(Operator.Op op, object val1, object val2) { string n1 = Rtf(val1); string n2 = Rtf(val2); return cmpStringStringE(op, n1, n2); } private static bool cmpStringStringO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number((string)val1); double n2 = NumberFunctions.Number((string)val2); return cmpNumberNumberO(op, n1, n2); } private static bool cmpRtfStringO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); double n2 = NumberFunctions.Number((string)val2); return cmpNumberNumberO(op, n1, n2); } private static bool cmpRtfRtfO(Operator.Op op, object val1, object val2) { double n1 = NumberFunctions.Number(Rtf(val1)); double n2 = NumberFunctions.Number(Rtf(val2)); return cmpNumberNumberO(op, n1, n2); } public override XPathNodeIterator Clone() { return new LogicalExpr(this); } private struct NodeSet { private Query _opnd; private XPathNavigator _current; public NodeSet(object opnd) { _opnd = (Query)opnd; _current = null; } public bool MoveNext() { _current = _opnd.Advance(); return _current != null; } public void Reset() { _opnd.Reset(); } public string Value { get { return _current.Value; } } } private static string Rtf(object o) { return ((XPathNavigator)o).Value; } public override XPathResultType StaticType { get { return XPathResultType.Boolean; } } public override void PrintQuery(XmlWriter w) { w.WriteStartElement(this.GetType().Name); w.WriteAttributeString("op", _op.ToString()); _opnd1.PrintQuery(w); _opnd2.PrintQuery(w); w.WriteEndElement(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; namespace Microsoft.NodejsTools.Profiling { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] [Description("Node.js Tools Profiling Package")] // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", "1.0.0.0", IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(ProfilingGuids.NodejsProfilingPkgString)] // set the window to dock where Toolbox/Performance Explorer dock by default [ProvideToolWindow(typeof(PerfToolWindow), Orientation = ToolWindowOrientation.Left, Style = VsDockStyle.Tabbed, Window = EnvDTE.Constants.vsWindowKindToolbox)] [ProvideFileFilterAttribute("{" + ProfilingGuids.NodejsProfilingPkgString + "}", "/1", "Node.js Performance Session (*" + PerfFileType + ");*" + PerfFileType, 100)] [ProvideEditorExtension(typeof(ProfilingSessionEditorFactory), ".njsperf", 50, ProjectGuid = ProfilingGuids.NodejsProfilingPkgString, NameResourceID = 105, DefaultName = "NodejsPerfSession")] [ProvideAutomationObject("NodejsProfiling")] internal sealed class NodejsProfilingPackage : Package { internal static NodejsProfilingPackage Instance; private static ProfiledProcess _profilingProcess; // process currently being profiled internal static string NodeProjectGuid = "{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}"; internal const string PerformanceFileFilter = "Performance Report Files|*.vspx;*.vsps"; private AutomationProfiling _profilingAutomation; private static OleMenuCommand _stopCommand, _startCommand, _startWizard, _startProfiling, _startCommandCtx; internal const string PerfFileType = ".njsperf"; /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public NodejsProfilingPackage() { Instance = this; } /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); UIThread.EnsureService(this); var shell = (IVsShell)GetService(typeof(SVsShell)); // we call into the Node.js package, so we need it loaded. // TODO - Ideally this wouldn't be hardcoded in here but we don't have a good shared location // move this guid to be from a shared file // Guid nodePackage = new Guid("FE8A8C3D-328A-476D-99F9-2A24B75F8C7F"); IVsPackage package; shell.LoadPackage(ref nodePackage, out package); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidStartNodeProfiling); var oleMenuItem = new OleMenuCommand(StartProfilingWizard, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActive; _startWizard = oleMenuItem; mcs.AddCommand(oleMenuItem); // Create the command for the menu item. menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidPerfExplorer); oleMenuItem = new OleMenuCommand(ShowPeformanceExplorer, menuCommandID); mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidAddPerfSession); oleMenuItem = new OleMenuCommand(AddPerformanceSession, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActive; mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidStartProfiling); oleMenuItem = _startCommand = new OleMenuCommand(StartProfiling, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActiveAndSessionsExist; mcs.AddCommand(oleMenuItem); // Exec is handled by the Performance Explorer node, but we want to handle QueryStatus here to disable // the command when another profiling session is running. menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidPerfCtxStartProfiling); oleMenuItem = _startCommandCtx = new OleMenuCommand(null, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActiveAndSessionsExist; mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidStopProfiling); _stopCommand = oleMenuItem = new OleMenuCommand(StopProfiling, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingInactive; mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(ProfilingGuids.NodejsProfilingCmdSet, (int)PkgCmdIDList.cmdidStartPerformanceAnalysis); _startProfiling = oleMenuItem = new OleMenuCommand(StartPerfAnalysis, menuCommandID); oleMenuItem.BeforeQueryStatus += IsNodejsProjectStartup; mcs.AddCommand(oleMenuItem); } //Create Editor Factory. Note that the base Package class will call Dispose on it. base.RegisterEditorFactory(new ProfilingSessionEditorFactory(this)); } private void StartPerfAnalysis(object sender, EventArgs e) { var view = new ProfilingTargetView(); var sessions = ShowPerformanceExplorer().Sessions; SessionNode activeSession = sessions.ActiveSession; if (activeSession == null || activeSession.Target.ProjectTarget == null || !ProjectTarget.IsSame(activeSession.Target.ProjectTarget, view.Project.GetTarget())) { // need to create a new session var target = new ProfilingTarget() { ProjectTarget = view.Project.GetTarget() }; activeSession = AddPerformanceSession( view.Project.Name, target ); } ProfileProjectTarget(activeSession, activeSession.Target.ProjectTarget, true); } private void IsNodejsProjectStartup(object sender, EventArgs e) { bool foundStartupProject = false; var dteService = (EnvDTE.DTE)(GetService(typeof(EnvDTE.DTE))); if (dteService.Solution.SolutionBuild.StartupProjects != null) { var startupProjects = ((object[])dteService.Solution.SolutionBuild.StartupProjects).Select(x => x.ToString()); foreach (EnvDTE.Project project in dteService.Solution.Projects) { var kind = project.Kind; if (String.Equals(kind, NodejsProfilingPackage.NodeProjectGuid, StringComparison.OrdinalIgnoreCase)) { if (startupProjects.Contains(project.UniqueName, StringComparer.OrdinalIgnoreCase)) { foundStartupProject = true; break; } } } } var oleMenu = sender as OleMenuCommand; oleMenu.Enabled = foundStartupProject; } protected override object GetAutomationObject(string name) { if (name == "NodejsProfiling") { if (_profilingAutomation == null) { var pane = (PerfToolWindow)this.FindToolWindow(typeof(PerfToolWindow), 0, true); _profilingAutomation = new AutomationProfiling(pane.Sessions); } return _profilingAutomation; } return base.GetAutomationObject(name); } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void StartProfilingWizard(object sender, EventArgs e) { var targetView = new ProfilingTargetView(); var dialog = new LaunchProfiling(targetView); var res = dialog.ShowModal() ?? false; if (res && targetView.IsValid) { var target = targetView.GetTarget(); if (target != null) { ProfileTarget(target); } } } internal SessionNode ProfileTarget(ProfilingTarget target, bool openReport = true) { bool save; string name = target.GetProfilingName(out save); var session = ShowPerformanceExplorer().Sessions.AddTarget(target, name, save); StartProfiling(target, session, openReport); return session; } internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true) { if (!Utilities.SaveDirtyFiles()) { // Abort return; } if (target.ProjectTarget != null) { ProfileProjectTarget(session, target.ProjectTarget, openReport); } else if (target.StandaloneTarget != null) { ProfileStandaloneTarget(session, target.StandaloneTarget, openReport); } else { if (MessageBox.Show(Resources.NoProfilingConfiguredMessageText, Resources.NoProfilingConfiguredMessageCaption, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { var newTarget = session.OpenTargetProperties(); if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null)) { StartProfiling(newTarget, session, openReport); } } } } private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport) { var targetGuid = projectTarget.TargetProject; var dte = (EnvDTE.DTE)GetGlobalService(typeof(EnvDTE.DTE)); EnvDTE.Project projectToProfile = null; foreach (EnvDTE.Project project in dte.Solution.Projects) { var kind = project.Kind; if (String.Equals(kind, NodejsProfilingPackage.NodeProjectGuid, StringComparison.OrdinalIgnoreCase)) { var guid = project.Properties.Item("Guid").Value as string; Guid guidVal; if (Guid.TryParse(guid, out guidVal) && guidVal == projectTarget.TargetProject) { projectToProfile = project; break; } } } if (projectToProfile != null) { var t = ProfileProject(session, projectToProfile, openReport); } else { MessageBox.Show(Resources.ProjectNotFoundErrorMessageText, Resources.NodejsToolsForVS); } } internal async System.Threading.Tasks.Task ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport) { var uiThread = (UIThreadBase)NodejsProfilingPackage.Instance.GetService(typeof(UIThreadBase)); if (!await uiThread.InvokeTask(() => EnsureProjectUpToDate(projectToProfile)) && await uiThread.InvokeAsync(() => MessageBox.Show(Resources.FailedToBuild, Resources.NodejsToolsForVS, MessageBoxButton.YesNo)) == MessageBoxResult.No) { return; } var interpreterArgs = (string)projectToProfile.Properties.Item(NodeProjectProperty.NodeExeArguments).Value; var scriptArgs = (string)projectToProfile.Properties.Item(NodeProjectProperty.ScriptArguments).Value; var startBrowser = (bool)projectToProfile.Properties.Item(NodeProjectProperty.StartWebBrowser).Value; string launchUrl = (string)projectToProfile.Properties.Item(NodeProjectProperty.LaunchUrl).Value; int? port = (int?)projectToProfile.Properties.Item(NodeProjectProperty.NodejsPort).Value; string interpreterPath = (string)projectToProfile.Properties.Item(NodeProjectProperty.NodeExePath).Value; string startupFile = (string)projectToProfile.Properties.Item("StartupFile").Value; if (String.IsNullOrEmpty(startupFile)) { MessageBox.Show(Resources.NoConfiguredStatupFileErrorMessageText, Resources.NodejsToolsForVS); return; } string workingDir = projectToProfile.Properties.Item("WorkingDirectory").Value as string; if (String.IsNullOrEmpty(workingDir) || workingDir == ".") { workingDir = projectToProfile.Properties.Item("ProjectHome").Value as string; if (String.IsNullOrEmpty(workingDir)) { workingDir = Path.GetDirectoryName(projectToProfile.FullName); } } RunProfiler( session, interpreterPath, interpreterArgs, startupFile, scriptArgs, workingDir, null, openReport, launchUrl, port, startBrowser ); } private class UpdateSolutionEvents : IVsUpdateSolutionEvents { private readonly TaskCompletionSource<bool> SuccessSource = new TaskCompletionSource<bool>(); public Task<bool> Task { get { return SuccessSource.Task; } } public int OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } public int UpdateSolution_Begin(ref int pfCancelUpdate) { pfCancelUpdate = 0; return VSConstants.S_OK; } public int UpdateSolution_Cancel() { return VSConstants.S_OK; } public int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { SuccessSource.SetResult(fSucceeded != 0); return VSConstants.S_OK; } public int UpdateSolution_StartUpdate(ref int pfCancelUpdate) { pfCancelUpdate = 0; return VSConstants.S_OK; } } /// <summary> /// Ensures the project is up to date. Returns true if the project is up to date /// or is successfully built, false if it's not up to date. /// </summary> private async Task<bool> EnsureProjectUpToDate(EnvDTE.Project projectToProfile) { var guid = Guid.Parse((string)projectToProfile.Properties.Item("Guid").Value); var solution = (IVsSolution)GetService(typeof(SVsSolution)); IVsHierarchy hierarchy; if (ErrorHandler.Succeeded(solution.GetProjectOfGuid(ref guid, out hierarchy))) { var buildMan = (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)); if (buildMan != null) { if (((IVsSolutionBuildManager3)buildMan).AreProjectsUpToDate(0) == VSConstants.S_OK) { // projects are up to date, no need to build. return true; } uint updateCookie = VSConstants.VSCOOKIE_NIL; var updateEvents = new UpdateSolutionEvents(); try { if (ErrorHandler.Succeeded(buildMan.AdviseUpdateSolutionEvents(updateEvents, out updateCookie))) { int hr; if (ErrorHandler.Succeeded( hr = buildMan.StartSimpleUpdateProjectConfiguration( hierarchy, null, null, (uint)(VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD), 0, 0 ))) { return await updateEvents.Task; } } } finally { if (updateCookie != VSConstants.VSCOOKIE_NIL) { buildMan.UnadviseUpdateSolutionEvents(updateCookie); } } } } return true; } private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport) { RunProfiler( session, runTarget.InterpreterPath, String.Empty, // interpreter args runTarget.Script, runTarget.Arguments, runTarget.WorkingDirectory, null, // env vars openReport, null, // launch url, null, // port false // start browser ); } private static void RunProfiler(SessionNode session, string interpreter, string interpreterArgs, string script, string scriptArgs, string workingDir, Dictionary<string, string> env, bool openReport, string launchUrl, int? port, bool startBrowser) { if (String.IsNullOrWhiteSpace(interpreter)) { Nodejs.ShowNodejsNotInstalled(); return; } else if (!File.Exists(interpreter)) { Nodejs.ShowNodejsPathNotFound(interpreter); return; } var arch = NativeMethods.GetBinaryType(interpreter); bool jmc = true; using (var vsperfKey = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_UserSettings).OpenSubKey("VSPerf")) { if (vsperfKey != null) { var value = vsperfKey.GetValue("tools.options.justmycode"); int jmcSetting; if (value != null && value is string && Int32.TryParse((string)value, out jmcSetting)) { jmc = jmcSetting != 0; } } } var process = new ProfiledProcess(interpreter, interpreterArgs, script, scriptArgs, workingDir, env, arch, launchUrl, port, startBrowser, jmc); string baseName = Path.GetFileNameWithoutExtension(session.Filename); string date = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture); string outPath = Path.Combine(Path.GetDirectoryName(session.Filename), baseName + "_" + date + ".vspx"); int count = 1; while (File.Exists(outPath)) { outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vspx"); count++; } process.ProcessExited += (sender, args) => { var dte = (EnvDTE.DTE)NodejsProfilingPackage.GetGlobalService(typeof(EnvDTE.DTE)); _profilingProcess = null; _stopCommand.Enabled = false; _startCommand.Enabled = true; _startCommandCtx.Enabled = true; if (openReport && File.Exists(outPath)) { dte.ItemOperations.OpenFile(outPath); } }; session.AddProfile(outPath); process.StartProfiling(outPath); _profilingProcess = process; _stopCommand.Enabled = true; _startCommand.Enabled = false; _startCommandCtx.Enabled = false; } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void ShowPeformanceExplorer(object sender, EventArgs e) { ShowPerformanceExplorer(); } internal PerfToolWindow ShowPerformanceExplorer() { var pane = this.FindToolWindow(typeof(PerfToolWindow), 0, true); if (pane == null) { throw new InvalidOperationException(); } IVsWindowFrame frame = pane.Frame as IVsWindowFrame; if (frame == null) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(frame.Show()); return pane as PerfToolWindow; } private void AddPerformanceSession(object sender, EventArgs e) { string baseName = "Performance"; var target = new ProfilingTarget(); AddPerformanceSession(baseName, target); } private SessionNode AddPerformanceSession(string baseName, ProfilingTarget target) { var dte = (EnvDTE.DTE)NodejsProfilingPackage.GetGlobalService(typeof(EnvDTE.DTE)); string filename; int? id = null; bool save = false; do { filename = baseName + id + PerfFileType; if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { filename = Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), filename); save = true; } id = (id ?? 0) + 1; } while (File.Exists(filename)); return ShowPerformanceExplorer().Sessions.AddTarget(target, filename, save); } private void StartProfiling(object sender, EventArgs e) { ShowPerformanceExplorer().Sessions.StartProfiling(); } private void StopProfiling(object sender, EventArgs e) { var process = _profilingProcess; if (process != null) { process.StopProfiling(); } } private void IsProfilingActiveAndSessionsExist(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = false; } else { if (PerfToolWindow.Instance != null && PerfToolWindow.Instance.Sessions.Sessions.Count > 0) { oleMenu.Enabled = true; } else { oleMenu.Enabled = false; } } } private void IsProfilingInactive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = true; } else { oleMenu.Enabled = false; } } private void IsProfilingActive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = false; } else { oleMenu.Enabled = true; } } public bool IsProfiling { get { return _profilingProcess != null; } } internal Guid GetStartupProjectGuid() { var buildMgr = (IVsSolutionBuildManager)GetService(typeof(IVsSolutionBuildManager)); IVsHierarchy hierarchy; if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out hierarchy)) && hierarchy != null) { Guid guid; if (ErrorHandler.Succeeded(hierarchy.GetGuidProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out guid ))) { return guid; } } return Guid.Empty; } internal IVsSolution Solution { get { return GetService(typeof(SVsSolution)) as IVsSolution; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; using System.Xml.Xsl; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Icons; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Modules.UserDefinedTable.Components; using DotNetNuke.Security; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Skins.Controls; using Microsoft.VisualBasic; using Globals = DotNetNuke.Common.Globals; namespace DotNetNuke.Modules.UserDefinedTable { /// ----------------------------------------------------------------------------- /// <summary> /// The UserDefinedTable Class provides the UI for displaying the UserDefinedTable /// </summary> /// ----------------------------------------------------------------------------- public partial class List : PortalModuleBase, IActionable, IPostBackEventHandler { #region Search class SearchManager { readonly List _parent; readonly PlaceHolder _searchPlaceHolder; readonly LinkButton _cmdSearch; readonly LinkButton _cmdResetSearch; enum SearchControlTypes { Columns = 1, @Operator = 2, Search = 3 } public SearchManager(List parent) { _parent = parent; _cmdSearch = parent.cmdSearch; _cmdSearch.Click += cmdSearch_Click; _cmdResetSearch = parent.cmdResetSearch; _cmdResetSearch.Click += cmdResetSearch_Click; _searchPlaceHolder = parent.phSearchSentence; } public bool IsSearching { get { return _parent.ViewState["IsSearching"].AsBoolean() || ! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}q", _parent.ModuleId)]); } private set { _parent.ViewState["IsSearching"] = value; } } TextBox TxtSearch { get { return ((TextBox) (SearchControl(SearchControlTypes.Search))); } } DropDownList DrpSearchMode { get { return ((DropDownList) (SearchControl(SearchControlTypes.Operator))); } } DropDownList DrpSearchableColumns { get { return ((DropDownList) (SearchControl(SearchControlTypes.Columns))); } } public string Filter() { var searchString = string.Empty; if (TxtSearch.Text == string.Empty) { return string.Empty; } var dataSet = _parent.DataSet; foreach (DataRow row in dataSet.Tables[DataSetTableName.Fields].Rows) { if (TxtSearch.Visible && Convert.ToBoolean(row[FieldsTableColumn.Searchable])) { var fieldTitle = row[FieldsTableColumn.Title].ToString(); if (DrpSearchableColumns.SelectedValue == "allcolumns" || DrpSearchableColumns.SelectedValue == fieldTitle) { //add to search expression: if (searchString != string.Empty) { searchString += " OR "; } if (_parent.Settings.UrlSearch && dataSet.Tables[DataSetTableName.Data].Columns.Contains(fieldTitle + DataTableColumn.Appendix_Url)) { fieldTitle += DataTableColumn.Appendix_Url; } else if ( dataSet.Tables[DataSetTableName.Data].Columns.Contains(fieldTitle + DataTableColumn. Appendix_Caption)) { fieldTitle += DataTableColumn.Appendix_Caption; } if (dataSet.Tables[DataSetTableName.Data].Columns[fieldTitle].DataType == typeof (string)) { searchString += string.Format("([{0}] Like \'[UDT:Search]\')", fieldTitle); } else { searchString += string.Format("(Convert([{0}], \'System.String\') Like \'[UDT:Search]\')", fieldTitle); } } } } var searchpattern = TxtSearch.Text; if (DrpSearchMode.Visible) { switch (DrpSearchMode.SelectedValue) { case "contain": searchpattern = string.Format("*{0}*", searchpattern); break; case "startwith": searchpattern = string.Format("{0}*", searchpattern); break; case "endwith": searchpattern = string.Format("*{0}", searchpattern); break; case "equal": break; } } else { if (searchpattern.StartsWith("|") && searchpattern.EndsWith("|")) { searchpattern = searchpattern.Substring(1, Convert.ToInt32(searchpattern.Length - 2)); } else if (searchpattern.StartsWith("|")) { searchpattern = string.Format("{0}*", searchpattern.Substring(1)); } else if (searchpattern.EndsWith("|")) { searchpattern = string.Format("*{0}", searchpattern.Substring(0, Convert.ToInt32(searchpattern.Length - 1))); } else { searchpattern = string.Format("*{0}*", searchpattern); } } return searchString.Replace("[UDT:Search]", EscapeSearchInput(searchpattern)); } static string EscapeSearchInput(string input) { return input.Replace("\'", "\'\'"); } void Reset() { TxtSearch.Text = ""; DrpSearchMode.SelectedValue = "contain"; DrpSearchableColumns.SelectedIndex = 0; } public bool DataBindingNeeded() { var isSearchable = _parent.DataSet.Tables[DataSetTableName.Fields].Rows .Cast<DataRow>() .Any(row => row[FieldsTableColumn.Searchable].AsBoolean()); if (isSearchable) { _parent.panSearch.Visible = true; if (! _parent.Settings.SimpleSearch ) { _parent.plSearch.Visible = false; } else { foreach (Control c in _searchPlaceHolder.Controls) { c.Visible = c.ID == "txtSearch"; } } if (IsSearching == false && ! _parent.Settings.ShowNoRecordsUntilSearch ) { IsSearching = true; //always set flag to true, if ShowNoRecordsUntilSearch is not checked } } _parent.cmdResetSearch.Visible = TxtSearch.Text != "" || DrpSearchMode.SelectedValue != "contain"; //'Show Datagrid if //' - Module has no search columns OR //' - IsSearching = True OR //' - search box is not empty return (! isSearchable || IsSearching || TxtSearch.Text != ""); } public void LoadControls() { _searchPlaceHolder.Controls.Clear(); const string regexPattern = "(?<=\\{)(?<control>\\d)(?=\\})|(?<text>[^\\{\\}]+)"; foreach ( Match m in new Regex(regexPattern).Matches(Localization.GetString("SearchSentence", _parent.LocalResourceFile))) { if (m.Result("${text}").AsString() != string.Empty) { _searchPlaceHolder.Controls.Add(new LiteralControl(m.Result("${text}"))); } if (m.Result("${control}").AsString() != string.Empty) { var controlType = (SearchControlTypes) (int.Parse(m.Result("${control}"))); SearchControl(controlType); } } //ensure Search Controls SearchControl(SearchControlTypes.Columns); SearchControl(SearchControlTypes.Operator); SearchControl(SearchControlTypes.Search); } Control SearchControl(SearchControlTypes controlType) { var moduleId = _parent.ModuleId; switch (controlType) { case SearchControlTypes.Columns: var drpSearchableColumns = (DropDownList) (_searchPlaceHolder.FindControl("drpSearchableColumns")); if (drpSearchableColumns == null) { var drp = new DropDownList {ID = "drpSearchableColumns", CssClass = "NormalTextBox"}; _searchPlaceHolder.Controls.Add(drp); var lbl = new Label {ID = "lblSearchableColumn"}; lbl.Font.Bold = true; lbl.Visible = false; _searchPlaceHolder.Controls.Add(lbl); LoadColumns(); drpSearchableColumns = drp; if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}c", moduleId)])) { drpSearchableColumns.SelectedValue = _parent.Request.QueryString[string.Format("u{0}c", moduleId)].UrlHexDecode(); } } return drpSearchableColumns; case SearchControlTypes.Operator: var drpSearchMode = (DropDownList) (_searchPlaceHolder.FindControl("drpSearchMode")); if (drpSearchMode == null) { var drp = new DropDownList {ID = "drpSearchMode", CssClass = "NormalTextBox"}; drp.Items.Add( new ListItem(Localization.GetString("SearchMode.Contain", _parent.LocalResourceFile), "contain")); drp.Items.Add( new ListItem(Localization.GetString("SearchMode.StartWith", _parent.LocalResourceFile), "startwith")); drp.Items.Add( new ListItem(Localization.GetString("SearchMode.EndWith", _parent.LocalResourceFile), "endwith")); drp.Items.Add( new ListItem(Localization.GetString("SearchMode.Equal", _parent.LocalResourceFile), "equal")); _searchPlaceHolder.Controls.Add(drp); drpSearchMode = drp; if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}m", moduleId)])) { drpSearchMode.SelectedValue = _parent.Request.QueryString[string.Format("u{0}m", moduleId)]; } } return drpSearchMode; case SearchControlTypes.Search: var txtSearch = (TextBox) (_searchPlaceHolder.FindControl("txtSearch")); if (txtSearch == null) { txtSearch = new TextBox {ID = "txtSearch"}; _searchPlaceHolder.Controls.Add(txtSearch); if (! string.IsNullOrEmpty(_parent.Request.QueryString[string.Format("u{0}q", moduleId)])) { txtSearch.Text = _parent.Request.QueryString[string.Format("u{0}q", moduleId)].UrlHexDecode(); } } return txtSearch; } return null; } void LoadColumns() { DrpSearchableColumns.Items.Clear(); DrpSearchableColumns.Items.Add( new ListItem(Localization.GetString("AllColumns", _parent.LocalResourceFile), "allcolumns")); var fieldTitle = string.Empty; foreach (DataRow row in _parent.DataSet.Tables[DataSetTableName.Fields].Rows) { var searchable = Convert.ToBoolean(row[FieldsTableColumn.Searchable]); if (searchable) { fieldTitle = row[FieldsTableColumn.Title].ToString(); if (fieldTitle != "allcolumns") { DrpSearchableColumns.Items.Add(new ListItem(fieldTitle, fieldTitle)); } } } if (DrpSearchableColumns.Items.Count == 2) { //display label instead of dropdownlist if there is only one searchable column DrpSearchableColumns.Items.RemoveAt(0); //remove "all searchable columns" DrpSearchableColumns.Visible = false; var lblSearchableColumn = (Label) (_searchPlaceHolder.FindControl("lblSearchableColumn")); lblSearchableColumn.Text = fieldTitle; lblSearchableColumn.Visible = true; } } void cmdSearch_Click(object sender, EventArgs e) { if (! _parent.RenderMethod.StartsWith("UDT_Xsl")) { _parent.CurrentPage = 1; IsSearching = true; } else { var @params = new List<string>(); var moduleId = _parent.ModuleId; if (! string.IsNullOrEmpty(TxtSearch.Text)) { @params.Add(string.Format("u{0}q={1}", moduleId, TxtSearch.Text.UrlHexEncode())); if (! _parent.Settings.SimpleSearch ) { @params.Add(string.Format("u{0}c={1}", moduleId, DrpSearchableColumns.SelectedValue.UrlHexEncode())); @params.Add(string.Format("u{0}m={1}", moduleId, DrpSearchMode.SelectedValue)); } var url = Globals.NavigateURL(_parent.TabId, "", @params.ToArray()); _parent.Response.Redirect(url); } // Such paramter } } void cmdResetSearch_Click(object sender, EventArgs e) { if (! _parent.RenderMethod.StartsWith("UDT_Xsl")) { Reset(); _parent.CurrentPage = 1; IsSearching = false; } else { _parent.Response.Redirect(Globals.NavigateURL(_parent.TabId)); } } } #endregion #region Private Members DataSet _dataSet; SearchManager _search; Components.Settings _settings; new Components.Settings Settings { get { return _settings ?? (_settings = new Components.Settings(ModuleContext.Settings)); } } #endregion #region Private Properties UserDefinedTableController _udtController; UserDefinedTableController UdtController { get { return _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext)); } } DataSet DataSet { get { return _dataSet ?? (_dataSet = UdtController.GetDataSet()); } } string RenderMethod { get { return string.Format("UDT_{0}", Settings.RenderingMethod ); } } #region properties Only Needed in Grid Mode int CurrentPage { get { if (ViewState["CurrentPage"] == null) { return 1; } return Convert.ToInt32(ViewState["CurrentPage"]); } set { ViewState["CurrentPage"] = value; } } string SortField { get { if (ViewState["SortField"] == null) { if (Settings.SortFieldId!=Null.NullInteger ) { ViewState["SortField"] = GetFieldTitle(Settings.SortFieldId ); } } return ViewState["SortField"].AsString(); } set { ViewState["SortField"] = value; } } string SortOrder { get { if (ViewState["SortOrder"] == null) { return Settings.SortOrder; } return ViewState["SortOrder"].AsString(); } set { ViewState["SortOrder"] = value; } } #endregion #endregion #region Data Binding void BindData() { if (!SchemaIsDefined() ) { ShowModuleMessage("NoFieldsDefined.ErrorMessage", ModuleContext.EditUrl("Manage"), "No fields defined"); } else { var mustBind = true; if (Settings.ShowSearchTextBox) { if (! _search.DataBindingNeeded()) { ctlPagingControl.TotalRecords = 0; ctlPagingControl.Visible = false; lblNoRecordsFound.Visible = false; mustBind = false; } } else { panSearch.Visible = false; } if (mustBind) { switch (RenderMethod) { case SettingName.XslUserDefinedStyleSheet: var styleSheet = (string) ModuleContext.Settings[RenderMethod]; if (string.IsNullOrEmpty( styleSheet )) { BindDataToDataGrid(); } else BindDataUsingXslTransform(styleSheet); break; case SettingName.XslPreDefinedStyleSheet: var oldStyleSheet = (string) ModuleContext.Settings[RenderMethod]; var newStyleSheet = CopyScriptToPortal(oldStyleSheet); var mc = new ModuleController(); mc.UpdateTabModuleSetting(TabModuleId, SettingName.RenderingMethod, "XslUserDefinedStyleSheet"); mc.UpdateTabModuleSetting(TabModuleId,SettingName.XslUserDefinedStyleSheet , newStyleSheet ); BindDataUsingXslTransform(newStyleSheet); break; default: //grid rendering BindDataToDataGrid(); break; } } } } string CopyScriptToPortal(string styleSheet) { var path = MapPath(styleSheet); var filename = Path.GetFileName(path); var folderManager = FolderManager.Instance; if (!folderManager.FolderExists(PortalId, "XslStyleSheets")) folderManager.AddFolder(PortalId, "XslStyleSheets"); const string legacyPath = "XslStyleSheets/UDT Legacy"; var folderInfo = folderManager.FolderExists(PortalId, legacyPath)? folderManager.GetFolder(PortalId, legacyPath) : folderManager.AddFolder(PortalId, legacyPath); using (var source= new FileStream(path,FileMode.Open )) { var fileInfo = !FileManager.Instance.FileExists(folderInfo, filename) ? FileManager.Instance.AddFile(folderInfo, filename, source) : FileManager.Instance.GetFile(folderInfo, filename); return string.Format("{0}/{1}", legacyPath, fileInfo.FileName); } } void ShowModuleMessage(string keyForLocalization, string parameter, string fallBackMessage) { //Dummy text var strMessageFormat = Localization.GetString(keyForLocalization, LocalResourceFile).AsString(); if (strMessageFormat != string.Empty) { fallBackMessage = string.Format(strMessageFormat, parameter); } ShowModuleMessage(fallBackMessage); } /// ----------------------------------------------------------------------------- /// <summary> /// BindDataToDataGrid fetchs the data from the database and binds it to the grid /// </summary> /// ----------------------------------------------------------------------------- void BindDataToDataGrid() { PopulateDataGridColumns(); var dataTable = DataSet.Tables[DataSetTableName.Data]; dataTable .FilterAndSort( GetRowFilter(Settings.Filter, _search.Filter()), SortField, SortOrder) .Top(Settings.TopCount); //Paging var paging = new { PageSize = Settings.Paging, AllowPaging = Settings.Paging != Null.NullInteger, PageIndex = Convert.ToInt32( Math.Min(CurrentPage, Math.Ceiling(((double)dataTable.Rows.Count / Settings.Paging))) - 1), TotalRecords = dataTable.Rows.Count }; dataTable.Page( paging.PageIndex, paging.PageSize); using (var data = new DataView(dataTable)) { if (data.Count > 0) { lblNoRecordsFound.Visible = false; try { grdData.DataSource = data; grdData.DataBind(); } catch (FormatException e) { HandleException(e, "Databind Exception"); } grdData.Visible = true; ctlPagingControl.Visible = paging.AllowPaging; ctlPagingControl.PageSize = paging.PageSize; ctlPagingControl.CurrentPage = paging.PageIndex + 1; ctlPagingControl.TotalRecords = paging.TotalRecords; } else { if (_search.IsSearching) { lblNoRecordsFound.Visible = true; } ctlPagingControl.TotalRecords = 0; ctlPagingControl.Visible = false; } } } PortalModuleBase GetModuleControl() { return (PortalModuleBase) (((Parent.Parent ) is PortalModuleBase) ? Parent.Parent : this); } /// ----------------------------------------------------------------------------- /// <summary> /// set up Fielddefinitions for Datagrid /// </summary> /// ----------------------------------------------------------------------------- void PopulateDataGridColumns() { for (var intColumn = grdData.Columns.Count - 1; intColumn >= 1; intColumn--) { grdData.Columns.RemoveAt(intColumn); } foreach (DataRow row in DataSet.Tables[DataSetTableName.Fields].Rows) { //Add Fields dynamically to the grdData var colField = new BoundField { HeaderText = row[FieldsTableColumn.Title].ToString(), DataField = row[FieldsTableColumn.Title].ToString(), HtmlEncode = false, Visible = Convert.ToBoolean(row[FieldsTableColumn.Visible]), SortExpression = string.Format("{0}|ASC", row[FieldsTableColumn.Title]) }; //Add a sorting indicator to the headertext if ( row[FieldsTableColumn.Title].ToString() == SortField && colField.Visible) { if (SortOrder == "ASC") { colField.HeaderText += string.Format( "<img src=\"{0}/images/sortascending.gif\" border=\"0\" alt=\"Sorted By {1} In Ascending Order\"/>", (Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath), SortField); } else { colField.HeaderText += string.Format( "<img src=\"{0}/images/sortdescending.gif\" border=\"0\" alt=\"Sorted By {1} In Descending Order\"/>", (Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath), SortField); } } //Column settings depending on the fieldtype DataType.ByName(row[FieldsTableColumn.Type].ToString()). SetStylesAndFormats(colField,row[FieldsTableColumn.OutputSettings].AsString()); grdData.Columns.Add(colField); } var editLinkNeed = DataSet.Tables[DataSetTableName.Data].Rows .Cast<DataRow>() .Any(row => ! string.IsNullOrEmpty(row[DataTableColumn.EditLink] as string)); if (! editLinkNeed) { grdData.Columns.RemoveAt(0); } } /// ----------------------------------------------------------------------------- /// <summary> /// BindDataUsingXslTransform fetchs the data from the database and binds it to the grid /// </summary> /// ----------------------------------------------------------------------------- void BindDataUsingXslTransform(string styleSheet) { try { DataSet.Tables.Add(UdtController.Context("", Settings.SortFieldId.ToString(), Settings.SortOrder , Settings.Paging.ToString())); DataSet.Tables[DataSetTableName.Data] .FilterAndSort(GetRowFilter(Settings.Filter, _search.Filter()), SortField, SortOrder) .Top(Settings.TopCount); var xslTrans = new XslCompiledTransform(); var script = Utilities.ReadStringFromFile(styleSheet, PortalId); var reader = new XmlTextReader(new StringReader(script)); xslTrans.Load(reader); using (XmlReader xmlData = new XmlTextReader(new StringReader(DataSet.GetXml()))) { using (var stringWriter = new StringWriter()) { //Dynamic UDT Params. Add all Request parameters that starts with "UDT_{moduleid}_Param*" as "Param*" named XSL parameter var args = new XsltArgumentList(); var udtParameterPrefix = string.Format(Definition.QueryStringParameter,ModuleContext.ModuleId); foreach (string paramKey in Request.Params.Keys) { if (paramKey != null && paramKey.ToLowerInvariant().StartsWith(udtParameterPrefix)) { args.AddParam(paramKey.ToLowerInvariant().Substring(udtParameterPrefix.Length - 5), string.Empty, Request[paramKey]); } } xslTrans.Transform(xmlData, args, stringWriter); XslOutput.Controls.Add(new LiteralControl(stringWriter.ToString())); } } XslOutput.Visible = true; } catch (Exception exc) { HandleException(exc, string.Format("{0}<br/>StyleSheet:{1}", Localization.GetString("XslFailed.ErrorMessage", LocalResourceFile), styleSheet)); BindDataToDataGrid(); } } void HandleException(Exception exc, string localizedMessage) { var message = new PortalSecurity().InputFilter(exc.Message, PortalSecurity.FilterFlag.NoScripting); message = string.Format("{0}<br/>Error Description: {1}", localizedMessage, message); ShowModuleMessage(message); Exceptions.LogException(exc); } void ShowModuleMessage(string message) { var moduleControl = GetModuleControl(); var modSecurity = new ModuleSecurity(ModuleContext); if (modSecurity.IsAllowedToAdministrateModule()) { UI.Skins.Skin.AddModuleMessage(moduleControl, message,ModuleMessage.ModuleMessageType.YellowWarning); } } #endregion #region Private Subs and Functions string GetRowFilter(string filter, string search) { var tokenReplace = new TokenReplace(escapeApostrophe: true) {ModuleInfo = ModuleContext.Configuration}; if (filter != string.Empty) { filter = tokenReplace.ReplaceEnvironmentTokens(filter); } if (filter != string.Empty && search != string.Empty) { return string.Format("{0} AND ({1})", filter, search); } return filter + search; } string GetFieldTitle(int fieldId) { using ( var dv = new DataView(DataSet.Tables[DataSetTableName.Fields]) {RowFilter = string.Format("{0}={1}", FieldsTableColumn.Id, fieldId)}) { if (dv.Count > 0) { return (string) (dv[0][FieldsTableColumn.Title]); } return ""; } } bool IsKnownField(string fieldName) { var fieldstable = DataSet.Tables[DataSetTableName.Fields]; fieldName = fieldName.Replace("\'", "\'\'"); return fieldstable.Select(string.Format("{0}=\'{1}\'", FieldsTableColumn.Title, fieldName)).Length >= 0; } #endregion #region Event Handlers protected override void OnInit(EventArgs e) { base.OnInit(e); ModuleContext.HelpURL = string.Format("http://www.dotnetnuke.com/{0}?tabid=457", Globals.glbDefaultPage); Load += Page_Load; PreRender += Page_PreRender; ctlPagingControl.PageChanged += ctlPagingControl_CurrentPageChanged; grdData.Sorting += grdData_Sorting; try { _search = new SearchManager(this); _search.LoadControls(); } catch (Exception ex) { Exceptions.LogException(ex); } } void Page_Load(object sender, EventArgs e) { try { if (! IsPostBack) { CurrentPage = 1; EnsureActionButton(); } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } protected void ctlPagingControl_CurrentPageChanged(object sender, EventArgs e) { CurrentPage = ctlPagingControl.CurrentPage; } protected void grdData_Sorting(object sender, GridViewSortEventArgs e) { try { var strSort = e.SortExpression.Split('|'); var newSortField = strSort[0]; if (IsKnownField(newSortField)) { if ((newSortField == SortField && SortOrder == "ASC") || (newSortField != SortField && strSort[1] == "DESC")) { SortOrder = "DESC"; } else { SortOrder = "ASC"; } SortField = newSortField; } } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } protected void Page_PreRender(object sender, EventArgs e) { try { BindData(); } catch (Exception exc) { HandleException(exc, Localization.GetString("DataBindingFailed.ErrorMessage", LocalResourceFile)); } } #endregion #region Optional Interfaces public void EnsureActionButton() { var modSecurity = new ModuleSecurity(ModuleContext); var useButtons = Settings.UseButtonsInForm ; if (Settings.OnlyFormIsShown ) { var url = Globals.NavigateURL(ModuleContext.TabId); var title = Localization.GetString("BackToForm.Action", LocalResourceFile); ActionLink.NavigateUrl = url; ActionLink.Text = title; placeholderActions.Visible = useButtons; } else if (Settings.OnlyListIsShown && modSecurity.IsAllowedToAddRow() && SchemaIsDefined() && (modSecurity.IsAllowedToAdministrateModule() || HasAddPermissonByQuota())) { var url = ModuleContext.EditUrl(); var title = Localization.GetString(ModuleActionType.AddContent, LocalResourceFile); ActionLink.NavigateUrl = url; ActionLink.Text = title; placeholderActions.Visible = useButtons; } } public ModuleActionCollection ModuleActions { get { var actions = new ModuleActionCollection(); try { var modSecurity = new ModuleSecurity(ModuleContext); var useButtons = Settings.UseButtonsInForm ; var cmdName = useButtons ? "": ModuleActionType.AddContent; try { if (Settings.OnlyFormIsShown ) { var url = Globals.NavigateURL(ModuleContext.TabId); var title = Localization.GetString("BackToForm.Action", LocalResourceFile); actions.Add(ModuleContext.GetNextActionID(), title, cmdName, "", Utilities.IconURL("Lt"), url, false, SecurityAccessLevel.View, true, false); } else if (Settings.OnlyListIsShown && modSecurity.IsAllowedToAddRow() && SchemaIsDefined() && (modSecurity.IsAllowedToAdministrateModule() || HasAddPermissonByQuota())) { var url = ModuleContext.EditUrl(); var title = Localization.GetString(ModuleActionType.AddContent, LocalResourceFile); actions.Add(ModuleContext.GetNextActionID(), title, cmdName , "",Utilities.IconURL("Add"), url, false, SecurityAccessLevel.View, true, false); } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { // This try/catch is to avoid loosing control about your current UDT module - if an error happens inside GetDatSet, it will be raised and handled again inside databind } actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("ShowXML.Action", LocalResourceFile), "", "", ResolveUrl("~/images/XML.gif"), (ResolveUrl(string.Format("~{0}ShowXml.ashx", Definition.PathOfModule)) + "?tabid=" + ModuleContext.TabId + "&mid=" + ModuleContext.ModuleId), false, SecurityAccessLevel.Edit, true, true); //Add 'DeleteAll' command: if (DataSet.Tables[DataSetTableName.Data].Rows.Count > 0) { var urlDelete = Page.ClientScript.GetPostBackEventReference(this, "DeleteAll"); urlDelete = string.Format("javascript:if (confirm(\'{0}\')) {1}", Localization.GetString("DeleteAll.Confirm", LocalResourceFile).AsString().Replace( "\'", "\\\'"), urlDelete); actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("DeleteAll.Action", LocalResourceFile), "", "", Utilities.IconURL("Delete"), urlDelete, false, SecurityAccessLevel.Edit, true, false); } if (RenderMethod == SettingName.XslUserDefinedStyleSheet) { actions.Add(ModuleContext.GetNextActionID(), Localization.GetString("EditXsl.Action", LocalResourceFile), "", "", Utilities.IconURL("Wizard"), ModuleContext.EditUrl("Edit", "Current", "GenerateXsl"), false, SecurityAccessLevel.Edit, true, false); } } catch (Exception ex) { Exceptions.LogException(ex); } return actions; } } bool SchemaIsDefined() { return DataSet.Tables[DataSetTableName.Fields].Rows.Count > 4; } bool HasAddPermissonByQuota() { return ModuleSecurity.HasAddPermissonByQuota(DataSet.Tables[DataSetTableName.Fields], DataSet.Tables[DataSetTableName.Data], Settings.UserRecordQuota , ModuleContext.PortalSettings.UserInfo.Username); } public void RaisePostBackEvent(string eventArgument) { var modSecurity = new ModuleSecurity(ModuleContext); if (eventArgument == "DeleteAll" && modSecurity.IsAllowedToAdministrateModule()) { UdtController.DeleteRows(); Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true); } } #endregion } }
using System; using System.Linq; using Eto.Forms; using swc = Windows.UI.Xaml.Controls; using sw = Windows.UI.Xaml; using wf = Windows.Foundation; using swd = Windows.UI.Xaml.Data; using swm = Windows.UI.Xaml.Media; using Eto.Drawing; namespace Eto.WinRT.Forms { /// <summary> /// Table layout handler. /// </summary> /// <copyright>(c) 2014 by Vivek Jhaveri</copyright> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class TableLayoutHandler : WpfLayout<swc.Grid, TableLayout, TableLayout.ICallback>, TableLayout.IHandler { swc.Border border; Size spacing; Control[,] controls; bool[] columnScale; bool[] rowScale; int lastColumnScale; int lastRowScale; bool inGroupBox; public Size Adjust { get; set; } public override sw.FrameworkElement ContainerControl { get { return border; } } public override Color BackgroundColor { get { return border.Background.ToEtoColor(); } set { border.Background = value.ToWpfBrush(Control.Background); } } public override wf.Size GetPreferredSize(wf.Size constraint) { var widths = new double[columnScale.Length]; double height = 0; for (int y = 0; y < rowScale.Length; y++) { double maxHeight = 0; for (int x = 0; x < widths.Length; x++) { var childControl = controls[x, y].GetWpfFrameworkElement(); if (childControl != null) { var preferredSize = childControl.GetPreferredSize(Conversions.PositiveInfinitySize); var margin = childControl.ContainerControl.Margin; widths[x] = Math.Max(widths[x], preferredSize.Width + margin.Horizontal()); maxHeight = Math.Max(maxHeight, preferredSize.Height + margin.Vertical()); } } height += maxHeight; } return new wf.Size(widths.Sum() + border.Padding.Horizontal(), height + border.Padding.Vertical()); } public void CreateControl(int cols, int rows) { controls = new Control[cols, rows]; columnScale = new bool[cols]; rowScale = new bool[rows]; lastColumnScale = cols - 1; lastRowScale = rows - 1; Control = new swc.Grid { #if TODO_XAML SnapsToDevicePixels = true #endif }; for (int i = 0; i < cols; i++) Control.ColumnDefinitions.Add(new swc.ColumnDefinition { Width = GetColumnWidth(i) }); for (int i = 0; i < rows; i++) Control.RowDefinitions.Add(new swc.RowDefinition { Height = GetRowHeight(i) }); for (int y = 0; y < rows; y++) for (int x = 0; x < cols; x++) Control.Children.Add(EmptyCell(x, y)); border = new swc.Border { Child = Control }; Spacing = Size.Empty; Padding = Padding.Empty; Control.SizeChanged += (s, e) => SetChildrenSizes(); Control.Loaded += (s, e) => SetChildrenSizes(); } class MyEmptyCell : sw.FrameworkElement { } sw.FrameworkElement EmptyCell(int x, int y) { var empty = new MyEmptyCell(); swc.Grid.SetColumn(empty, x); swc.Grid.SetRow(empty, y); SetMargins(empty, x, y); return empty; } public override void OnLoadComplete(EventArgs e) { base.OnLoadComplete(e); inGroupBox = Widget.FindParent<GroupBox>() != null; #if TODO_XAML if (Control.IsLoaded) #endif SetScale(); } public override void SetScale(bool xscale, bool yscale) { base.SetScale(xscale, yscale); SetScale(); } void SetScale() { for (int y = 0; y < Control.RowDefinitions.Count; y++) { for (int x = 0; x < Control.ColumnDefinitions.Count; x++) { var handler = controls[x, y].GetWpfFrameworkElement(); if (handler != null) SetScale(handler, x, y); } } } public override void UpdatePreferredSize() { base.UpdatePreferredSize(); SetChildrenSizes(); } void SetChildrenSizes() { var inGroupBoxCurrent = inGroupBox; var widths = new double[Control.ColumnDefinitions.Count]; for (int y = 0; y < Control.RowDefinitions.Count; y++) { var rowdef = Control.RowDefinitions[y]; var maxy = rowdef.ActualHeight; if (inGroupBoxCurrent && rowdef.Height.IsStar) { maxy -= 1; inGroupBoxCurrent = false; } for (int x = 0; x < Control.ColumnDefinitions.Count; x++) { var coldef = Control.ColumnDefinitions[x]; var maxx = coldef.ActualWidth; var child = controls[x, y]; var childControl = child.GetWpfFrameworkElement(); if (childControl != null) { var margin = childControl.ContainerControl.Margin; childControl.ParentMinimumSize = new wf.Size(Math.Max(0, maxx - margin.Horizontal()), Math.Max(0, maxy - margin.Vertical())); } } } } void SetScale(IWpfFrameworkElement handler, int x, int y) { handler.SetScale(XScale && (columnScale[x] || lastColumnScale == x), YScale && (rowScale[y] || lastRowScale == y)); } void SetMargins() { foreach (var child in Control.Children.OfType<sw.FrameworkElement>()) { var x = swc.Grid.GetColumn(child); var y = swc.Grid.GetRow(child); SetMargins(child, x, y); } } sw.GridLength GetColumnWidth(int column) { var scale = columnScale[column] || column == lastColumnScale; return new sw.GridLength(1, scale ? sw.GridUnitType.Star : sw.GridUnitType.Auto); } sw.GridLength GetRowHeight(int row) { var scale = rowScale[row] || lastRowScale == row; return new sw.GridLength(1, scale ? sw.GridUnitType.Star : sw.GridUnitType.Auto); } public void SetColumnScale(int column, bool scale) { columnScale[column] = scale; var lastScale = lastColumnScale; lastColumnScale = columnScale.Any(r => r) ? -1 : columnScale.Length - 1; Control.ColumnDefinitions[column].Width = GetColumnWidth(column); if (lastScale != lastColumnScale) { Control.ColumnDefinitions[columnScale.Length - 1].Width = GetColumnWidth(columnScale.Length - 1); } SetScale(); } public bool GetColumnScale(int column) { return columnScale[column]; } public void SetRowScale(int row, bool scale) { rowScale[row] = scale; var lastScale = lastRowScale; lastRowScale = rowScale.Any(r => r) ? -1 : rowScale.Length - 1; Control.RowDefinitions[row].Height = GetRowHeight(row); if (lastScale != lastRowScale) { Control.RowDefinitions[rowScale.Length - 1].Height = GetRowHeight(rowScale.Length - 1); } SetScale(); } public bool GetRowScale(int row) { return rowScale[row]; } public Size Spacing { get { return spacing; } set { spacing = value; SetMargins(); } } void SetMargins(sw.FrameworkElement c, int x, int y) { var margin = new sw.Thickness(); if (x > 0) margin.Left = spacing.Width / 2; if (x < Control.ColumnDefinitions.Count - 1) margin.Right = spacing.Width / 2; if (y > 0) margin.Top = spacing.Height / 2; if (y < Control.RowDefinitions.Count - 1) margin.Bottom = spacing.Height / 2; c.HorizontalAlignment = sw.HorizontalAlignment.Stretch; c.VerticalAlignment = sw.VerticalAlignment.Stretch; c.Margin = margin; } public Padding Padding { get { return border.Padding.ToEto(); } set { border.Padding = value.ToWpf(); } } void Remove(int x, int y) { var control = controls[x, y]; controls[x, y] = null; if (control != null) Control.Children.Remove(control.GetContainerControl()); } public void Add(Control child, int x, int y) { Remove(x, y); if (child == null) { Control.Children.Add(EmptyCell(x, y)); } else { var handler = child.GetWpfFrameworkElement(); var control = handler.ContainerControl; controls[x, y] = child; control.SetValue(swc.Grid.ColumnProperty, x); control.SetValue(swc.Grid.RowProperty, y); SetMargins(control, x, y); SetScale(handler, x, y); Control.Children.Add(control); } UpdatePreferredSize(); } public void Move(Control child, int x, int y) { var handler = child.GetWpfFrameworkElement(); var control = handler.ContainerControl; var oldx = swc.Grid.GetColumn(control); var oldy = swc.Grid.GetRow(control); Remove(x, y); control.SetValue(swc.Grid.ColumnProperty, x); control.SetValue(swc.Grid.RowProperty, y); SetMargins(control, x, y); SetScale(handler, x, y); Control.Children.Add(EmptyCell(oldx, oldy)); controls[x, y] = child; UpdatePreferredSize(); } public void Remove(Control child) { Remove(child.GetContainerControl()); } public override void Remove(sw.FrameworkElement child) { var x = swc.Grid.GetColumn(child); var y = swc.Grid.GetRow(child); Control.Children.Remove(child); controls[x, y] = null; Control.Children.Add(EmptyCell(x, y)); UpdatePreferredSize(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Threading; using System.Windows.Forms; using System.Web; using System.IO; using System.Timers; using System.Net; using MjpegProcessor; namespace ImageProcessing2014 { public unsafe class ImageProcessing { //private static Bitmap image; //private static BitmapData imageData; //private static int imageWidth; //private static int imageHeight; //private static int stride; //private static Stopwatch stopwatch; public static void Init() { Util.Filter.InitializeLookUpTable(); //stopwatch = new Stopwatch(); } public static Goal ProcessImage(Bitmap image) { //stopwatch.Restart(); //long t1 = stopwatch.ElapsedMilliseconds; Console.WriteLine("unlocking bits"); BitmapData imageData = image.LockBits( new Rectangle(0, 0, VisionConstants.Camera.IMAGE_WIDTH, VisionConstants.Camera.IMAGE_HEIGHT), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb ); //long t2 = stopwatch.ElapsedMilliseconds; byte* pScan0 = (byte*)imageData.Scan0.ToPointer(); Console.WriteLine("finding goal"); Goal goal = FindGoal(pScan0, VisionConstants.Camera.IMAGE_STRIDE, VisionConstants.Camera.IMAGE_WIDTH, VisionConstants.Camera.IMAGE_HEIGHT); //Console.Write ("Goal is "); //Console.WriteLine((goal.isHot) ? "not " : ("") + "hot"); Console.WriteLine("Side: " + goal.Side + " | " + "Is Hot: " + goal.isHot + " | " + "Distance: " + goal.Distance + " | " + "Yaw: " + goal.Yaw); //long t3 = stopwatch.ElapsedMilliseconds; // FindBalls(pScan0, VisionConstants.Camera.IMAGE_STRIDE, VisionConstants.Camera.IMAGE_WIDTH, VisionConstants.Camera.IMAGE_HEIGHT); //long t4 = stopwatch.ElapsedMilliseconds; //Pen penViolet = new Pen(Brushes.DarkViolet); //Pen penFuchsia = new Pen(Brushes.Fuchsia);' Console.WriteLine("unlocking bits"); image.UnlockBits(imageData); //long t5 = stopwatch.ElapsedMilliseconds; //Console.WriteLine(t1 + "get " + (t2-t1) + "lock " + (t3-t2) + "goals " + (t4-t3) + "balls " + (t5-t4) "unlock"); //return goal; return null; } public static Goal FindGoal(byte* pScan0, int stride, int imageWidth, int imageHeight) { List<Blob> blobs; PixelTester.PixelTest test = PixelTester.TestGoalPixel; PixelFiller.PixelFill fill = PixelFiller.FillPixel; Byte[] states = new byte[imageWidth * imageHeight]; fixed(byte* pStates = states) { //fill states Util.Filter.FilterGoal(pScan0, pStates, stride, imageWidth, imageHeight); //find blobs blobs = Util.Processing.FindBlobs(pStates, fill, test); Util.Processing.FilterVTBlobs(blobs); // order corners happens here... } //List<List<DoublePoint>> verticalVTs = new List<List<DoublePoint>>(); List<DoublePoint> largestVerticalVT = new List<DoublePoint>(); int pointCount = -1; // VT means Vision Targets List<List<DoublePoint>> horizontalVTs = new List<List<DoublePoint>>(); foreach(Blob blob in blobs) { foreach(Point p in blob.ConvexHull) { //fills the corners of the convex hull (from pX - 1 to pX + 1, pY - 1 to pY + 1) Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, p.X - 1, p.Y - 1, 3, 3, Util.Drawing.RED); } List<DoublePoint> unfisheyedCorners = new List<DoublePoint>(); List<Point> corners = blob.Corners; Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, corners[0].X - 1, corners[0].Y - 1, 3, 3, Util.Drawing.GREEN); unfisheyedCorners.Add(Util.Processing.CorrectFishEye(corners[0])); Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, corners[1].X - 1, corners[1].Y - 1, 3, 3, Util.Drawing.BLUE); unfisheyedCorners.Add(Util.Processing.CorrectFishEye(corners[1])); Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, corners[2].X - 1, corners[2].Y - 1, 3, 3, Util.Drawing.YELLOW); unfisheyedCorners.Add(Util.Processing.CorrectFishEye(corners[2])); Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, corners[3].X - 1, corners[3].Y - 1, 3, 3, Util.Drawing.CYAN); unfisheyedCorners.Add(Util.Processing.CorrectFishEye(corners[3])); /*foreach(Point corner in blob.Corners) { Util.Drawing.FillRectangle(pScan0, stride, imageWidth, imageHeight, corner.X - 1, corner.Y - 1, 3, 3, Util.Drawing.GREEN); unfisheyedCorners.Add(Util.Processing.CorrectFishEye(corner)); }*/ //double dist = Util.Processing.GetDistance(unfisheyedCorners[0], unfisheyedCorners[1], unfisheyedCorners[2], unfisheyedCorners[3], VisionConstants.Field.VisionTargetOrientation.Horizontal); //double angle = Util.Processing.GetAngle(unfisheyedCorners[0], unfisheyedCorners[1], unfisheyedCorners[2], unfisheyedCorners[3]); double x = (unfisheyedCorners[1].X + unfisheyedCorners[3].X - unfisheyedCorners[0].X - unfisheyedCorners[2].X) / 2; double y = (unfisheyedCorners[2].Y + unfisheyedCorners[3].Y - unfisheyedCorners[0].Y - unfisheyedCorners[1].Y) / 2; if(x > y) horizontalVTs.Add(unfisheyedCorners); else if(blob.CalculatePointCount() > pointCount) { //TODO: Make calculatepointcount a property pointCount = blob.CalculatePointCount(); largestVerticalVT = unfisheyedCorners; } } if(pointCount == -1) //haven't found any vertical goals return new Goal(); bool isHot = false; double hotnessThreshold = 1.5*Util.Math.GetDistance(largestVerticalVT[0], largestVerticalVT[1]); Goal.Sides herro = Goal.Sides.Left; foreach(List<DoublePoint> corners in horizontalVTs) { Console.WriteLine("VT DIST: " + Util.Math.GetDistance(corners[2], largestVerticalVT[1])); Console.WriteLine("hotThresh" + hotnessThreshold); if(Util.Math.GetDistance(corners[2], largestVerticalVT[1]) < hotnessThreshold) { isHot = true; herro = Goal.Sides.Right; break; } else if(Util.Math.GetDistance(corners[3], largestVerticalVT[0]) < hotnessThreshold) { isHot = true; herro = Goal.Sides.Left; break; } } double dist = Util.Processing.GetDistance(largestVerticalVT[0], largestVerticalVT[1], largestVerticalVT[2], largestVerticalVT[3], VisionConstants.Field.VisionTargetOrientation.Vertical); double angle = Util.Processing.GetAngle(largestVerticalVT[0], largestVerticalVT[1], largestVerticalVT[2], largestVerticalVT[3]); //something to do with cosines. maybe sines double xGoal = herro == Goal.Sides.Left ? dist*Math.Sin(angle) + VisionConstants.Camera.VT_GOAL_DELTA_X : dist*Math.Sin(angle) - VisionConstants.Camera.VT_GOAL_DELTA_X; double yGoal = dist*Math.Cos(angle); return new Goal(Math.Sqrt(xGoal * xGoal + yGoal * yGoal), Math.Atan2(xGoal, yGoal), herro, isHot); } public static void FindBalls(byte* pScan0, int stride, int imageWidth, int imageHeight) { List<Blob> rBlobs, bBlobs; var states = new byte[imageWidth * imageHeight]; fixed(byte* pStates = states) { //fill states Util.Filter.FilterBall(pScan0, stride, imageWidth, imageHeight, pStates); //find blobs of red and blue PixelFiller.PixelFill fill = PixelFiller.FillColoredPixel; PixelTester.PixelTest test = PixelTester.TestRedPixel; rBlobs = Util.Processing.FindBlobs(pStates, fill, test); test = PixelTester.TestBluePixel; bBlobs = Util.Processing.FindBlobs(pStates, fill, test); #if DEBUG Console.WriteLine("============DEBUG============"); Console.WriteLine("rBlobs contains " + rBlobs.Count); Console.WriteLine("bBlobs contains " + bBlobs.Count); Console.WriteLine("============================"); #endif } //draw bounding boxes // var a = false; // foreach (var blob in wBlobs) { // a = !a; // foreach (Point point in blob) // *(uint*)(pScan0 + point.Y*stride + point.X*4) = a ? 0xFFFF7777 : 0xFF77FF77; // } // foreach(var blob in rBlobs) { // var minX = imageWidth; // var maxX = 0; // int minY = imageHeight; // int maxY = 0; // foreach (LineSegment x in blob.GetLineSegments()) // { // // int y = point.Y; // if (x.leftX < minX) // minX = x.leftX; // if (x.rightX > maxX) // maxX = x.rightX; // } // Console.WriteLine ("minX " + minX + " maxX " + maxX); // var width = maxX - minX; // var theta = ((double)width / imageWidth) * Util.Drawing.H_FOV; // var dist = BALL_WIDTH / (2 * Math.Tan(theta / 2)); // var yposp = (maxX + minX) / 2 - imageWidth / 2; // var ypos = BALL_WIDTH * width / yposp; // var xpos = Math.Sqrt(dist * dist - (ypos * ypos + Util.Drawing.GREEN_CAMERA_HEIGHT * Util.Drawing.GREEN_CAMERA_HEIGHT)); // var zpos = 0.0; // //Console.WriteLine(dist); // //Console.WriteLine(ypos); // Console.WriteLine(xpos + " " + ypos + " " + zpos); // } // foreach (var blob in bBlobs) // { // var minX = imageWidth; // var maxX = 0; // // int minY = imageHeight; // // int maxY = 0; // foreach (LineSegment x in blob.GetLineSegments()) { // // int y = point.Y; // if (x.leftX < minX) // minX = x.leftX; // if (x.leftX > maxX) // maxX = x.leftX; // } // var width = maxX - minX; // var theta = ((double)width / imageWidth) * Util.Drawing.H_FOV; // var dist = BALL_WIDTH / (2 * Math.Tan(theta / 2)); // var yposp = (maxX + minX) / 2 - imageWidth / 2; // var ypos = BALL_WIDTH * width / yposp; // var xpos = Math.Sqrt(dist * dist - (ypos * ypos + Util.Drawing.GREEN_CAMERA_HEIGHT * Util.Drawing.GREEN_CAMERA_HEIGHT)); // var zpos = 0.0; // //Console.WriteLine(dist); // //Console.WriteLine(ypos); // Console.WriteLine(xpos + " " + ypos + " " + zpos); //} } private static Bitmap getImage(string path) { //pictureBox.Load(path); //return (Bitmap)pictureBox.Image; //try { // using(WebClient Client = new WebClient()) { // Client.DownloadFile(path, "image.jpg"); // } //} catch(WebException e) { // Console.WriteLine(e.Status + " | " + e.Message + " | " + e.InnerException); //} //var bytes = File.ReadAllBytes("image.jpg"); //var ms = new MemoryStream(bytes); //var img = (Bitmap)Image.FromStream(ms); ////var img = (Bitmap)Image.FromFile("image.jpg"); //return img; WebRequest requestPic = WebRequest.Create(path); WebResponse responsePic = requestPic.GetResponse(); return (Bitmap)Image.FromStream(responsePic.GetResponseStream()); } } }
using System; using System.Collections.Generic; using System.Linq; using Qwack.Core.Basic; using Qwack.Core.Basic.Correlation; using Qwack.Core.Cubes; using Qwack.Core.Curves; using Qwack.Core.Instruments; using Qwack.Core.Models; using Qwack.Dates; using Qwack.Models.Models; using Qwack.Options.VolSurfaces; using Qwack.Transport.BasicTypes; using Qwack.Transport.TransportObjects.MarketData.Models; namespace Qwack.Models { public class AssetFxModel : IAssetFxModel { private readonly Dictionary<VolSurfaceKey, IVolSurface> _assetVols; private readonly Dictionary<string, IPriceCurve> _assetCurves; private readonly Dictionary<string, IFixingDictionary> _fixings; private DateTime _buildDate; private readonly IFundingModel _fundingModel; public IFundingModel FundingModel => _fundingModel; public DateTime BuildDate => _buildDate; public IPriceCurve[] Curves => _assetCurves.Values.ToArray(); public ICorrelationMatrix CorrelationMatrix { get; set; } public AssetFxModel(DateTime buildDate, IFundingModel fundingModel) { _assetCurves = new Dictionary<string, IPriceCurve>(); _assetVols = new Dictionary<VolSurfaceKey, IVolSurface>(); _fixings = new Dictionary<string, IFixingDictionary>(); _buildDate = buildDate; _fundingModel = fundingModel; } public AssetFxModel(TO_AssetFxModel transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) : this(transportObject.BuildDate, new FundingModel(transportObject.FundingModel, currencyProvider, calendarProvider)) { _assetCurves = transportObject.AssetCurves?.ToDictionary(x => x.Key, x => x.Value.GetPriceCurve(currencyProvider, calendarProvider)) ?? new Dictionary<string, IPriceCurve>(); _assetVols = transportObject.AssetVols?.ToDictionary(x => new VolSurfaceKey(x.Key, currencyProvider), y => VolSurfaceFactory.GetVolSurface(y.Value, currencyProvider)) ?? new Dictionary<VolSurfaceKey, IVolSurface>(); _fixings = transportObject.Fixings?.ToDictionary(x => x.Key, x => (IFixingDictionary)new FixingDictionary(x.Value)) ?? new Dictionary<string, IFixingDictionary>(); CorrelationMatrix = transportObject.CorrelationMatrix==null?null:CorrelationMatrixFactory.GetCorrelationMatrix(transportObject.CorrelationMatrix); } public void AddPriceCurve(string name, IPriceCurve curve) => _assetCurves[name] = curve; public void AddVolSurface(string name, IVolSurface surface) { if (IsFx(name)) FundingModel.VolSurfaces[name] = surface; else _assetVols[new VolSurfaceKey(surface.AssetId, surface.Currency)] = surface; } public void AddVolSurface(VolSurfaceKey key, IVolSurface surface) => _assetVols[key] = surface; public static bool IsFx(string name) => name.Length == 7 && name[3] == '/'; public IPriceCurve GetPriceCurve(string name, Currency currency = null) { if (IsFx(name)) return new FxForwardCurve(BuildDate, FundingModel, FundingModel.GetCurrency(name.Substring(0, 3)), FundingModel.GetCurrency(name.Substring(4, 3))); if (!_assetCurves.TryGetValue(name, out var curve)) throw new Exception($"Curve with name {name} not found"); if (currency != null && curve.Currency != currency) return new CompositePriceCurve(curve.BuildDate, curve, FundingModel, currency); return curve; } public IVolSurface GetVolSurface(string name, Currency currency = null) { if (IsFx(name)) return FundingModel.GetVolSurface(name); if (currency != null) { if (!_assetVols.TryGetValue(new VolSurfaceKey(name,currency), out var surface)) throw new Exception($"Vol surface {name}/{currency} not found"); return surface; } var surfaces = _assetVols.Where(x => name.Contains("~") ? x.Key.ToString() == name : x.Key.AssetId == name); if(!surfaces.Any()) throw new Exception($"Vol surface {name} not found"); return surfaces.First().Value; } public bool TryGetVolSurface(string name, out IVolSurface surface, Currency currency = null) { surface = null; if (IsFx(name)) return FundingModel.TryGetVolSurface(name, out surface); if (currency != null) return _assetVols.TryGetValue(new VolSurfaceKey(name, currency), out surface); surface = _assetVols.Where(x => name.Contains("~") ? x.Key.ToString() == name : x.Key.AssetId == name).FirstOrDefault().Value; return surface != default(IVolSurface); } public void AddFixingDictionary(string name, IFixingDictionary fixings) => _fixings[name] = fixings; public IFixingDictionary GetFixingDictionary(string name) { if (!_fixings.TryGetValue(name, out var dict)) throw new Exception($"Fixing dictionary with name {name} not found"); return dict; } public bool TryGetFixingDictionary(string name, out IFixingDictionary fixings) => _fixings.TryGetValue(name, out fixings); public string[] CurveNames => _assetCurves.Keys.Select(x => x).ToArray(); public string[] VolSurfaceNames => _assetVols.Keys.Select(x => x.AssetId).ToArray(); public string[] FixingDictionaryNames => _fixings.Keys.Select(x => x).ToArray(); public IAssetFxModel VanillaModel => this; public double GetVolForStrikeAndDate(string name, DateTime expiry, double strike) { var surface = GetVolSurface(name); var curve = GetPriceCurve(name); var fwd = surface.OverrideSpotLag == null ? curve.GetPriceForFixingDate(expiry) : curve.GetPriceForDate(expiry.AddPeriod(RollType.F, curve.SpotCalendar, surface.OverrideSpotLag)); var vol = surface.GetVolForAbsoluteStrike(strike, expiry, fwd); return vol; } public double GetVolForDeltaStrikeAndDate(string name, DateTime expiry, double strike) { var fwd = GetPriceCurve(name).GetPriceForFixingDate(expiry); //needs to account for spot/fwd offset var vol = GetVolSurface(name).GetVolForDeltaStrike(strike, expiry, fwd); return vol; } public double GetFxVolForStrikeAndDate(string name, DateTime expiry, double strike) { var pair = FundingModel.FxMatrix.GetFxPair(name); var fwd = FundingModel.GetFxRate(expiry.SpotDate(pair.SpotLag, pair.PrimaryCalendar, pair.PrimaryCalendar), pair.Domestic, pair.Foreign); //needs to account for spot/fwd offset var vol = FundingModel.GetVolSurface(name).GetVolForAbsoluteStrike(strike, expiry, fwd); return vol; } public double GetFxVolForDeltaStrikeAndDate(string name, DateTime expiry, double strike) { var pair = FundingModel.FxMatrix.GetFxPair(name); var fwd = FundingModel.GetFxRate(expiry.SpotDate(pair.SpotLag, pair.PrimaryCalendar, pair.PrimaryCalendar), pair.Domestic, pair.Foreign); //needs to account for spot/fwd offset var vol = FundingModel.GetVolSurface(name).GetVolForDeltaStrike(strike, expiry, fwd); return vol; } public double GetAverageVolForStrikeAndDates(string name, DateTime[] expiries, double strike) { var surface = GetVolSurface(name); var ts = expiries.Select(expiry => _buildDate.CalculateYearFraction(expiry, DayCountBasis.Act365F)).ToArray(); var fwds = expiries.Select(expiry=>_assetCurves[name].GetPriceForDate(expiry)); //needs to account for spot/fwd offset var vols = fwds.Select((fwd,ix)=> surface.GetVolForAbsoluteStrike(strike, expiries[ix], fwd)); var varianceAvg = vols.Select((v, ix) => v * v * ts[ix]).Sum(); varianceAvg /= ts.Sum(); var sigma = System.Math.Sqrt(varianceAvg/ts.Average()); return sigma; } public double GetAverageVolForMoneynessAndDates(string name, DateTime[] expiries, double moneyness) { var surface = GetVolSurface(name); var ts = expiries.Select(expiry => _buildDate.CalculateYearFraction(expiry, DayCountBasis.Act365F)).ToArray(); var fwds = expiries.Select(expiry => _assetCurves[name].GetPriceForDate(expiry)); //needs to account for spot/fwd offset var vols = fwds.Select((fwd, ix) => surface.GetVolForAbsoluteStrike(fwd * moneyness, expiries[ix], fwd)); var variances = vols.Select((v, ix) => v * v * ts[ix]).ToArray(); var varianceWeightedVol = vols.Select((v, ix) => v * variances[ix]).Sum()/variances.Sum(); return varianceWeightedVol; } public double GetCompositeVolForStrikeAndDate(string assetId, DateTime expiry, double strike, Currency ccy) { var curve = GetPriceCurve(assetId); if (curve.Currency == ccy) return GetVolForStrikeAndDate(assetId, expiry, strike); var fxId = $"{curve.Currency.Ccy}/{ccy.Ccy}"; var fxPair = FundingModel.FxMatrix.GetFxPair(fxId); var fxSpotDate = fxPair.SpotDate(expiry); var fxFwd = FundingModel.GetFxRate(fxSpotDate, fxId); var fxVol = FundingModel.GetVolSurface(fxId).GetVolForDeltaStrike(0.5, expiry, fxFwd); var tExpC = BuildDate.CalculateYearFraction(expiry, DayCountBasis.Act365F); var correl = CorrelationMatrix?.GetCorrelation(fxId, assetId, tExpC) ?? 0.0; var sigma = GetVolForStrikeAndDate(assetId, expiry, strike / fxFwd); sigma = System.Math.Sqrt(sigma * sigma + fxVol * fxVol + 2 * correl * fxVol * sigma); return sigma; } public IAssetFxModel Clone() { var c = new AssetFxModel(BuildDate, FundingModel.DeepClone(null)); foreach (var kv in _assetCurves) c.AddPriceCurve(kv.Key, kv.Value); foreach (var kv in _assetVols) c.AddVolSurface(kv.Key, kv.Value); foreach (var kv in _fixings) c.AddFixingDictionary(kv.Key, kv.Value); c.CorrelationMatrix = CorrelationMatrix; c.AttachPortfolio(_portfolio); return c; } public IAssetFxModel Clone(IFundingModel fundingModel) { var c = new AssetFxModel(BuildDate, fundingModel); foreach (var kv in _assetCurves) c.AddPriceCurve(kv.Key, kv.Value); foreach (var kv in _assetVols) c.AddVolSurface(kv.Key, kv.Value); foreach (var kv in _fixings) c.AddFixingDictionary(kv.Key, kv.Value); c.CorrelationMatrix = CorrelationMatrix; c.AttachPortfolio(_portfolio); return c; } public void AddPriceCurves(Dictionary<string, IPriceCurve> curves) { foreach (var kv in curves) _assetCurves[kv.Key] = kv.Value; } public void AddVolSurfaces(Dictionary<string, IVolSurface> surfaces) { foreach (var kv in surfaces) AddVolSurface(new VolSurfaceKey(kv.Value.AssetId, kv.Value.Currency), kv.Value); } public void AddFixingDictionaries(Dictionary<string, IFixingDictionary> fixings) { foreach (var kv in fixings) _fixings[kv.Key] = kv.Value; } private Portfolio _portfolio; public Portfolio Portfolio => _portfolio; public void AttachPortfolio(Portfolio portfolio) => _portfolio = portfolio; public ICube PV(Currency reportingCurrency) => _portfolio.PV(this, reportingCurrency); public IPvModel Rebuild(IAssetFxModel newVanillaModel, Portfolio portfolio) { var m = newVanillaModel.Clone(); m.AttachPortfolio(portfolio); return m; } private Dictionary<string, string[]> _dependencyTree; private Dictionary<string, string[]> _dependencyTreeFull; public void BuildDependencyTree() { if (_dependencyTree != null) return; _dependencyTree = new Dictionary<string, string[]>(); _dependencyTreeFull = new Dictionary<string, string[]>(); foreach (var curveName in CurveNames) { var curveObj = GetPriceCurve(curveName); var linkedCurves = Curves .Where(x => x is BasisPriceCurve bp && bp.BaseCurve.Name == curveName) .Select(x => x.Name) .ToArray(); _dependencyTree.Add(curveName, linkedCurves); } foreach(var kv in _dependencyTree) { var fullDeps = kv.Value; var newDeps = new List<string>(); foreach(var dep in kv.Value) { if(_dependencyTree.TryGetValue(dep, out var deps)) { newDeps.AddRange(deps); } } while(newDeps.Any()) { var actualNewDeps = newDeps.Where(x => !fullDeps.Contains(x)); fullDeps = fullDeps.Concat(actualNewDeps).Distinct().ToArray(); newDeps = new List<string>(); foreach (var dep in actualNewDeps) { if (_dependencyTree.TryGetValue(dep, out var deps)) { newDeps.AddRange(deps); } } } _dependencyTreeFull.Add(kv.Key, fullDeps); } } public string[] GetDependentCurves(string curve) => _dependencyTree.TryGetValue(curve, out var values) ? values : throw new Exception($"Curve {curve} not found"); public string[] GetAllDependentCurves(string curve) => _dependencyTreeFull.TryGetValue(curve, out var values) ? values : throw new Exception($"Curve {curve} not found"); public void OverrideBuildDate(DateTime buildDate) => _buildDate = buildDate; public TO_AssetFxModel ToTransportObject() => new() { AssetCurves = _assetCurves?.ToDictionary(x=>x.Key,x=>x.Value.GetTransportObject()), AssetVols = _assetVols?.ToDictionary(x=>x.Key.GetTransportObject(),x=>x.Value.GetTransportObject()), BuildDate = BuildDate, CorrelationMatrix = CorrelationMatrix?.GetTransportObject(), Fixings = _fixings?.ToDictionary(x=>x.Key,x=>x.Value.GetTransportObject()), FundingModel = _fundingModel.GetTransportObject(), Portfolio = _portfolio?.ToTransportObject(), }; public void RemovePriceCurve(IPriceCurve curve) => _assetCurves.Remove(curve.Name); public void RemoveVolSurface(IVolSurface surface) { var key = new VolSurfaceKey(surface.AssetId, surface.Currency); _assetVols.Remove(key); } public void RemoveFixingDictionary(string name) => _fixings.Remove(name); public IAssetFxModel TrimModel(Portfolio portfolio, string[] additionalIrCurves = null, string[] additionalCcys = null) { var o = Clone(); var assetIds = portfolio.AssetIds(); var pairs = portfolio.FxPairs(o); var ccys = pairs.SelectMany(x => x.Split('/')).Distinct().ToArray(); if(additionalCcys!=null) { ccys = ccys.Concat(additionalCcys).Distinct().ToArray(); } var irCurves = portfolio.Instruments .Where(x => x is IAssetInstrument).SelectMany(x => (x as IAssetInstrument).IrCurves(o)) .Concat(ccys.Select(c=>o.FundingModel.FxMatrix.DiscountCurveMap.Single(dc=>dc.Key.Ccy==c).Value)) .Distinct() .ToArray(); var surplusCurves = o.CurveNames.Where(x => !assetIds.Contains(x)).ToArray(); var surplusVols = o.VolSurfaceNames.Where(x => !assetIds.Contains(x)).ToArray(); var surplusFixings = o.FixingDictionaryNames.Where(x => !assetIds.Contains(x) && !pairs.Contains(x)).ToArray(); var surplusIrCurves = o.FundingModel.Curves.Keys.Where(x => !irCurves.Contains(x)).ToArray(); if(additionalIrCurves!=null) { surplusIrCurves = surplusIrCurves.Where(ir => !additionalIrCurves.Contains(ir)).ToArray(); } var surplusFxRates = o.FundingModel.FxMatrix.SpotRates.Keys.Where(x => !ccys.Contains(x.Ccy)).ToArray(); foreach (var s in surplusCurves) { o.RemovePriceCurve(o.GetPriceCurve(s)); } foreach (var s in surplusVols) { o.RemoveVolSurface(o.GetVolSurface(s)); } foreach (var s in surplusFixings) { o.RemoveFixingDictionary(s); } foreach (var s in surplusIrCurves) { o.FundingModel.Curves.Remove(s); } foreach (var s in surplusFxRates) { o.FundingModel.FxMatrix.SpotRates.Remove(s); } return o; } public double GetCorrelation(string label1, string label2, double t = 0) { if (CorrelationMatrix == null) throw new Exception("No correlation matrix attached to model"); return CorrelationMatrix.GetCorrelation(label1, label2, t); } } }
// <copyright file="SqlClientTests.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Data; using System.Diagnostics; using System.Linq; using Microsoft.Data.SqlClient; using Moq; using OpenTelemetry.Instrumentation.SqlClient.Implementation; using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Instrumentation.SqlClient.Tests { public class SqlClientTests : IDisposable { /* To run the integration tests, set the OTEL_SQLCONNECTIONSTRING machine-level environment variable to a valid Sql Server connection string. To use Docker... 1) Run: docker run -d --name sql2019 -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Pass@word" -p 5433:1433 mcr.microsoft.com/mssql/server:2019-latest 2) Set OTEL_SQLCONNECTIONSTRING as: Data Source=127.0.0.1,5433; User ID=sa; Password=Pass@word */ private const string SqlConnectionStringEnvVarName = "OTEL_SQLCONNECTIONSTRING"; private const string TestConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Database=master"; private static readonly string SqlConnectionString = SkipUnlessEnvVarFoundTheoryAttribute.GetEnvironmentVariable(SqlConnectionStringEnvVarName); private readonly FakeSqlClientDiagnosticSource fakeSqlClientDiagnosticSource; public SqlClientTests() { this.fakeSqlClientDiagnosticSource = new FakeSqlClientDiagnosticSource(); } public void Dispose() { this.fakeSqlClientDiagnosticSource.Dispose(); } [Fact] public void SqlClient_BadArgs() { TracerProviderBuilder builder = null; Assert.Throws<ArgumentNullException>(() => builder.AddSqlClientInstrumentation()); } [Trait("CategoryName", "SqlIntegrationTests")] [SkipUnlessEnvVarFoundTheory(SqlConnectionStringEnvVarName)] [InlineData(CommandType.Text, "select 1/1", false)] #if !NETFRAMEWORK [InlineData(CommandType.Text, "select 1/1", false, true)] #endif [InlineData(CommandType.Text, "select 1/0", false, false, true)] [InlineData(CommandType.Text, "select 1/0", false, false, true, false, false)] [InlineData(CommandType.Text, "select 1/0", false, false, true, true, false)] [InlineData(CommandType.StoredProcedure, "sp_who", false)] [InlineData(CommandType.StoredProcedure, "sp_who", true)] public void SuccessfulCommandTest( CommandType commandType, string commandText, bool captureStoredProcedureCommandName, bool captureTextCommandContent = false, bool isFailure = false, bool recordException = false, bool shouldEnrich = true) { var activityProcessor = new Mock<BaseProcessor<Activity>>(); activityProcessor.Setup(x => x.OnStart(It.IsAny<Activity>())).Callback<Activity>(c => c.SetTag("enriched", "no")); var sampler = new TestSampler(); using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddProcessor(activityProcessor.Object) .SetSampler(sampler) .AddSqlClientInstrumentation(options => { #if !NETFRAMEWORK options.SetDbStatementForStoredProcedure = captureStoredProcedureCommandName; options.SetDbStatementForText = captureTextCommandContent; options.RecordException = recordException; #else options.SetDbStatement = captureStoredProcedureCommandName; #endif if (shouldEnrich) { options.Enrich = ActivityEnrichment; } }) .Build(); #if NETFRAMEWORK // RecordException not available on netfx recordException = false; #endif using SqlConnection sqlConnection = new SqlConnection(SqlConnectionString); sqlConnection.Open(); string dataSource = sqlConnection.DataSource; sqlConnection.ChangeDatabase("master"); using SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection) { CommandType = commandType, }; try { sqlCommand.ExecuteNonQuery(); } catch { } Assert.Equal(3, activityProcessor.Invocations.Count); var activity = (Activity)activityProcessor.Invocations[1].Arguments[0]; VerifyActivityData(commandType, commandText, captureStoredProcedureCommandName, captureTextCommandContent, isFailure, recordException, shouldEnrich, dataSource, activity); VerifySamplingParameters(sampler.LatestSamplingParameters); } // DiagnosticListener-based instrumentation is only available on .NET Core #if !NETFRAMEWORK [Theory] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataAfterExecuteCommand, CommandType.StoredProcedure, "SP_GetOrders", true, false)] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataAfterExecuteCommand, CommandType.StoredProcedure, "SP_GetOrders", true, false, false)] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataAfterExecuteCommand, CommandType.Text, "select * from sys.databases", true, false)] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataAfterExecuteCommand, CommandType.Text, "select * from sys.databases", true, false, false)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftAfterExecuteCommand, CommandType.StoredProcedure, "SP_GetOrders", false, true)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftAfterExecuteCommand, CommandType.StoredProcedure, "SP_GetOrders", false, true, false)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftAfterExecuteCommand, CommandType.Text, "select * from sys.databases", false, true)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftAfterExecuteCommand, CommandType.Text, "select * from sys.databases", false, true, false)] public void SqlClientCallsAreCollectedSuccessfully( string beforeCommand, string afterCommand, CommandType commandType, string commandText, bool captureStoredProcedureCommandName, bool captureTextCommandContent, bool shouldEnrich = true) { using var sqlConnection = new SqlConnection(TestConnectionString); using var sqlCommand = sqlConnection.CreateCommand(); var processor = new Mock<BaseProcessor<Activity>>(); processor.Setup(x => x.OnStart(It.IsAny<Activity>())).Callback<Activity>(c => c.SetTag("enriched", "no")); using (Sdk.CreateTracerProviderBuilder() .AddSqlClientInstrumentation( (opt) => { opt.SetDbStatementForText = captureTextCommandContent; opt.SetDbStatementForStoredProcedure = captureStoredProcedureCommandName; if (shouldEnrich) { opt.Enrich = ActivityEnrichment; } }) .AddProcessor(processor.Object) .Build()) { var operationId = Guid.NewGuid(); sqlCommand.CommandType = commandType; sqlCommand.CommandText = commandText; var beforeExecuteEventData = new { OperationId = operationId, Command = sqlCommand, Timestamp = (long?)1000000L, }; this.fakeSqlClientDiagnosticSource.Write( beforeCommand, beforeExecuteEventData); var afterExecuteEventData = new { OperationId = operationId, Command = sqlCommand, Timestamp = 2000000L, }; this.fakeSqlClientDiagnosticSource.Write( afterCommand, afterExecuteEventData); } Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called. VerifyActivityData( sqlCommand.CommandType, sqlCommand.CommandText, captureStoredProcedureCommandName, captureTextCommandContent, false, false, shouldEnrich, sqlConnection.DataSource, (Activity)processor.Invocations[2].Arguments[0]); } [Theory] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataWriteCommandError)] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataWriteCommandError, false)] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand, SqlClientDiagnosticListener.SqlDataWriteCommandError, false, true)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftWriteCommandError)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftWriteCommandError, false)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand, SqlClientDiagnosticListener.SqlMicrosoftWriteCommandError, false, true)] public void SqlClientErrorsAreCollectedSuccessfully(string beforeCommand, string errorCommand, bool shouldEnrich = true, bool recordException = false) { using var sqlConnection = new SqlConnection(TestConnectionString); using var sqlCommand = sqlConnection.CreateCommand(); var processor = new Mock<BaseProcessor<Activity>>(); processor.Setup(x => x.OnStart(It.IsAny<Activity>())).Callback<Activity>(c => c.SetTag("enriched", "no")); using (Sdk.CreateTracerProviderBuilder() .AddSqlClientInstrumentation(options => { options.RecordException = recordException; if (shouldEnrich) { options.Enrich = ActivityEnrichment; } }) .AddProcessor(processor.Object) .Build()) { var operationId = Guid.NewGuid(); sqlCommand.CommandText = "SP_GetOrders"; sqlCommand.CommandType = CommandType.StoredProcedure; var beforeExecuteEventData = new { OperationId = operationId, Command = sqlCommand, Timestamp = (long?)1000000L, }; this.fakeSqlClientDiagnosticSource.Write( beforeCommand, beforeExecuteEventData); var commandErrorEventData = new { OperationId = operationId, Command = sqlCommand, Exception = new Exception("Boom!"), Timestamp = 2000000L, }; this.fakeSqlClientDiagnosticSource.Write( errorCommand, commandErrorEventData); } Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called. VerifyActivityData( sqlCommand.CommandType, sqlCommand.CommandText, true, false, true, recordException, shouldEnrich, sqlConnection.DataSource, (Activity)processor.Invocations[2].Arguments[0]); } [Theory] [InlineData(SqlClientDiagnosticListener.SqlDataBeforeExecuteCommand)] [InlineData(SqlClientDiagnosticListener.SqlMicrosoftBeforeExecuteCommand)] public void SqlClientCreatesActivityWithDbSystem( string beforeCommand) { using var sqlConnection = new SqlConnection(TestConnectionString); using var sqlCommand = sqlConnection.CreateCommand(); var sampler = new TestSampler { SamplingAction = _ => new SamplingResult(SamplingDecision.Drop), }; using (Sdk.CreateTracerProviderBuilder() .AddSqlClientInstrumentation() .SetSampler(sampler) .Build()) { this.fakeSqlClientDiagnosticSource.Write(beforeCommand, new { }); } VerifySamplingParameters(sampler.LatestSamplingParameters); } #endif private static void VerifyActivityData( CommandType commandType, string commandText, bool captureStoredProcedureCommandName, bool captureTextCommandContent, bool isFailure, bool recordException, bool shouldEnrich, string dataSource, Activity activity) { Assert.Equal("master", activity.DisplayName); Assert.Equal(ActivityKind.Client, activity.Kind); if (!isFailure) { Assert.Equal(Status.Unset, activity.GetStatus()); } else { var status = activity.GetStatus(); Assert.Equal(Status.Error.StatusCode, status.StatusCode); Assert.NotNull(status.Description); if (recordException) { var events = activity.Events.ToList(); Assert.Single(events); Assert.Equal(SemanticConventions.AttributeExceptionEventName, events[0].Name); } else { Assert.Empty(activity.Events); } } Assert.NotEmpty(activity.Tags.Where(tag => tag.Key == "enriched")); Assert.Equal(shouldEnrich ? "yes" : "no", activity.Tags.Where(tag => tag.Key == "enriched").FirstOrDefault().Value); Assert.Equal(SqlActivitySourceHelper.MicrosoftSqlServerDatabaseSystemName, activity.GetTagValue(SemanticConventions.AttributeDbSystem)); Assert.Equal("master", activity.GetTagValue(SemanticConventions.AttributeDbName)); switch (commandType) { case CommandType.StoredProcedure: if (captureStoredProcedureCommandName) { Assert.Equal(commandText, activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } else { Assert.Null(activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } break; case CommandType.Text: if (captureTextCommandContent) { Assert.Equal(commandText, activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } else { Assert.Null(activity.GetTagValue(SemanticConventions.AttributeDbStatement)); } break; } Assert.Equal(dataSource, activity.GetTagValue(SemanticConventions.AttributePeerService)); } private static void VerifySamplingParameters(SamplingParameters samplingParameters) { Assert.NotNull(samplingParameters.Tags); Assert.Contains( samplingParameters.Tags, kvp => kvp.Key == SemanticConventions.AttributeDbSystem && (string)kvp.Value == SqlActivitySourceHelper.MicrosoftSqlServerDatabaseSystemName); } private static void ActivityEnrichment(Activity activity, string method, object obj) { Assert.NotEmpty(activity.Tags.Where(tag => tag.Key == "enriched")); Assert.Equal("no", activity.Tags.Where(tag => tag.Key == "enriched").FirstOrDefault().Value); activity.SetTag("enriched", "yes"); switch (method) { case "OnCustom": Assert.True(obj is SqlCommand); break; default: break; } } private class FakeSqlClientDiagnosticSource : IDisposable { private readonly DiagnosticListener listener; public FakeSqlClientDiagnosticSource() { this.listener = new DiagnosticListener(SqlClientInstrumentation.SqlClientDiagnosticListenerName); } public void Write(string name, object value) { this.listener.Write(name, value); } public void Dispose() { this.listener.Dispose(); } } } }
#region Apache Notice /***************************************************************************** * $Revision: 476843 $ * $LastChangedDate: 2006-11-19 17:07:45 +0100 (dim., 19 nov. 2006) $ * $LastChangedBy: gbayon $ * * iBATIS.NET Data Mapper * Copyright (C) 2006/2005 - The Apache Software Foundation * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System.Collections; using System.Text; using IBatisNet.DataMapper.Configuration.Statements; using IBatisNet.DataMapper.DataExchange; using IBatisNet.DataMapper.MappedStatements; using IBatisNet.DataMapper.Scope; using IBatisNet.DataMapper.Exceptions; using IBatisNet.Common.Utilities; using IBatisNet.Common.Utilities.Objects; namespace IBatisNet.DataMapper.Configuration.Sql.SimpleDynamic { /// <summary> /// SimpleDynamicSql. /// </summary> internal sealed class SimpleDynamicSql : ISql { #region private private const string ELEMENT_TOKEN = "$"; private string _simpleSqlStatement = string.Empty; private IStatement _statement = null; private DataExchangeFactory _dataExchangeFactory = null; #endregion #region Constructor (s) / Destructor /// <summary> /// Initializes a new instance of the <see cref="SimpleDynamicSql"/> class. /// </summary> /// <param name="scope">The scope.</param> /// <param name="sqlStatement">The SQL statement.</param> /// <param name="statement">The statement.</param> internal SimpleDynamicSql(IScope scope, string sqlStatement, IStatement statement) { _simpleSqlStatement = sqlStatement; _statement = statement; _dataExchangeFactory = scope.DataExchangeFactory; } #endregion #region Methods /// <summary> /// /// </summary> /// <param name="parameterObject"></param> /// <returns></returns> public string GetSql(object parameterObject) { return ProcessDynamicElements(parameterObject); } /// <summary> /// /// </summary> /// <param name="sqlStatement"></param> /// <returns></returns> public static bool IsSimpleDynamicSql(string sqlStatement) { return ((sqlStatement != null) && (sqlStatement.IndexOf(ELEMENT_TOKEN) > -1)); } /// <summary> /// /// </summary> /// <param name="parameterObject"></param> /// <returns></returns> private string ProcessDynamicElements(object parameterObject) { // define which character is seperating fields StringTokenizer parser = new StringTokenizer(_simpleSqlStatement, ELEMENT_TOKEN, true); StringBuilder newSql = new StringBuilder(); string token = null; string lastToken = null; IEnumerator enumerator = parser.GetEnumerator(); while (enumerator.MoveNext()) { token = ((string)enumerator.Current); if (ELEMENT_TOKEN.Equals(lastToken)) { if (ELEMENT_TOKEN.Equals(token)) { newSql.Append(ELEMENT_TOKEN); token = null; } else { object value = null; if (parameterObject != null) { if (_dataExchangeFactory.TypeHandlerFactory.IsSimpleType(parameterObject.GetType()) == true) { value = parameterObject; } else { value = ObjectProbe.GetMemberValue(parameterObject, token, _dataExchangeFactory.AccessorFactory); } } if (value != null) { newSql.Append(value.ToString()); } enumerator.MoveNext(); token = ((string)enumerator.Current); if (!ELEMENT_TOKEN.Equals(token)) { throw new DataMapperException("Unterminated dynamic element in sql (" + _simpleSqlStatement + ")."); } token = null; } } else { if (!ELEMENT_TOKEN.Equals(token)) { newSql.Append(token); } } lastToken = token; } return newSql.ToString(); } #region ISql Members /// <summary> /// Builds a new <see cref="RequestScope"/> and the sql command text to execute. /// </summary> /// <param name="parameterObject">The parameter object (used in DynamicSql)</param> /// <param name="session">The current session</param> /// <param name="mappedStatement">The <see cref="IMappedStatement"/>.</param> /// <returns>A new <see cref="RequestScope"/>.</returns> public RequestScope GetRequestScope(IMappedStatement mappedStatement, object parameterObject, ISqlMapSession session) { string sqlStatement = ProcessDynamicElements(parameterObject); RequestScope request = new RequestScope(_dataExchangeFactory, session, _statement); request.PreparedStatement = BuildPreparedStatement(session, request, sqlStatement); request.MappedStatement = mappedStatement; return request; } /// <summary> /// Build the PreparedStatement /// </summary> /// <param name="session"></param> /// <param name="request"></param> /// <param name="sqlStatement"></param> private PreparedStatement BuildPreparedStatement(ISqlMapSession session, RequestScope request, string sqlStatement) { PreparedStatementFactory factory = new PreparedStatementFactory(session, request, _statement, sqlStatement); return factory.Prepare(); } #endregion #endregion } }
using System; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.Drawing.Imaging; using JustGestures.GestureParts; using JustGestures.Languages; namespace JustGestures.GUI { using ControlItems; public partial class Form_addGesture : Form { BaseActionControl m_currentControl; UC_actions uc_actions; UC_name uc_name; UC_gesture uc_gesture; UC_openPrgFld uc_openPrgFld; UC_mailSearchWeb uc_mailSearchWeb; UC_customKeystrokes uc_customKeystrokes; UC_selectProgram uc_selectProgram; UC_plainText uc_plainText; UC_clipboard uc_clipboard; List<MyGesture> m_newGestures; MyGesture m_tempGesture; GesturesCollection m_gestures; MyNeuralNetwork m_network; bool m_appMode = false; List<MyGesture> m_selectedGroups; public Form_addGesture() { InitializeComponent(); MyInitializing(); } public bool AppMode { set { m_appMode = value; } } public GesturesCollection Gestures { //get { return gestures; } set { m_gestures = value; } } public List<MyGesture> NewGestures { get { return m_newGestures; } } public MyNeuralNetwork MyNNetwork { get { return m_network; } set { m_network = value; } } public List<MyGesture> SelectedGroups { set { m_selectedGroups = value; } } private void MyInitializing() { typeof(GroupBox).InvokeMember("DoubleBuffered", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic, null, groupBox_MainPanel, new object[] { true }); this.FormBorderStyle = FormBorderStyle.Fixed3D; m_tempGesture = new MyGesture(string.Empty); m_newGestures = new List<MyGesture>(); m_selectedGroups = new List<MyGesture>(); #region User Control Declaration uc_openPrgFld = new UC_openPrgFld(); uc_actions = new UC_actions(); uc_name = new UC_name(); uc_gesture = new UC_gesture(); uc_customKeystrokes = new UC_customKeystrokes(); uc_selectProgram = new UC_selectProgram(); uc_plainText = new UC_plainText(); uc_clipboard = new UC_clipboard(); uc_mailSearchWeb = new UC_mailSearchWeb(); groupBox_MainPanel.Controls.Add(uc_actions); groupBox_MainPanel.Controls.Add(uc_name); groupBox_MainPanel.Controls.Add(uc_gesture); groupBox_MainPanel.Controls.Add(uc_openPrgFld); groupBox_MainPanel.Controls.Add(uc_customKeystrokes); groupBox_MainPanel.Controls.Add(uc_selectProgram); groupBox_MainPanel.Controls.Add(uc_plainText); groupBox_MainPanel.Controls.Add(uc_clipboard); groupBox_MainPanel.Controls.Add(uc_mailSearchWeb); foreach (BaseActionControl myControl in groupBox_MainPanel.Controls) { myControl.Dock = DockStyle.Fill; myControl.TempGesture = m_tempGesture; myControl.CanContinue += new BaseActionControl.DlgCanContinue(Continue); myControl.ChangeAboutText += new BaseActionControl.DlgChangeAboutText(ChangeAboutText); myControl.ChangeInfoText += new BaseActionControl.DlgChangeInfoText(uC_infoIcon1.ChangeInfoText); myControl.Visible = false; } #endregion User Control Declaration btn_back.Text = Translation.Btn_back; btn_cancel.Text = Translation.Btn_cancel; btn_next.Text = Translation.Btn_next; } private void Form_addGesture_Load(object sender, EventArgs e) { if (!m_appMode) { this.Text = Translation.GetText("AG_caption"); this.Icon = Properties.Resources.add_gesture16; uc_gesture.MyNNetwork = m_network; uc_gesture.Gestures = m_gestures; uc_name.Gestures = m_gestures; uc_actions.Gestures = m_gestures; uc_actions.SelectedGroups = m_selectedGroups; m_currentControl = uc_actions; uc_clipboard.Gestures = m_gestures; this.Size = new Size(680, 580); } else { this.Text = Translation.GetText("AA_caption"); this.Icon = Properties.Resources.add_app16; btn_back.Visible = false; m_currentControl = uc_selectProgram; this.Size = new Size(530, 430); } this.MinimumSize = this.MaximumSize = this.Size; m_currentControl.Show(); MoveToPage(m_currentControl.Identifier); } private void MoveToPage(BaseActionControl.Page page) { m_currentControl.Hide(); btn_next.Enabled = false; btn_back.Enabled = true; switch (page) { case BaseActionControl.Page.Action: m_currentControl = uc_actions; break; case BaseActionControl.Page.PrgWwwFld: m_currentControl = uc_openPrgFld; break; case BaseActionControl.Page.MailSearchWeb: m_currentControl = uc_mailSearchWeb; break; case BaseActionControl.Page.Keystrokes: m_currentControl = uc_customKeystrokes; break; case BaseActionControl.Page.Gesture: m_currentControl = uc_gesture; uc_gesture.Previous = uc_actions.Next == uc_gesture.Identifier ? uc_actions.Identifier : uc_actions.Next; break; case BaseActionControl.Page.Name: m_currentControl = uc_name; break; case BaseActionControl.Page.Application: m_currentControl = uc_selectProgram; break; case BaseActionControl.Page.PlainText: m_currentControl = uc_plainText; break; case BaseActionControl.Page.Clipboard: m_currentControl = uc_clipboard; break; } m_currentControl.Show(); if (m_currentControl.Next != BaseActionControl.Page.None) { btn_next.DialogResult = DialogResult.None; btn_next.Text = Translation.Btn_next; } else { btn_next.DialogResult = DialogResult.OK; if (!m_appMode) btn_next.Text = Translation.Btn_finish; else btn_next.Text = Translation.Btn_add; } if (m_currentControl.Previous == BaseActionControl.Page.None) { btn_back.Enabled = false; } } private void button_cancel_Click(object sender, EventArgs e) { this.Close(); } private void ChangeAboutText(string title) { StringFormat strFormat = new StringFormat(); strFormat.LineAlignment = StringAlignment.Center; //strFormat.Alignment = StringAlignment.Center; Font strFont = new Font(FontFamily.GenericSansSerif, 11, FontStyle.Bold); Rectangle r = new Rectangle(0, 0, pB_about.Width, pB_about.Height); Bitmap bmp = new Bitmap(pB_about.Width, pB_about.Height); Graphics gp = Graphics.FromImage(bmp); gp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; Pen pen = new Pen(Brushes.Gray, 1); gp.FillRectangle(new SolidBrush(pB_about.BackColor), r); int height = pB_about.Height - 12; int offset = pB_about.Height; gp.DrawImage(Properties.Resources.logo32, pB_about.Width - offset, 6, height, height); //gp.DrawLine(pen, 0, 0, pB_about.Width, 0); gp.DrawLine(new Pen(Brushes.Gray, 1), 0, pB_about.Height - 2, pB_about.Width, pB_about.Height - 2); //gp.DrawLine(new Pen(Brushes.Black, 1), 0, pB_about.Height - 2, pB_about.Width, pB_about.Height - 2); gp.DrawLine(new Pen(Brushes.White, 1), 0, pB_about.Height - 1, pB_about.Width, pB_about.Height - 1); r.X += 10; //r.Width -= 6; r.Y += 2; r.Height -= 7; gp.DrawString(title, strFont, Brushes.Black, r, strFormat); gp.Dispose(); pB_about.Image = bmp; } private void Continue(bool _continue) { btn_next.Enabled = _continue; } private void button_next_Click(object sender, EventArgs e) { if (btn_next.DialogResult == DialogResult.OK) { if (!m_appMode) { m_network = uc_gesture.MyNNetwork; foreach (MyGesture group in uc_actions.NewGroups) m_newGestures.Add(group); foreach (MyGesture group in uc_actions.SelectedGroups) { string id = MyGesture.CreateUniqueId(m_tempGesture, m_gestures); MyGesture gest = new MyGesture(id); gest.SetItem(m_tempGesture); gest.Activator = m_tempGesture.Activator; gest.Action = m_tempGesture.Action; gest.AppGroup = group; m_newGestures.Add(gest); m_gestures.Add(gest); } } else { string id = MyGesture.CreateUniqueId(m_tempGesture, m_gestures); MyGesture gest = new MyGesture(id); gest.SetItem(m_tempGesture); gest.Action = m_tempGesture.Action; gest.Activator = new MouseActivator(string.Empty, MouseActivator.Types.Undefined); m_newGestures.Add(gest); } } MoveToPage(m_currentControl.Next); } private void button_back_Click(object sender, EventArgs e) { MoveToPage(m_currentControl.Previous); } private void Form_addGesture_FormClosing(object sender, FormClosingEventArgs e) { if (!m_appMode) { uc_gesture.OnClosingForm(this.DialogResult); uc_openPrgFld.OnClosingForm(); uc_mailSearchWeb.OnClosingForm(); } else uc_selectProgram.OnClosingForm(); } private void panel_ForButtons_Paint(object sender, PaintEventArgs e) { Graphics g = panel_ForButtons.CreateGraphics(); g.DrawLine(new Pen(Brushes.Gray, 1), 0, 2, panel_ForButtons.Width, 2); //g.DrawLine(new Pen(Brushes.Black, 1), 0, 2, panel_ForButtons.Width, 2); g.DrawLine(new Pen(Brushes.White, 1), 0, 1, panel_ForButtons.Width, 1); g.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace JS_Test.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.Reflection.Internal { [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal unsafe struct MemoryBlock { internal readonly byte* Pointer; internal readonly int Length; internal MemoryBlock(byte* buffer, int length) { Debug.Assert(length >= 0 && (buffer != null || length == 0)); this.Pointer = buffer; this.Length = length; } internal static MemoryBlock CreateChecked(byte* buffer, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if (buffer == null && length != 0) { throw new ArgumentNullException("buffer"); } // the reader performs little-endian specific operations if (!BitConverter.IsLittleEndian) { throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired); } return new MemoryBlock(buffer, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBounds(int offset, int byteCount) { if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length) { Throw.OutOfBounds(); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void ThrowValueOverflow() { throw new BadImageFormatException(SR.ValueTooLarge); } internal byte[] ToArray() { return Pointer == null ? null : PeekBytes(0, Length); } private string GetDebuggerDisplay() { if (Pointer == null) { return "<null>"; } int displayedBytes; return GetDebuggerDisplay(out displayedBytes); } internal string GetDebuggerDisplay(out int displayedBytes) { displayedBytes = Math.Min(Length, 64); string result = BitConverter.ToString(PeekBytes(0, displayedBytes)); if (displayedBytes < Length) { result += "-..."; } return result; } internal string GetDebuggerDisplay(int offset) { if (Pointer == null) { return "<null>"; } int displayedBytes; string display = GetDebuggerDisplay(out displayedBytes); if (offset < displayedBytes) { display = display.Insert(offset * 3, "*"); } else if (displayedBytes == Length) { display += "*"; } else { display += "*..."; } return display; } internal MemoryBlock GetMemoryBlockAt(int offset, int length) { CheckBounds(offset, length); return new MemoryBlock(Pointer + offset, length); } internal byte PeekByte(int offset) { CheckBounds(offset, sizeof(byte)); return Pointer[offset]; } internal int PeekInt32(int offset) { uint result = PeekUInt32(offset); if (unchecked((int)result != result)) { ThrowValueOverflow(); } return (int)result; } internal uint PeekUInt32(int offset) { CheckBounds(offset, sizeof(uint)); return *(uint*)(Pointer + offset); } /// <summary> /// Decodes a compressed integer value starting at offset. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <param name="offset">Offset to the start of the compressed data.</param> /// <param name="numberOfBytesRead">Bytes actually read.</param> /// <returns> /// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid. /// </returns> internal int PeekCompressedInteger(int offset, out int numberOfBytesRead) { CheckBounds(offset, 0); byte* ptr = Pointer + offset; long limit = Length - offset; if (limit == 0) { numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } byte headerByte = ptr[0]; if ((headerByte & 0x80) == 0) { numberOfBytesRead = 1; return headerByte; } else if ((headerByte & 0x40) == 0) { if (limit >= 2) { numberOfBytesRead = 2; return ((headerByte & 0x3f) << 8) | ptr[1]; } } else if ((headerByte & 0x20) == 0) { if (limit >= 4) { numberOfBytesRead = 4; return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; } } numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } internal ushort PeekUInt16(int offset) { CheckBounds(offset, sizeof(ushort)); return *(ushort*)(Pointer + offset); } // When reference has tag bits. internal uint PeekTaggedReference(int offset, bool smallRefSize) { return PeekReferenceUnchecked(offset, smallRefSize); } // Use when searching for a tagged or non-tagged reference. // The result may be an invalid reference and shall only be used to compare with a valid reference. internal uint PeekReferenceUnchecked(int offset, bool smallRefSize) { return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset); } // When reference has at most 24 bits. internal int PeekReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!TokenTypeIds.IsValidRowId(value)) { Throw.ReferenceOverflow(); } return (int)value; } // #String, #Blob heaps internal int PeekHeapReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!HeapHandleType.IsValidHeapOffset(value)) { Throw.ReferenceOverflow(); } return (int)value; } internal Guid PeekGuid(int offset) { CheckBounds(offset, sizeof(Guid)); return *(Guid*)(Pointer + offset); } internal string PeekUtf16(int offset, int byteCount) { CheckBounds(offset, byteCount); // doesn't allocate a new string if byteCount == 0 return new string((char*)(Pointer + offset), 0, byteCount / sizeof(char)); } internal string PeekUtf8(int offset, int byteCount) { CheckBounds(offset, byteCount); return Encoding.UTF8.GetString(Pointer + offset, byteCount); } /// <summary> /// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param> /// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <returns>The decoded string.</returns> internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0') { Debug.Assert(terminator <= 0x7F); CheckBounds(offset, 0); int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator); return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder); } /// <summary> /// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first). /// Returned length does not include the terminator, but numberOfBytesRead out parameter does. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <returns>Length (byte count) not including terminator.</returns> internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0') { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7f); byte* start = Pointer + offset; byte* end = Pointer + Length; byte* current = start; while (current < end) { byte b = *current; if (b == 0 || b == terminator) { break; } current++; } int length = (int)(current - start); numberOfBytesRead = length; if (current < end) { // we also read the terminator numberOfBytesRead++; } return length; } internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar) { CheckBounds(startOffset, 0); Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); for (int i = startOffset; i < Length; i++) { byte b = Pointer[i]; if (b == 0) { break; } if (b == asciiChar) { return i; } } return -1; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int firstDifference; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase); if (result == FastComparisonResult.Inconclusive) { int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return result == FastComparisonResult.Equal; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int endIndex; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase); switch (result) { case FastComparisonResult.Equal: case FastComparisonResult.BytesStartWithText: return true; case FastComparisonResult.Unequal: case FastComparisonResult.TextStartsWithBytes: return false; default: Debug.Assert(result == FastComparisonResult.Inconclusive); int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } internal enum FastComparisonResult { Equal, BytesStartWithText, TextStartsWithBytes, Unequal, Inconclusive } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase) { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7F); byte* startPointer = Pointer + offset; byte* endPointer = Pointer + Length; byte* currentPointer = startPointer; int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); int currentIndex = textStart; while (currentIndex < text.Length && currentPointer != endPointer) { byte currentByte = *currentPointer; // note that terminator is not compared case-insensitively even if ignore case is true if (currentByte == 0 || currentByte == terminator) { break; } char currentChar = text[currentIndex]; if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask)) { currentIndex++; currentPointer++; } else { firstDifferenceIndex = currentIndex; // uncommon non-ascii case --> fall back to slow allocating comparison. return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal; } } firstDifferenceIndex = currentIndex; bool textTerminated = currentIndex == text.Length; bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator; if (textTerminated && bytesTerminated) { return FastComparisonResult.Equal; } return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); // Make sure that we won't read beyond the block even if the block doesn't end with 0 byte. if (asciiPrefix.Length > Length - offset) { return false; } byte* p = Pointer + offset; for (int i = 0; i < asciiPrefix.Length; i++) { Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f); if (asciiPrefix[i] != *p) { return false; } p++; } return true; } internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); byte* p = Pointer + offset; int limit = Length - offset; for (int i = 0; i < asciiString.Length; i++) { Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f); if (i > limit) { // Heap value is shorter. return -1; } if (*p != asciiString[i]) { // If we hit the end of the heap value (*p == 0) // the heap value is shorter than the string, so we return negative value. return *p - asciiString[i]; } p++; } // Either the heap value name matches exactly the given string or // it is longer so it is considered "greater". return (*p == 0) ? 0 : +1; } internal byte[] PeekBytes(int offset, int byteCount) { CheckBounds(offset, byteCount); if (byteCount == 0) { return EmptyArray<byte>.Instance; } byte[] result = new byte[byteCount]; Marshal.Copy((IntPtr)(Pointer + offset), result, 0, byteCount); return result; } internal int IndexOf(byte b, int start) { CheckBounds(start, 0); byte* p = Pointer + start; byte* end = Pointer + Length; while (p < end) { if (*p == b) { return (int)(p - Pointer); } p++; } return -1; } // same as Array.BinarySearch, but without using IComparer internal int BinarySearch(string[] asciiKeys, int offset) { var low = 0; var high = asciiKeys.Length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = asciiKeys[middle]; int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue); if (comparison == 0) { return middle; } if (comparison < 0) { high = middle - 1; } else { low = middle + 1; } } return ~low; } /// <summary> /// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList), /// seaches for the parent given a reference to a child. /// </summary> /// <returns>Returns row number [0..RowCount).</returns> internal int BinarySearchForSlot( int rowCount, int rowSize, int referenceListOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall); uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (endRowNumber == 1) { if (referenceValue >= endValue) { return endRowNumber; } return startRowNumber; } while (endRowNumber - startRowNumber > 1) { if (referenceValue <= startValue) { return referenceValue == startValue ? startRowNumber : startRowNumber - 1; } if (referenceValue >= endValue) { return referenceValue == endValue ? endRowNumber : endRowNumber + 1; } int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber; startValue = midReferenceValue; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber; endValue = midReferenceValue; } else { return midRowNumber; } } return startRowNumber; } /// <summary> /// In a table ordered by a column containing entity references seaches for a row with the specified reference. /// </summary> /// <returns>Returns row number [0..RowCount) or -1 if not found.</returns> internal int BinarySearchReference( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } // Row number [0, ptrTable.Length) or -1 if not found. internal int BinarySearchReference( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = ptrTable.Length - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, rowCount) or -1 out int endRowNumber) // [0, rowCount) or -1 { int foundRowNumber = BinarySearchReference( rowCount, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < rowCount && PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, ptrTable.Length) or -1 out int endRowNumber) // [0, ptrTable.Length) or -1 { int foundRowNumber = BinarySearchReference( ptrTable, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < ptrTable.Length && PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } // Always RowNumber.... internal int LinearSearchReference( int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int currOffset = referenceOffset; int totalSize = this.Length; while (currOffset < totalSize) { uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall); if (currReference == referenceValue) { return currOffset / rowSize; } currOffset += rowSize; } return -1; } internal bool IsOrderedByReferenceAscending( int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; uint previous = 0; while (offset < totalSize) { uint current = PeekReferenceUnchecked(offset, isReferenceSmall); if (current < previous) { return false; } previous = current; offset += rowSize; } return true; } internal int[] BuildPtrTable( int numberOfRows, int rowSize, int referenceOffset, bool isReferenceSmall) { int[] ptrTable = new int[numberOfRows]; uint[] unsortedReferences = new uint[numberOfRows]; for (int i = 0; i < ptrTable.Length; i++) { ptrTable[i] = i + 1; } ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall); Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); }); return ptrTable; } private void ReadColumn( uint[] result, int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; int i = 0; while (offset < totalSize) { result[i] = PeekReferenceUnchecked(offset, isReferenceSmall); offset += rowSize; i++; } Debug.Assert(i == result.Length); } internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size) { int bytesRead; int numberOfBytes = PeekCompressedInteger(index, out bytesRead); if (numberOfBytes == BlobReader.InvalidCompressedInteger) { offset = 0; size = 0; return false; } offset = index + bytesRead; size = numberOfBytes; return true; } } }
// // Job.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Threading; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Hyena.Jobs { public enum JobState { None, Scheduled, Running, Paused, Cancelled, Completed }; public class Job { public event EventHandler Updated; public event EventHandler Finished; public event EventHandler CancelRequested; private int update_freeze_ref; private JobState state = JobState.None; private ManualResetEvent pause_event; private DateTime created_at = DateTime.Now; private TimeSpan run_time = TimeSpan.Zero; private Object sync = new Object (); public bool IsCancelRequested { get; private set; } #region Internal Properties internal bool IsScheduled { get { return state == JobState.Scheduled; } } internal bool IsRunning { get { return state == JobState.Running; } } internal bool IsPaused { get { return state == JobState.Paused; } } public bool IsFinished { get { lock (sync) { return state == JobState.Cancelled || state == JobState.Completed; } } } internal DateTime CreatedAt { get { return created_at; } } internal TimeSpan RunTime { get { return run_time; } } #endregion #region Scheduler Methods internal void Start () { Log.Debug ("Starting", Title); lock (sync) { if (state != JobState.Scheduled && state != JobState.Paused) { Log.DebugFormat ("Job {0} in {1} state is not runnable", Title, state); return; } State = JobState.Running; if (pause_event != null) { pause_event.Set (); } RunJob (); } } internal void Cancel () { lock (sync) { if (!IsFinished) { IsCancelRequested = true; State = JobState.Cancelled; EventHandler handler = CancelRequested; if (handler != null) { handler (this, EventArgs.Empty); } } } Log.Debug ("Canceled", Title); } internal void Preempt () { Log.Debug ("Preemptd", Title); Pause (false); } internal bool Pause () { Log.Debug ("Pausing ", Title); return Pause (true); } private bool Pause (bool unschedule) { lock (sync) { if (IsFinished) { Log.DebugFormat ("Job {0} in {1} state is not pausable", Title, state); return false; } State = unschedule ? JobState.Paused : JobState.Scheduled; if (pause_event != null) { pause_event.Reset (); } } return true; } #endregion private string title; private string status; private string [] icon_names; private double progress; #region Public Properties public string Title { get { return title; } set { title = value; OnUpdated (); } } public string Status { get { return status; } set { status = value; OnUpdated (); } } public double Progress { get { return progress; } set { progress = Math.Max (0.0, Math.Min (1.0, value)); OnUpdated (); } } public string [] IconNames { get { return icon_names; } set { if (value != null) { icon_names = value; OnUpdated (); } } } public bool IsBackground { get; set; } public bool CanCancel { get; set; } public string CancelMessage { get; set; } public bool DelayShow { get; set; } public PriorityHints PriorityHints { get; set; } // Causes runtime method-not-found error in mono 2.0.1 //public IEnumerable<Resource> Resources { get; protected set; } internal Resource [] Resources; public JobState State { get { return state; } internal set { state = value; OnUpdated (); } } public void SetResources (params Resource [] resources) { Resources = resources; } #endregion #region Constructor public Job () : this (null, PriorityHints.None) { } public Job (string title, PriorityHints hints, params Resource [] resources) { Title = title; PriorityHints = hints; Resources = resources; } #endregion #region Abstract Methods protected virtual void RunJob () { } #endregion #region Protected Methods public void Update (string title, string status, double progress) { Title = title; Status = status; Progress = progress; } protected void FreezeUpdate () { System.Threading.Interlocked.Increment (ref update_freeze_ref); } protected void ThawUpdate (bool raiseUpdate) { System.Threading.Interlocked.Decrement (ref update_freeze_ref); if (raiseUpdate) { OnUpdated (); } } protected void OnUpdated () { if (update_freeze_ref != 0) { return; } EventHandler handler = Updated; if (handler != null) { handler (this, EventArgs.Empty); } } public void YieldToScheduler () { if (IsPaused || IsScheduled) { if (pause_event == null) { pause_event = new ManualResetEvent (false); } pause_event.WaitOne (); } } protected void OnFinished () { Log.Debug ("Finished", Title); pause_event = null; if (state != JobState.Cancelled) { State = JobState.Completed; } EventHandler handler = Finished; if (handler != null) { handler (this, EventArgs.Empty); } } #endregion internal bool HasScheduler { get; set; } } }
// // Copyright (c) 2004-2021 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 { using System; using System.Collections.Generic; using Xunit; public class LogLevelTests : NLogTestBase { [Fact] [Trait("Component", "Core")] public void OrdinalTest() { Assert.True(LogLevel.Trace < LogLevel.Debug); Assert.True(LogLevel.Debug < LogLevel.Info); Assert.True(LogLevel.Info < LogLevel.Warn); Assert.True(LogLevel.Warn < LogLevel.Error); Assert.True(LogLevel.Error < LogLevel.Fatal); Assert.True(LogLevel.Fatal < LogLevel.Off); Assert.False(LogLevel.Trace > LogLevel.Debug); Assert.False(LogLevel.Debug > LogLevel.Info); Assert.False(LogLevel.Info > LogLevel.Warn); Assert.False(LogLevel.Warn > LogLevel.Error); Assert.False(LogLevel.Error > LogLevel.Fatal); Assert.False(LogLevel.Fatal > LogLevel.Off); Assert.True(LogLevel.Trace <= LogLevel.Debug); Assert.True(LogLevel.Debug <= LogLevel.Info); Assert.True(LogLevel.Info <= LogLevel.Warn); Assert.True(LogLevel.Warn <= LogLevel.Error); Assert.True(LogLevel.Error <= LogLevel.Fatal); Assert.True(LogLevel.Fatal <= LogLevel.Off); Assert.False(LogLevel.Trace >= LogLevel.Debug); Assert.False(LogLevel.Debug >= LogLevel.Info); Assert.False(LogLevel.Info >= LogLevel.Warn); Assert.False(LogLevel.Warn >= LogLevel.Error); Assert.False(LogLevel.Error >= LogLevel.Fatal); Assert.False(LogLevel.Fatal >= LogLevel.Off); } [Fact] [Trait("Component", "Core")] public void LogLevelEqualityTest() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelInfo = LogLevel.Info; Assert.True(LogLevel.Trace == levelTrace); Assert.True(LogLevel.Info == levelInfo); Assert.False(LogLevel.Trace == levelInfo); Assert.False(LogLevel.Trace != levelTrace); Assert.False(LogLevel.Info != levelInfo); Assert.True(LogLevel.Trace != levelInfo); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputInRange_ExpectValidLevel() { Assert.Same(LogLevel.FromOrdinal(0), LogLevel.Trace); Assert.Same(LogLevel.FromOrdinal(1), LogLevel.Debug); Assert.Same(LogLevel.FromOrdinal(2), LogLevel.Info); Assert.Same(LogLevel.FromOrdinal(3), LogLevel.Warn); Assert.Same(LogLevel.FromOrdinal(4), LogLevel.Error); Assert.Same(LogLevel.FromOrdinal(5), LogLevel.Fatal); Assert.Same(LogLevel.FromOrdinal(6), LogLevel.Off); } [Fact] [Trait("Component", "Core")] public void LogLevelFromOrdinal_InputOutOfRange_ExpectException() { Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(100)); // Boundary conditions. Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(-1)); Assert.Throws<ArgumentException>(() => LogLevel.FromOrdinal(7)); } [Fact] [Trait("Component", "Core")] public void FromStringTest() { Assert.Same(LogLevel.FromString("trace"), LogLevel.Trace); Assert.Same(LogLevel.FromString("debug"), LogLevel.Debug); Assert.Same(LogLevel.FromString("info"), LogLevel.Info); Assert.Same(LogLevel.FromString("warn"), LogLevel.Warn); Assert.Same(LogLevel.FromString("error"), LogLevel.Error); Assert.Same(LogLevel.FromString("fatal"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("off"), LogLevel.Off); Assert.Same(LogLevel.FromString("Trace"), LogLevel.Trace); Assert.Same(LogLevel.FromString("Debug"), LogLevel.Debug); Assert.Same(LogLevel.FromString("Info"), LogLevel.Info); Assert.Same(LogLevel.FromString("Warn"), LogLevel.Warn); Assert.Same(LogLevel.FromString("Error"), LogLevel.Error); Assert.Same(LogLevel.FromString("Fatal"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("Off"), LogLevel.Off); Assert.Same(LogLevel.FromString("TracE"), LogLevel.Trace); Assert.Same(LogLevel.FromString("DebuG"), LogLevel.Debug); Assert.Same(LogLevel.FromString("InfO"), LogLevel.Info); Assert.Same(LogLevel.FromString("WarN"), LogLevel.Warn); Assert.Same(LogLevel.FromString("ErroR"), LogLevel.Error); Assert.Same(LogLevel.FromString("FataL"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("TRACE"), LogLevel.Trace); Assert.Same(LogLevel.FromString("DEBUG"), LogLevel.Debug); Assert.Same(LogLevel.FromString("INFO"), LogLevel.Info); Assert.Same(LogLevel.FromString("WARN"), LogLevel.Warn); Assert.Same(LogLevel.FromString("ERROR"), LogLevel.Error); Assert.Same(LogLevel.FromString("FATAL"), LogLevel.Fatal); Assert.Same(LogLevel.FromString("NoNe"), LogLevel.Off); Assert.Same(LogLevel.FromString("iNformaTION"), LogLevel.Info); Assert.Same(LogLevel.FromString("WarNING"), LogLevel.Warn); } [Fact] [Trait("Component", "Core")] public void FromStringFailingTest() { Assert.Throws<ArgumentException>(() => LogLevel.FromString("zzz")); Assert.Throws<ArgumentException>(() => LogLevel.FromString(string.Empty)); Assert.Throws<ArgumentNullException>(() => LogLevel.FromString(null)); } [Fact] [Trait("Component", "Core")] public void LogLevelNullComparison() { LogLevel level = LogLevel.Info; Assert.False(level is null); Assert.True(level != null); Assert.False(null == level); Assert.True(null != level); level = null; Assert.True(level is null); Assert.False(level != null); Assert.True(null == level); Assert.False(null != level); } [Fact] [Trait("Component", "Core")] public void ToStringTest() { Assert.Equal("Trace", LogLevel.Trace.ToString()); Assert.Equal("Debug", LogLevel.Debug.ToString()); Assert.Equal("Info", LogLevel.Info.ToString()); Assert.Equal("Warn", LogLevel.Warn.ToString()); Assert.Equal("Error", LogLevel.Error.ToString()); Assert.Equal("Fatal", LogLevel.Fatal.ToString()); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_ValidLevels_ExpectIntValues() { LogLevel levelTrace = LogLevel.Trace; LogLevel levelDebug = LogLevel.Debug; LogLevel levelInfo = LogLevel.Info; LogLevel levelWarn = LogLevel.Warn; LogLevel levelError = LogLevel.Error; LogLevel levelFatal = LogLevel.Fatal; LogLevel levelOff = LogLevel.Off; LogLevel levelMin = LogLevel.MinLevel; LogLevel levelMax = LogLevel.MaxLevel; Assert.Equal(LogLevel.Trace.CompareTo(levelDebug), -1); Assert.Equal(LogLevel.Debug.CompareTo(levelInfo), -1); Assert.Equal(LogLevel.Info.CompareTo(levelWarn), -1); Assert.Equal(LogLevel.Warn.CompareTo(levelError), -1); Assert.Equal(LogLevel.Error.CompareTo(levelFatal), -1); Assert.Equal(LogLevel.Fatal.CompareTo(levelOff), -1); Assert.Equal(1, LogLevel.Debug.CompareTo(levelTrace)); Assert.Equal(1, LogLevel.Info.CompareTo(levelDebug)); Assert.Equal(1, LogLevel.Warn.CompareTo(levelInfo)); Assert.Equal(1, LogLevel.Error.CompareTo(levelWarn)); Assert.Equal(1, LogLevel.Fatal.CompareTo(levelError)); Assert.Equal(1, LogLevel.Off.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Debug.CompareTo(levelDebug)); Assert.Equal(0, LogLevel.Info.CompareTo(levelInfo)); Assert.Equal(0, LogLevel.Warn.CompareTo(levelWarn)); Assert.Equal(0, LogLevel.Error.CompareTo(levelError)); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelFatal)); Assert.Equal(0, LogLevel.Off.CompareTo(levelOff)); Assert.Equal(0, LogLevel.Trace.CompareTo(levelMin)); Assert.Equal(1, LogLevel.Debug.CompareTo(levelMin)); Assert.Equal(2, LogLevel.Info.CompareTo(levelMin)); Assert.Equal(3, LogLevel.Warn.CompareTo(levelMin)); Assert.Equal(4, LogLevel.Error.CompareTo(levelMin)); Assert.Equal(5, LogLevel.Fatal.CompareTo(levelMin)); Assert.Equal(6, LogLevel.Off.CompareTo(levelMin)); Assert.Equal(LogLevel.Trace.CompareTo(levelMax), -5); Assert.Equal(LogLevel.Debug.CompareTo(levelMax), -4); Assert.Equal(LogLevel.Info.CompareTo(levelMax), -3); Assert.Equal(LogLevel.Warn.CompareTo(levelMax), -2); Assert.Equal(LogLevel.Error.CompareTo(levelMax), -1); Assert.Equal(0, LogLevel.Fatal.CompareTo(levelMax)); Assert.Equal(1, LogLevel.Off.CompareTo(levelMax)); } [Fact] [Trait("Component", "Core")] public void LogLevelCompareTo_Null_ExpectLevelOff() { Assert.True(LogLevel.MinLevel.CompareTo(null) < 0); Assert.True(LogLevel.MaxLevel.CompareTo(null) < 0); Assert.True(LogLevel.Off.CompareTo(null) == 0); } [Fact] [Trait("Component", "Core")] public void LogLevel_MinMaxLevels_ExpectConstantValues() { Assert.Same(LogLevel.Trace, LogLevel.MinLevel); Assert.Same(LogLevel.Fatal, LogLevel.MaxLevel); } [Fact] [Trait("Component", "Core")] public void LogLevelGetHashCode() { Assert.Equal(0, LogLevel.Trace.GetHashCode()); Assert.Equal(1, LogLevel.Debug.GetHashCode()); Assert.Equal(2, LogLevel.Info.GetHashCode()); Assert.Equal(3, LogLevel.Warn.GetHashCode()); Assert.Equal(4, LogLevel.Error.GetHashCode()); Assert.Equal(5, LogLevel.Fatal.GetHashCode()); Assert.Equal(6, LogLevel.Off.GetHashCode()); } [Fact] [Trait("Component", "Core")] public void LogLevelEquals_Null_ExpectFalse() { Assert.False(LogLevel.Debug.Equals(null)); LogLevel logLevel = null; Assert.False(LogLevel.Debug.Equals(logLevel)); Object obj = logLevel; Assert.False(LogLevel.Debug.Equals(obj)); } [Fact] public void LogLevelEqual_TypeOfObject() { // Objects of any other type should always return false. Assert.False(LogLevel.Debug.Equals((int) 1)); Assert.False(LogLevel.Debug.Equals((string)"Debug")); // Valid LogLevel objects boxed as Object type. Object levelTrace = LogLevel.Trace; Object levelDebug = LogLevel.Debug; Object levelInfo = LogLevel.Info; Object levelWarn = LogLevel.Warn; Object levelError = LogLevel.Error; Object levelFatal = LogLevel.Fatal; Object levelOff = LogLevel.Off; Assert.False(LogLevel.Warn.Equals(levelTrace)); Assert.False(LogLevel.Warn.Equals(levelDebug)); Assert.False(LogLevel.Warn.Equals(levelInfo)); Assert.True(LogLevel.Warn.Equals(levelWarn)); Assert.False(LogLevel.Warn.Equals(levelError)); Assert.False(LogLevel.Warn.Equals(levelFatal)); Assert.False(LogLevel.Warn.Equals(levelOff)); } [Fact] public void LogLevelEqual_TypeOfLogLevel() { Assert.False(LogLevel.Warn.Equals(LogLevel.Trace)); Assert.False(LogLevel.Warn.Equals(LogLevel.Debug)); Assert.False(LogLevel.Warn.Equals(LogLevel.Info)); Assert.True(LogLevel.Warn.Equals(LogLevel.Warn)); Assert.False(LogLevel.Warn.Equals(LogLevel.Error)); Assert.False(LogLevel.Warn.Equals(LogLevel.Fatal)); Assert.False(LogLevel.Warn.Equals(LogLevel.Off)); } [Fact] public void LogLevel_GetAllLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal, LogLevel.Off }, LogLevel.AllLevels); } [Fact] public void LogLevel_SetAllLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>) LogLevel.AllLevels).Add(LogLevel.Fatal)); } [Fact] public void LogLevel_GetAllLoggingLevels() { Assert.Equal( new List<LogLevel>() { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }, LogLevel.AllLoggingLevels); } [Fact] public void LogLevel_SetAllLoggingLevels() { Assert.Throws<NotSupportedException>(() => ((ICollection<LogLevel>)LogLevel.AllLoggingLevels).Add(LogLevel.Fatal)); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedSecurityPoliciesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSecurityPolicyRequest request = new GetSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicy expectedResponse = new SecurityPolicy { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Rules = { new SecurityPolicyRule(), }, AdaptiveProtectionConfig = new SecurityPolicyAdaptiveProtectionConfig(), Fingerprint = "fingerprint009e6052", Description = "description2cf9da67", AdvancedOptionsConfig = new SecurityPolicyAdvancedOptionsConfig(), SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicy response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSecurityPolicyRequest request = new GetSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicy expectedResponse = new SecurityPolicy { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Rules = { new SecurityPolicyRule(), }, AdaptiveProtectionConfig = new SecurityPolicyAdaptiveProtectionConfig(), Fingerprint = "fingerprint009e6052", Description = "description2cf9da67", AdvancedOptionsConfig = new SecurityPolicyAdvancedOptionsConfig(), SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicy responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPolicy responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSecurityPolicyRequest request = new GetSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicy expectedResponse = new SecurityPolicy { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Rules = { new SecurityPolicyRule(), }, AdaptiveProtectionConfig = new SecurityPolicyAdaptiveProtectionConfig(), Fingerprint = "fingerprint009e6052", Description = "description2cf9da67", AdvancedOptionsConfig = new SecurityPolicyAdvancedOptionsConfig(), SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicy response = client.Get(request.Project, request.SecurityPolicy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSecurityPolicyRequest request = new GetSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicy expectedResponse = new SecurityPolicy { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Rules = { new SecurityPolicyRule(), }, AdaptiveProtectionConfig = new SecurityPolicyAdaptiveProtectionConfig(), Fingerprint = "fingerprint009e6052", Description = "description2cf9da67", AdvancedOptionsConfig = new SecurityPolicyAdvancedOptionsConfig(), SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicy responseCallSettings = await client.GetAsync(request.Project, request.SecurityPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPolicy responseCancellationToken = await client.GetAsync(request.Project, request.SecurityPolicy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRuleRequestObject() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", Priority = 1546225849, }; SecurityPolicyRule expectedResponse = new SecurityPolicyRule { Kind = "kindf7aa39d9", Match = new SecurityPolicyRuleMatcher(), Action = "action09558c41", Preview = true, Description = "description2cf9da67", Priority = 1546225849, }; mockGrpcClient.Setup(x => x.GetRule(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicyRule response = client.GetRule(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRuleRequestObjectAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", Priority = 1546225849, }; SecurityPolicyRule expectedResponse = new SecurityPolicyRule { Kind = "kindf7aa39d9", Match = new SecurityPolicyRuleMatcher(), Action = "action09558c41", Preview = true, Description = "description2cf9da67", Priority = 1546225849, }; mockGrpcClient.Setup(x => x.GetRuleAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPolicyRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicyRule responseCallSettings = await client.GetRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPolicyRule responseCancellationToken = await client.GetRuleAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRule() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicyRule expectedResponse = new SecurityPolicyRule { Kind = "kindf7aa39d9", Match = new SecurityPolicyRuleMatcher(), Action = "action09558c41", Preview = true, Description = "description2cf9da67", Priority = 1546225849, }; mockGrpcClient.Setup(x => x.GetRule(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicyRule response = client.GetRule(request.Project, request.SecurityPolicy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRuleAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuleSecurityPolicyRequest request = new GetRuleSecurityPolicyRequest { SecurityPolicy = "security_policy76596315", Project = "projectaa6ff846", }; SecurityPolicyRule expectedResponse = new SecurityPolicyRule { Kind = "kindf7aa39d9", Match = new SecurityPolicyRuleMatcher(), Action = "action09558c41", Preview = true, Description = "description2cf9da67", Priority = 1546225849, }; mockGrpcClient.Setup(x => x.GetRuleAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPolicyRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPolicyRule responseCallSettings = await client.GetRuleAsync(request.Project, request.SecurityPolicy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPolicyRule responseCancellationToken = await client.GetRuleAsync(request.Project, request.SecurityPolicy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ListPreconfiguredExpressionSetsRequestObject() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest { PageToken = "page_tokenf09e5538", MaxResults = 2806814450U, OrderBy = "order_byb4d33ada", Project = "projectaa6ff846", Filter = "filtere47ac9b2", ReturnPartialSuccess = false, }; SecurityPoliciesListPreconfiguredExpressionSetsResponse expectedResponse = new SecurityPoliciesListPreconfiguredExpressionSetsResponse { PreconfiguredExpressionSets = new SecurityPoliciesWafConfig(), }; mockGrpcClient.Setup(x => x.ListPreconfiguredExpressionSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPoliciesListPreconfiguredExpressionSetsResponse response = client.ListPreconfiguredExpressionSets(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListPreconfiguredExpressionSetsRequestObjectAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest { PageToken = "page_tokenf09e5538", MaxResults = 2806814450U, OrderBy = "order_byb4d33ada", Project = "projectaa6ff846", Filter = "filtere47ac9b2", ReturnPartialSuccess = false, }; SecurityPoliciesListPreconfiguredExpressionSetsResponse expectedResponse = new SecurityPoliciesListPreconfiguredExpressionSetsResponse { PreconfiguredExpressionSets = new SecurityPoliciesWafConfig(), }; mockGrpcClient.Setup(x => x.ListPreconfiguredExpressionSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPoliciesListPreconfiguredExpressionSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPoliciesListPreconfiguredExpressionSetsResponse responseCallSettings = await client.ListPreconfiguredExpressionSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPoliciesListPreconfiguredExpressionSetsResponse responseCancellationToken = await client.ListPreconfiguredExpressionSetsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ListPreconfiguredExpressionSets() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest { Project = "projectaa6ff846", }; SecurityPoliciesListPreconfiguredExpressionSetsResponse expectedResponse = new SecurityPoliciesListPreconfiguredExpressionSetsResponse { PreconfiguredExpressionSets = new SecurityPoliciesWafConfig(), }; mockGrpcClient.Setup(x => x.ListPreconfiguredExpressionSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPoliciesListPreconfiguredExpressionSetsResponse response = client.ListPreconfiguredExpressionSets(request.Project); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ListPreconfiguredExpressionSetsAsync() { moq::Mock<SecurityPolicies.SecurityPoliciesClient> mockGrpcClient = new moq::Mock<SecurityPolicies.SecurityPoliciesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ListPreconfiguredExpressionSetsSecurityPoliciesRequest request = new ListPreconfiguredExpressionSetsSecurityPoliciesRequest { Project = "projectaa6ff846", }; SecurityPoliciesListPreconfiguredExpressionSetsResponse expectedResponse = new SecurityPoliciesListPreconfiguredExpressionSetsResponse { PreconfiguredExpressionSets = new SecurityPoliciesWafConfig(), }; mockGrpcClient.Setup(x => x.ListPreconfiguredExpressionSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SecurityPoliciesListPreconfiguredExpressionSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); SecurityPoliciesClient client = new SecurityPoliciesClientImpl(mockGrpcClient.Object, null); SecurityPoliciesListPreconfiguredExpressionSetsResponse responseCallSettings = await client.ListPreconfiguredExpressionSetsAsync(request.Project, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SecurityPoliciesListPreconfiguredExpressionSetsResponse responseCancellationToken = await client.ListPreconfiguredExpressionSetsAsync(request.Project, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Eto.Wpf.CustomControls { /// <summary> /// An image that supports multiple sizes depending on its own rendering size. /// </summary> /// <remarks> /// Extends the standard <see cref="Image"/> control with the functionality to /// load all the available frames in its <see cref="Image.Source"/> and render the one /// that best matches the current rendering size of the control. /// /// For example, if the Source is a TIFF file containing frames of sizes 24x24, 48x48 and 128x128 /// and the image is rendered at size 40x40, the frame with resolution 48x48 is used. /// The same control with the same source rendered at 24x24 would use the 24x24 frame. /// /// <para>Written by Isak Savo - isak.savo@gmail.com, (c) 2011-2012. Licensed under the Code Project </para> /// </remarks> public class MultiSizeImage : Image { Brush background; bool useSmallestSpace; public Brush Background { get { return background; } set { if (background != value) { background = value; InvalidateVisual(); } } } public bool UseSmallestSpace { get { return useSmallestSpace; } set { if (useSmallestSpace != value) { useSmallestSpace = value; InvalidateMeasure(); } } } static MultiSizeImage() { // Tell WPF to inform us whenever the Source dependency property is changed SourceProperty.OverrideMetadata(typeof(MultiSizeImage), new FrameworkPropertyMetadata(HandleSourceChanged)); } static void HandleSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var img = (MultiSizeImage)sender; img.UpdateAvailableFrames(); } /// <summary> /// List containing one frame of every size available in the original file. The frame /// stored in this list is the one with the highest pixel depth for that size. /// </summary> readonly List<BitmapSource> _availableFrames = new List<BitmapSource>(); /// <summary> /// Gets the pixel depth (in bits per pixel, bpp) of the specified frame /// </summary> /// <param name="frame">The frame to get BPP for</param> /// <returns>The number of bits per pixel in the frame</returns> static int GetFramePixelDepth(BitmapFrame frame) { if (frame.Decoder.CodecInfo.ContainerFormat == new Guid("{a3a860c4-338f-4c17-919a-fba4b5628f21}") && frame.Thumbnail != null) { // Windows Icon format, original pixel depth is in the thumbnail return frame.Thumbnail.Format.BitsPerPixel; } // Other formats, just assume the frame has the correct BPP info return frame.Format.BitsPerPixel; } protected override Size ArrangeOverride(Size arrangeSize) { return MeasureArrangeHelper(arrangeSize); } protected override Size MeasureOverride(Size constraint) { return MeasureArrangeHelper(constraint); } static bool IsZero(double value) { return Math.Abs(value) < 2.2204460492503131E-15; } static Size ComputeScaleFactor(Size availableSize, Size contentSize, Stretch stretch, StretchDirection stretchDirection) { double widthFactor = 1.0; double heightFactor = 1.0; bool widthSet = !double.IsPositiveInfinity(availableSize.Width); bool heightSet = !double.IsPositiveInfinity(availableSize.Height); if ((stretch == Stretch.Uniform || stretch == Stretch.UniformToFill || stretch == Stretch.Fill) && (widthSet || heightSet)) { widthFactor = (IsZero(contentSize.Width) ? 0.0 : (availableSize.Width / contentSize.Width)); heightFactor = (IsZero(contentSize.Height) ? 0.0 : (availableSize.Height / contentSize.Height)); if (!widthSet) widthFactor = heightFactor; else { if (!heightSet) heightFactor = widthFactor; else { switch (stretch) { case Stretch.Uniform: { double num3 = (widthFactor < heightFactor) ? widthFactor : heightFactor; heightFactor = (widthFactor = num3); break; } case Stretch.UniformToFill: { double num4 = (widthFactor > heightFactor) ? widthFactor : heightFactor; heightFactor = (widthFactor = num4); break; } } } } switch (stretchDirection) { case StretchDirection.UpOnly: if (widthFactor < 1.0) widthFactor = 1.0; if (heightFactor < 1.0) heightFactor = 1.0; break; case StretchDirection.DownOnly: if (widthFactor > 1.0) widthFactor = 1.0; if (heightFactor > 1.0) heightFactor = 1.0; break; } } return new Size(widthFactor, heightFactor); } Size MeasureArrangeHelper(Size inputSize) { if (Source == null) return new Size(0, 0); var first = _availableFrames.LastOrDefault(); var size = new Size(Source.Width, Source.Height); if (first == null) return size; size = new Size(first.Width, first.Height); Size scale = ComputeScaleFactor(inputSize, size, Stretch, StretchDirection); if (UseSmallestSpace) { if (double.IsPositiveInfinity(inputSize.Width) && scale.Width > 1) { scale.Width = 1; scale.Height = 1; } if (double.IsPositiveInfinity(inputSize.Height) && scale.Height > 1) { scale.Width = 1; scale.Height = 1; } } return new Size(size.Width * scale.Width, size.Height * scale.Height); } /// <summary> /// Scans the ImageSource for available frames and stores /// them as individual bitmap sources. This is done once, /// when the <see cref="Image.Source"/> property is set (or changed) /// </summary> void UpdateAvailableFrames() { _availableFrames.Clear(); var bmFrame = Source as BitmapFrame; if (bmFrame == null) return; var decoder = bmFrame.Decoder; if (decoder != null && decoder.Frames != null) { var framesInSizeOrder = from frame in decoder.Frames group frame by frame.PixelHeight * frame.PixelWidth into g orderby g.Key select new { Size = g.Key, Frames = g.OrderByDescending(GetFramePixelDepth) }; _availableFrames.AddRange(framesInSizeOrder.Select(group => group.Frames.First())); } } /// <summary> /// Renders the contents of the image /// </summary> /// <param name="dc">An instance of <see cref="T:System.Windows.Media.DrawingContext"/> used to render the control.</param> protected override void OnRender(DrawingContext dc) { if (background != null) dc.DrawRectangle(background, null, new Rect(0, 0, RenderSize.Width, RenderSize.Height)); if (Source == null) return; ImageSource src = Source; var ourSize = RenderSize.Width * RenderSize.Height; foreach (var frame in _availableFrames) { src = frame; if (frame.PixelWidth * frame.PixelHeight >= ourSize) break; } dc.DrawImage(src, new Rect(new Point(0, 0), RenderSize)); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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 SensusUI.UiProperties; using System; using System.Collections.Generic; using System.Threading; using Newtonsoft.Json; using System.Linq; using System.Threading.Tasks; namespace SensusService.Probes { public abstract class PollingProbe : Probe { /// <summary> /// It's important to mitigate lag in polling operations since participation assessments are done on the basis of poll rates. /// </summary> private const bool POLL_CALLBACK_LAG = false; private int _pollingSleepDurationMS; private int _pollingTimeoutMinutes; private bool _isPolling; private string _pollCallbackId; private List<DateTime> _pollTimes; private readonly object _locker = new object(); [EntryIntegerUiProperty("Sleep Duration (MS):", true, 5)] public virtual int PollingSleepDurationMS { get { return _pollingSleepDurationMS; } set { if (value <= 1000) value = 1000; if (value != _pollingSleepDurationMS) { _pollingSleepDurationMS = value; if (_pollCallbackId != null) _pollCallbackId = SensusServiceHelper.Get().RescheduleRepeatingCallback(_pollCallbackId, _pollingSleepDurationMS, _pollingSleepDurationMS, POLL_CALLBACK_LAG); } } } [EntryIntegerUiProperty("Timeout (Mins.):", true, 6)] public int PollingTimeoutMinutes { get { return _pollingTimeoutMinutes; } set { if (value < 1) value = 1; _pollingTimeoutMinutes = value; } } [JsonIgnore] public abstract int DefaultPollingSleepDurationMS { get; } protected override float RawParticipation { get { int oneDayMS = (int)new TimeSpan(1, 0, 0, 0).TotalMilliseconds; float pollsPerDay = oneDayMS / (float)_pollingSleepDurationMS; float fullParticipationPolls = pollsPerDay * Protocol.ParticipationHorizonDays; lock (_pollTimes) { return _pollTimes.Count(pollTime => pollTime >= Protocol.ParticipationHorizon) / fullParticipationPolls; } } } public List<DateTime> PollTimes { get { return _pollTimes; } } public override string CollectionDescription { get { TimeSpan interval = new TimeSpan(0, 0, 0, 0, _pollingSleepDurationMS); double value = -1; string unit; int decimalPlaces = 0; if (interval.TotalSeconds <= 60) { value = interval.TotalSeconds; unit = "second"; decimalPlaces = 1; } else if (interval.TotalMinutes <= 60) { value = interval.TotalMinutes; unit = "minute"; } else if (interval.TotalHours <= 24) { value = interval.TotalHours; unit = "hour"; } else { value = interval.TotalDays; unit = "day"; } value = Math.Round(value, decimalPlaces); if (value == 1) return DisplayName + ": Once per " + unit + "."; else return DisplayName + ": Every " + value + " " + unit + "s."; } } protected PollingProbe() { _pollingSleepDurationMS = DefaultPollingSleepDurationMS; _pollingTimeoutMinutes = 5; _isPolling = false; _pollCallbackId = null; _pollTimes = new List<DateTime>(); } protected override void InternalStart() { lock (_locker) { base.InternalStart(); #if __IOS__ string userNotificationMessage = DisplayName + " data requested."; #elif __ANDROID__ string userNotificationMessage = null; #elif WINDOWS_PHONE string userNotificationMessage = null; // TODO: Should we use a message? #else #error "Unrecognized platform." #endif ScheduledCallback callback = new ScheduledCallback((callbackId, cancellationToken, letDeviceSleepCallback) => { return Task.Run(() => { if (Running) { _isPolling = true; IEnumerable<Datum> data = null; try { SensusServiceHelper.Get().Logger.Log("Polling.", LoggingLevel.Normal, GetType()); data = Poll(cancellationToken); lock (_pollTimes) { _pollTimes.Add(DateTime.Now); _pollTimes.RemoveAll(pollTime => pollTime < Protocol.ParticipationHorizon); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to poll: " + ex.Message, LoggingLevel.Normal, GetType()); } if (data != null) foreach (Datum datum in data) { if (cancellationToken.IsCancellationRequested) break; try { StoreDatum(datum); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to store datum: " + ex.Message, LoggingLevel.Normal, GetType()); } } _isPolling = false; } }); }, GetType().FullName + " Poll", TimeSpan.FromMinutes(_pollingTimeoutMinutes), userNotificationMessage); _pollCallbackId = SensusServiceHelper.Get().ScheduleRepeatingCallback(callback, 0, _pollingSleepDurationMS, POLL_CALLBACK_LAG); } } protected abstract IEnumerable<Datum> Poll(CancellationToken cancellationToken); public override void Stop() { lock (_locker) { base.Stop(); SensusServiceHelper.Get().UnscheduleCallback(_pollCallbackId); _pollCallbackId = null; } } public override bool TestHealth(ref string error, ref string warning, ref string misc) { bool restart = base.TestHealth(ref error, ref warning, ref misc); if (Running) { double msElapsedSincePreviousStore = (DateTimeOffset.UtcNow - MostRecentStoreTimestamp).TotalMilliseconds; int allowedLagMS = 5000; if (!_isPolling && _pollingSleepDurationMS <= int.MaxValue - allowedLagMS && // some probes (iOS HealthKit) have polling delays set to int.MaxValue. if we add to this (as we're about to do in the next check), we'll wrap around to 0 resulting in incorrect statuses. only do the check if we won't wrap around. msElapsedSincePreviousStore > (_pollingSleepDurationMS + allowedLagMS)) // system timer callbacks aren't always fired exactly as scheduled, resulting in health tests that identify warning conditions for delayed polling. allow a small fudge factor to ignore these warnings. warning += "Probe \"" + GetType().FullName + "\" has not stored data in " + msElapsedSincePreviousStore + "ms (polling delay = " + _pollingSleepDurationMS + "ms)." + Environment.NewLine; } return restart; } public override void ResetForSharing() { base.ResetForSharing(); _isPolling = false; _pollCallbackId = null; lock (_pollTimes) { _pollTimes.Clear(); } } } }
#region File Description //----------------------------------------------------------------------------- // AudioManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using System.Collections.Generic; #endregion namespace RolePlaying { /// <summary> /// Component that manages audio playback for all cues. /// </summary> /// <remarks> /// Similar to a class found in the Net Rumble starter kit on the /// XNA Creators Club Online website (http://creators.xna.com). /// </remarks> public class AudioManager : GameComponent { #region Singleton /// <summary> /// The singleton for this type. /// </summary> private static AudioManager audioManager = null; #endregion #region Audio Data /// <summary> /// The audio engine used to play all cues. /// </summary> private AudioEngine audioEngine; /// <summary> /// The soundbank that contains all cues. /// </summary> private SoundBank soundBank; /// <summary> /// The wavebank with all wave files for this game. /// </summary> private WaveBank waveBank; #endregion #region Initialization Methods /// <summary> /// Constructs the manager for audio playback of all cues. /// </summary> /// <param name="game">The game that this component will be attached to.</param> /// <param name="settingsFile">The filename of the XACT settings file.</param> /// <param name="waveBankFile">The filename of the XACT wavebank file.</param> /// <param name="soundBankFile">The filename of the XACT soundbank file.</param> private AudioManager(Game game, string settingsFile, string waveBankFile, string soundBankFile) : base(game) { try { audioEngine = new AudioEngine(settingsFile); waveBank = new WaveBank(audioEngine, waveBankFile); soundBank = new SoundBank(audioEngine, soundBankFile); } catch (NoAudioHardwareException) { // silently fall back to silence audioEngine = null; waveBank = null; soundBank = null; } } /// <summary> /// Initialize the static AudioManager functionality. /// </summary> /// <param name="game">The game that this component will be attached to.</param> /// <param name="settingsFile">The filename of the XACT settings file.</param> /// <param name="waveBankFile">The filename of the XACT wavebank file.</param> /// <param name="soundBankFile">The filename of the XACT soundbank file.</param> public static void Initialize(Game game, string settingsFile, string waveBankFile, string soundBankFile) { audioManager = new AudioManager(game, settingsFile, waveBankFile, soundBankFile); if (game != null) { game.Components.Add(audioManager); } } #endregion #region Cue Methods /// <summary> /// Retrieve a cue by name. /// </summary> /// <param name="cueName">The name of the cue requested.</param> /// <returns>The cue corresponding to the name provided.</returns> public static Cue GetCue(string cueName) { if (String.IsNullOrEmpty(cueName) || (audioManager == null) || (audioManager.audioEngine == null) || (audioManager.soundBank == null) || (audioManager.waveBank == null)) { return null; } return audioManager.soundBank.GetCue(cueName); } /// <summary> /// Plays a cue by name. /// </summary> /// <param name="cueName">The name of the cue to play.</param> public static void PlayCue(string cueName) { if ((audioManager != null) && (audioManager.audioEngine != null) && (audioManager.soundBank != null) && (audioManager.waveBank != null)) { audioManager.soundBank.PlayCue(cueName); } } #endregion #region Music /// <summary> /// The cue for the music currently playing, if any. /// </summary> private Cue musicCue; /// <summary> /// Stack of music cue names, for layered music playback. /// </summary> private Stack<string> musicCueNameStack = new Stack<string>(); /// <summary> /// Plays the desired music, clearing the stack of music cues. /// </summary> /// <param name="cueName">The name of the music cue to play.</param> public static void PlayMusic(string cueName) { // start the new music cue if (audioManager != null) { audioManager.musicCueNameStack.Clear(); PushMusic(cueName); } } /// <summary> /// Plays the music for this game, adding it to the music stack. /// </summary> /// <param name="cueName">The name of the music cue to play.</param> public static void PushMusic(string cueName) { // start the new music cue if ((audioManager != null) && (audioManager.audioEngine != null) && (audioManager.soundBank != null) && (audioManager.waveBank != null)) { audioManager.musicCueNameStack.Push(cueName); if ((audioManager.musicCue == null) || (audioManager.musicCue.Name != cueName)) { if (audioManager.musicCue != null) { audioManager.musicCue.Stop(AudioStopOptions.AsAuthored); audioManager.musicCue.Dispose(); audioManager.musicCue = null; } audioManager.musicCue = GetCue(cueName); if (audioManager.musicCue != null) { audioManager.musicCue.Play(); } } } } /// <summary> /// Stops the current music and plays the previous music on the stack. /// </summary> public static void PopMusic() { // start the new music cue if ((audioManager != null) && (audioManager.audioEngine != null) && (audioManager.soundBank != null) && (audioManager.waveBank != null)) { string cueName = null; if (audioManager.musicCueNameStack.Count > 0) { audioManager.musicCueNameStack.Pop(); if (audioManager.musicCueNameStack.Count > 0) { cueName = audioManager.musicCueNameStack.Peek(); } } if ((audioManager.musicCue == null) || (audioManager.musicCue.Name != cueName)) { if (audioManager.musicCue != null) { audioManager.musicCue.Stop(AudioStopOptions.AsAuthored); audioManager.musicCue.Dispose(); audioManager.musicCue = null; } if (!String.IsNullOrEmpty(cueName)) { audioManager.musicCue = GetCue(cueName); if (audioManager.musicCue != null) { audioManager.musicCue.Play(); } } } } } /// <summary> /// Stop music playback, clearing the cue. /// </summary> public static void StopMusic() { if (audioManager != null) { audioManager.musicCueNameStack.Clear(); if (audioManager.musicCue != null) { audioManager.musicCue.Stop(AudioStopOptions.AsAuthored); audioManager.musicCue.Dispose(); audioManager.musicCue = null; } } } #endregion #region Updating Methods /// <summary> /// Update the audio manager, particularly the engine. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // update the audio engine if (audioEngine != null) { audioEngine.Update(); } //if ((musicCue != null) && musicCue.IsStopped) //{ // AudioManager.PopMusic(); //} base.Update(gameTime); } #endregion #region Instance Disposal Methods /// <summary> /// Clean up the component when it is disposing. /// </summary> protected override void Dispose(bool disposing) { try { if (disposing) { StopMusic(); if (soundBank != null) { soundBank.Dispose(); soundBank = null; } if (waveBank != null) { waveBank.Dispose(); waveBank = null; } if (audioEngine != null) { audioEngine.Dispose(); audioEngine = null; } } } finally { base.Dispose(disposing); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public abstract class SendReceive : MemberDatas { private readonly ITestOutputHelper _log; public SendReceive(ITestOutputHelper output) { _log = output; } public abstract Task<Socket> AcceptAsync(Socket s); public abstract Task ConnectAsync(Socket s, EndPoint endPoint); public abstract Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer); public abstract Task<SocketReceiveFromResult> ReceiveFromAsync( Socket s, ArraySegment<byte> buffer, EndPoint endPoint); public abstract Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList); public abstract Task<int> SendAsync(Socket s, ArraySegment<byte> buffer); public abstract Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList); public abstract Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint); public virtual bool GuaranteedSendOrdering => true; public virtual bool ValidatesArrayArguments => true; public virtual bool SupportsNonBlocking => true; [Theory] [InlineData(null, 0, 0)] // null array [InlineData(1, -1, 0)] // offset low [InlineData(1, 2, 0)] // offset high [InlineData(1, 0, -1)] // count low [InlineData(1, 1, 2)] // count high public async Task InvalidArguments_Throws(int? length, int offset, int count) { if (length == null && !ValidatesArrayArguments) return; using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Type expectedExceptionType = length == null ? typeof(ArgumentNullException) : typeof(ArgumentOutOfRangeException); var validBuffer = new ArraySegment<byte>(new byte[1]); var invalidBuffer = new FakeArraySegment { Array = length != null ? new byte[length.Value] : null, Offset = offset, Count = count }.ToActual(); await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, invalidBuffer)); await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, new List<ArraySegment<byte>> { invalidBuffer })); await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, new List<ArraySegment<byte>> { validBuffer, invalidBuffer })); await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, invalidBuffer)); await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, new List<ArraySegment<byte>> { invalidBuffer })); await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, new List<ArraySegment<byte>> { validBuffer, invalidBuffer })); } } [ActiveIssue(16945)] // Packet loss, potentially due to other tests running at the same time [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public async Task SendToRecvFrom_Datagram_UDP(IPAddress loopbackAddress) { IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress; // TODO #5185: Harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new SemaphoreSlim(0); var senderAck = new SemaphoreSlim(0); var receivedChecksums = new uint?[DatagramsToSend]; Task leftThread = Task.Run(async () => { using (left) { EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize()); var recvBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { SocketReceiveFromResult result = await ReceiveFromAsync( left, new ArraySegment<byte>(recvBuffer), remote); Assert.Equal(DatagramSize, result.ReceivedBytes); Assert.Equal(rightEndpoint, result.RemoteEndPoint); int datagramId = recvBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, result.ReceivedBytes); receiverAck.Release(); Assert.True(await senderAck.WaitAsync(TestTimeout)); } } }); var sentChecksums = new uint[DatagramsToSend]; using (right) { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)i; int sent = await SendToAsync(right, new ArraySegment<byte>(sendBuffer), leftEndpoint); Assert.True(await receiverAck.WaitAsync(AckTimeout)); senderAck.Release(); Assert.Equal(DatagramSize, sent); sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent); } } await leftThread; for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(LoopbacksAndBuffers))] public async Task SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456, ListenBacklog = 1, LingerTime = 1; int bytesReceived = 0, bytesSent = 0; Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32(); using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); Task serverProcessingTask = Task.Run(async () => { using (Socket remote = await AcceptAsync(server)) { if (!useMultipleBuffers) { var recvBuffer = new byte[256]; for (;;) { int received = await ReceiveAsync(remote, new ArraySegment<byte>(recvBuffer)); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } else { var recvBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[123]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 33)}; for (;;) { int received = await ReceiveAsync(remote, recvBuffers); if (received == 0) { break; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment<byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } } }); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, clientEndpoint); var random = new Random(); if (!useMultipleBuffers) { var sendBuffer = new byte[512]; for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = await SendAsync(client, new ArraySegment<byte>(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining))); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } } else { var sendBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[23]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 9)}; for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent) { for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } sent = await SendAsync(client, sendBuffers); bytesSent += sent; for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++) { ArraySegment<byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } client.LingerState = new LingerOption(true, LingerTime); client.Shutdown(SocketShutdown.Send); await serverProcessingTask; } Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public async Task SendRecv_Stream_TCP_AlternateBufferAndBufferList(IPAddress listenAt) { const int BytesToSend = 123456; int bytesReceived = 0, bytesSent = 0; Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32(); using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(1); Task serverProcessingTask = Task.Run(async () => { using (Socket remote = await AcceptAsync(server)) { byte[] recvBuffer1 = new byte[256], recvBuffer2 = new byte[256]; long iter = 0; while (true) { ArraySegment<byte> seg1 = new ArraySegment<byte>(recvBuffer1), seg2 = new ArraySegment<byte>(recvBuffer2); int received; switch (iter++ % 3) { case 0: // single buffer received = await ReceiveAsync(remote, seg1); break; case 1: // buffer list with a single buffer received = await ReceiveAsync(remote, new List<ArraySegment<byte>> { seg1 }); break; default: // buffer list with multiple buffers received = await ReceiveAsync(remote, new List<ArraySegment<byte>> { seg1, seg2 }); break; } if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer1, 0, Math.Min(received, recvBuffer1.Length)); if (received > recvBuffer1.Length) { receivedChecksum.Add(recvBuffer2, 0, received - recvBuffer1.Length); } } } }); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, clientEndpoint); var random = new Random(); byte[] sendBuffer1 = new byte[512], sendBuffer2 = new byte[512]; long iter = 0; for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer1); random.NextBytes(sendBuffer2); int amountFromSendBuffer1 = Math.Min(sendBuffer1.Length, remaining); switch (iter++ % 3) { case 0: // single buffer sent = await SendAsync(client, new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1)); break; case 1: // buffer list with a single buffer sent = await SendAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1) }); break; default: // buffer list with multiple buffers sent = await SendAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1), new ArraySegment<byte>(sendBuffer2, 0, Math.Min(sendBuffer2.Length, remaining - amountFromSendBuffer1)), }); break; } bytesSent += sent; sentChecksum.Add(sendBuffer1, 0, Math.Min(sent, sendBuffer1.Length)); if (sent > sendBuffer1.Length) { sentChecksum.Add(sendBuffer2, 0, sent - sendBuffer1.Length); } } client.Shutdown(SocketShutdown.Send); await serverProcessingTask; } Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(LoopbacksAndBuffers))] public async Task SendRecv_Stream_TCP_MultipleConcurrentReceives(IPAddress listenAt, bool useMultipleBuffers) { using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(1); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { Task clientConnect = ConnectAsync(client, clientEndpoint); using (Socket remote = await AcceptAsync(server)) { await clientConnect; if (useMultipleBuffers) { byte[] buffer1 = new byte[1], buffer2 = new byte[1], buffer3 = new byte[1], buffer4 = new byte[1], buffer5 = new byte[1]; Task<int> receive1 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer1), new ArraySegment<byte>(buffer2) }); Task<int> receive2 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer3), new ArraySegment<byte>(buffer4) }); Task<int> receive3 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer5) }); await Task.WhenAll( SendAsync(remote, new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 })), receive1, receive2, receive3); Assert.True(receive1.Result == 1 || receive1.Result == 2, $"Expected 1 or 2, got {receive1.Result}"); Assert.True(receive2.Result == 1 || receive2.Result == 2, $"Expected 1 or 2, got {receive2.Result}"); Assert.Equal(1, receive3.Result); if (GuaranteedSendOrdering) { if (receive1.Result == 1 && receive2.Result == 1) { Assert.Equal(1, buffer1[0]); Assert.Equal(0, buffer2[0]); Assert.Equal(2, buffer3[0]); Assert.Equal(0, buffer4[0]); Assert.Equal(3, buffer5[0]); } else if (receive1.Result == 1 && receive2.Result == 2) { Assert.Equal(1, buffer1[0]); Assert.Equal(0, buffer2[0]); Assert.Equal(2, buffer3[0]); Assert.Equal(3, buffer4[0]); Assert.Equal(4, buffer5[0]); } else if (receive1.Result == 2 && receive2.Result == 1) { Assert.Equal(1, buffer1[0]); Assert.Equal(2, buffer2[0]); Assert.Equal(3, buffer3[0]); Assert.Equal(0, buffer4[0]); Assert.Equal(4, buffer5[0]); } else // receive1.Result == 2 && receive2.Result == 2 { Assert.Equal(1, buffer1[0]); Assert.Equal(2, buffer2[0]); Assert.Equal(3, buffer3[0]); Assert.Equal(4, buffer4[0]); Assert.Equal(5, buffer5[0]); } } } else { var buffer1 = new ArraySegment<byte>(new byte[1]); var buffer2 = new ArraySegment<byte>(new byte[1]); var buffer3 = new ArraySegment<byte>(new byte[1]); Task<int> receive1 = ReceiveAsync(client, buffer1); Task<int> receive2 = ReceiveAsync(client, buffer2); Task<int> receive3 = ReceiveAsync(client, buffer3); await Task.WhenAll( SendAsync(remote, new ArraySegment<byte>(new byte[] { 1, 2, 3 })), receive1, receive2, receive3); Assert.Equal(3, receive1.Result + receive2.Result + receive3.Result); if (GuaranteedSendOrdering) { Assert.Equal(1, buffer1.Array[0]); Assert.Equal(2, buffer2.Array[0]); Assert.Equal(3, buffer3.Array[0]); } } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(LoopbacksAndBuffers))] public async Task SendRecv_Stream_TCP_MultipleConcurrentSends(IPAddress listenAt, bool useMultipleBuffers) { using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { byte[] sendData = new byte[5000000]; new Random(42).NextBytes(sendData); Func<byte[], int, int, byte[]> slice = (input, offset, count) => { var arr = new byte[count]; Array.Copy(input, offset, arr, 0, count); return arr; }; server.BindToAnonymousPort(listenAt); server.Listen(1); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { Task clientConnect = ConnectAsync(client, clientEndpoint); using (Socket remote = await AcceptAsync(server)) { await clientConnect; Task<int> send1, send2, send3; if (useMultipleBuffers) { var bufferList1 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 0, 1000000)), new ArraySegment<byte>(slice(sendData, 1000000, 1000000)) }; var bufferList2 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 2000000, 1000000)), new ArraySegment<byte>(slice(sendData, 3000000, 1000000)) }; var bufferList3 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 4000000, 1000000)) }; send1 = SendAsync(client, bufferList1); send2 = SendAsync(client, bufferList2); send3 = SendAsync(client, bufferList3); } else { var buffer1 = new ArraySegment<byte>(slice(sendData, 0, 2000000)); var buffer2 = new ArraySegment<byte>(slice(sendData, 2000000, 2000000)); var buffer3 = new ArraySegment<byte>(slice(sendData, 4000000, 1000000)); send1 = SendAsync(client, buffer1); send2 = SendAsync(client, buffer2); send3 = SendAsync(client, buffer3); } int receivedTotal = 0; int received; var receiveBuffer = new byte[sendData.Length]; while (receivedTotal < receiveBuffer.Length) { if ((received = await ReceiveAsync(remote, new ArraySegment<byte>(receiveBuffer, receivedTotal, receiveBuffer.Length - receivedTotal))) == 0) break; receivedTotal += received; } Assert.Equal(5000000, receivedTotal); if (GuaranteedSendOrdering) { Assert.Equal(sendData, receiveBuffer); } } } } } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(LoopbacksAndBuffers))] public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int TestTimeout = 30000; var listener = new TcpListener(listenAt, 0); listener.Start(ListenBacklog); try { int bytesReceived = 0; var receivedChecksum = new Fletcher32(); Task serverTask = Task.Run(async () => { using (Socket remote = await listener.AcceptSocketAsync()) { var recvBuffer = new byte[256]; while (true) { if (pollBeforeOperation) { Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded"); } int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); if (received == 0) { Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded"); break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } }); int bytesSent = 0; var sentChecksum = new Fletcher32(); Task clientTask = Task.Run(async () => { var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, clientEndpoint); if (pollBeforeOperation) { Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout"); } var random = new Random(); var sendBuffer = new byte[512]; for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); if (pollBeforeOperation) { Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded"); } sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } } }); Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out"); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } finally { listener.Stop(); } } [Fact] public async Task SendRecv_0ByteReceive_Success() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener); await Task.WhenAll( acceptTask, ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { for (int i = 0; i < 3; i++) { // Have the client do a 0-byte receive. No data is available, so this should pend. Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(Array.Empty<byte>())); Assert.False(receive.IsCompleted); Assert.Equal(0, client.Available); // Have the server send 1 byte to the client. Assert.Equal(1, server.Send(new byte[1], 0, 1, SocketFlags.None)); Assert.Equal(0, server.Available); // The client should now wake up, getting 0 bytes with 1 byte available. Assert.Equal(0, await receive); Assert.Equal(1, client.Available); // We should be able to do another 0-byte receive that completes immediateliy Assert.Equal(0, await ReceiveAsync(client, new ArraySegment<byte>(new byte[1], 0, 0))); Assert.Equal(1, client.Available); // Then receive the byte Assert.Equal(1, await ReceiveAsync(client, new ArraySegment<byte>(new byte[1]))); Assert.Equal(0, client.Available); } } } } [Theory] [InlineData(false, 1)] [InlineData(true, 1)] public async Task SendRecv_BlockingNonBlocking_LingerTimeout_Success(bool blocking, int lingerTimeout) { if (!SupportsNonBlocking) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Blocking = blocking; listener.Blocking = blocking; client.LingerState = new LingerOption(true, lingerTimeout); listener.LingerState = new LingerOption(true, lingerTimeout); listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener); await Task.WhenAll( acceptTask, ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { server.Blocking = blocking; server.LingerState = new LingerOption(true, lingerTimeout); Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(new byte[1])); Assert.Equal(1, await SendAsync(server, new ArraySegment<byte>(new byte[1]))); Assert.Equal(1, await receive); } } } [Fact] [PlatformSpecific(~TestPlatforms.OSX)] // SendBufferSize, ReceiveBufferSize = 0 not supported on OSX. public async Task SendRecv_NoBuffering_Success() { if (!SupportsNonBlocking) return; using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = AcceptAsync(listener); await Task.WhenAll( acceptTask, ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { client.SendBufferSize = 0; server.ReceiveBufferSize = 0; var sendBuffer = new byte[10000]; Task sendTask = SendAsync(client, new ArraySegment<byte>(sendBuffer)); int totalReceived = 0; var receiveBuffer = new ArraySegment<byte>(new byte[4096]); while (totalReceived < sendBuffer.Length) { int received = await ReceiveAsync(server, receiveBuffer); if (received <= 0) break; totalReceived += received; } Assert.Equal(sendBuffer.Length, totalReceived); await sendTask; } } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] public void SocketSendReceiveBufferSize_SetZero_ThrowsSocketException() { using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketException e; e = Assert.Throws<SocketException>(() => socket.SendBufferSize = 0); Assert.Equal(e.SocketErrorCode, SocketError.InvalidArgument); e = Assert.Throws<SocketException>(() => socket.ReceiveBufferSize = 0); Assert.Equal(e.SocketErrorCode, SocketError.InvalidArgument); } } } public sealed class SendReceiveUdpClient : MemberDatas { [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress loopbackAddress) { IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress; // TODO #5185: harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; using (var left = new UdpClient(new IPEndPoint(leftAddress, 0))) using (var right = new UdpClient(new IPEndPoint(rightAddress, 0))) { var leftEndpoint = (IPEndPoint)left.Client.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.Client.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); var receivedChecksums = new uint?[DatagramsToSend]; int receivedDatagrams = 0; Task receiverTask = Task.Run(async () => { for (; receivedDatagrams < DatagramsToSend; receivedDatagrams++) { UdpReceiveResult result = await left.ReceiveAsync(); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); Assert.Equal(DatagramSize, result.Buffer.Length); Assert.Equal(rightEndpoint, result.RemoteEndPoint); int datagramId = (int)result.Buffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(result.Buffer, 0, result.Buffer.Length); } }); var sentChecksums = new uint[DatagramsToSend]; int sentDatagrams = 0; Task senderTask = Task.Run(async () => { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (; sentDatagrams < DatagramsToSend; sentDatagrams++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; int sent = await right.SendAsync(sendBuffer, DatagramSize, leftEndpoint); Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); } }); Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } } } } public sealed class SendReceiveListener : MemberDatas { [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(Loopbacks))] public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var listener = new TcpListener(listenAt, 0); listener.Start(ListenBacklog); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); Task serverTask = Task.Run(async () => { using (TcpClient remote = await listener.AcceptTcpClientAsync()) using (NetworkStream stream = remote.GetStream()) { var recvBuffer = new byte[256]; for (;;) { int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } }); int bytesSent = 0; var sentChecksum = new Fletcher32(); Task clientTask = Task.Run(async () => { var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new TcpClient(clientEndpoint.AddressFamily)) { await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port); using (NetworkStream stream = client.GetStream()) { var random = new Random(); var sendBuffer = new byte[512]; for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = Math.Min(sendBuffer.Length, remaining); await stream.WriteAsync(sendBuffer, 0, sent); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } client.LingerState = new LingerOption(true, LingerTime); } } }); Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), $"Time out waiting for serverTask ({serverTask.Status}) and clientTask ({clientTask.Status})"); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } } public sealed class SendReceiveSync : SendReceive { public SendReceiveSync(ITestOutputHelper output) : base(output) { } public override Task<Socket> AcceptAsync(Socket s) => Task.Run(() => s.Accept()); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Run(() => s.Connect(endPoint)); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Receive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None)); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Run(() => s.Receive(bufferList, SocketFlags.None)); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Run(() => { int received = s.ReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint); return new SocketReceiveFromResult { ReceivedBytes = received, RemoteEndPoint = endPoint }; }); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Send(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None)); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Run(() => s.Send(bufferList, SocketFlags.None)); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Run(() => s.SendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint)); public override bool GuaranteedSendOrdering => false; public override bool SupportsNonBlocking => false; } public sealed class SendReceiveApm : SendReceive { public SendReceiveApm(ITestOutputHelper output) : base(output) { } public override Task<Socket> AcceptAsync(Socket s) => Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, null); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, endPoint, null); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Factory.FromAsync((callback, state) => s.BeginReceive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state), s.EndReceive, null); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Factory.FromAsync(s.BeginReceive, s.EndReceive, bufferList, SocketFlags.None, null); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) { var tcs = new TaskCompletionSource<SocketReceiveFromResult>(); s.BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint, iar => { try { int receivedBytes = s.EndReceiveFrom(iar, ref endPoint); tcs.TrySetResult(new SocketReceiveFromResult { ReceivedBytes = receivedBytes, RemoteEndPoint = endPoint }); } catch (Exception e) { tcs.TrySetException(e); } }, null); return tcs.Task; } public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Factory.FromAsync((callback, state) => s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state), s.EndSend, null); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => Task.Factory.FromAsync(s.BeginSend, s.EndSend, bufferList, SocketFlags.None, null); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => Task.Factory.FromAsync( (callback, state) => s.BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint, callback, state), s.EndSendTo, null); } public sealed class SendReceiveTask : SendReceive { public SendReceiveTask(ITestOutputHelper output) : base(output) { } public override Task<Socket> AcceptAsync(Socket s) => s.AcceptAsync(); public override Task ConnectAsync(Socket s, EndPoint endPoint) => s.ConnectAsync(endPoint); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => s.ReceiveAsync(buffer, SocketFlags.None); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => s.ReceiveAsync(bufferList, SocketFlags.None); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => s.ReceiveFromAsync(buffer, SocketFlags.None, endPoint); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => s.SendAsync(buffer, SocketFlags.None); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => s.SendAsync(bufferList, SocketFlags.None); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => s.SendToAsync(buffer, SocketFlags.None, endPoint); } public sealed class SendReceiveEap : SendReceive { public SendReceiveEap(ITestOutputHelper output) : base(output) { } public override bool ValidatesArrayArguments => false; public override Task<Socket> AcceptAsync(Socket s) => InvokeAsync(s, e => e.AcceptSocket, e => s.AcceptAsync(e)); public override Task ConnectAsync(Socket s, EndPoint endPoint) => InvokeAsync(s, e => true, e => { e.RemoteEndPoint = endPoint; return s.ConnectAsync(e); }); public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); return s.ReceiveAsync(e); }); public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) => InvokeAsync(s, e => e.BytesTransferred, e => { e.BufferList = bufferList; return s.ReceiveAsync(e); }); public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => InvokeAsync(s, e => new SocketReceiveFromResult { ReceivedBytes = e.BytesTransferred, RemoteEndPoint = e.RemoteEndPoint }, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); e.RemoteEndPoint = endPoint; return s.ReceiveFromAsync(e); }); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); return s.SendAsync(e); }); public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) => InvokeAsync(s, e => e.BytesTransferred, e => { e.BufferList = bufferList; return s.SendAsync(e); }); public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) => InvokeAsync(s, e => e.BytesTransferred, e => { e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); e.RemoteEndPoint = endPoint; return s.SendToAsync(e); }); private static Task<TResult> InvokeAsync<TResult>( Socket s, Func<SocketAsyncEventArgs, TResult> getResult, Func<SocketAsyncEventArgs, bool> invoke) { var tcs = new TaskCompletionSource<TResult>(); var saea = new SocketAsyncEventArgs(); EventHandler<SocketAsyncEventArgs> handler = (_, e) => { if (e.SocketError == SocketError.Success) tcs.SetResult(getResult(e)); else tcs.SetException(new SocketException((int)e.SocketError)); saea.Dispose(); }; saea.Completed += handler; if (!invoke(saea)) handler(s, saea); return tcs.Task; } [Theory] [InlineData(1, -1, 0)] // offset low [InlineData(1, 2, 0)] // offset high [InlineData(1, 0, -1)] // count low [InlineData(1, 1, 2)] // count high public void BufferList_InvalidArguments_Throws(int length, int offset, int count) { using (var e = new SocketAsyncEventArgs()) { ArraySegment<byte> invalidBuffer = new FakeArraySegment { Array = new byte[length], Offset = offset, Count = count }.ToActual(); Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { invalidBuffer }); ArraySegment<byte> validBuffer = new ArraySegment<byte>(new byte[1]); Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { validBuffer, invalidBuffer }); } } } public abstract class MemberDatas { public static readonly object[][] Loopbacks = new[] { new object[] { IPAddress.Loopback }, new object[] { IPAddress.IPv6Loopback }, }; public static readonly object[][] LoopbacksAndBuffers = new object[][] { new object[] { IPAddress.IPv6Loopback, true }, new object[] { IPAddress.IPv6Loopback, false }, new object[] { IPAddress.Loopback, true }, new object[] { IPAddress.Loopback, false }, }; } internal struct FakeArraySegment { public byte[] Array; public int Offset; public int Count; public ArraySegment<byte> ToActual() { ArraySegmentWrapper wrapper = default(ArraySegmentWrapper); wrapper.Fake = this; return wrapper.Actual; } } [StructLayout(LayoutKind.Explicit)] internal struct ArraySegmentWrapper { [FieldOffset(0)] public ArraySegment<byte> Actual; [FieldOffset(0)] public FakeArraySegment Fake; } }
#region Copyright Information // Sentience Lab Unity Framework // (C) Sentience Lab (sentiencelab@aut.ac.nz), Auckland University of Technology, Auckland, New Zealand #endregion Copyright Information using System.Collections.Generic; using UnityEngine; namespace SentienceLab.MoCap { /// <summary> /// Class for rendering skeletons for a Motion Capture actor. /// </summary> /// [AddComponentMenu("Motion Capture/Skeleton Renderer")] public class SkeletonRenderer : MonoBehaviour, SceneListener { [Tooltip("The name of the MoCap actor to render.")] public string actorName; [Tooltip("A template game object for how to display the bones. Needs to be one unit long along the Y axis and start at the origin.")] public GameObject boneTemplate; /// <summary> /// Called at the start of the game. /// Tries to find the MoCap client singleton and then /// registers this object as a listener with the client. /// </summary> /// void Start() { // initialise variables skeletonNode = null; actor = null; boneList = new Dictionary<Bone, BoneObject>(); // sanity checks if (boneTemplate == null) { Debug.LogWarning("No bone template defined"); } // find any MoCap data modifiers and store them modifiers = GetComponents<IMoCapDataModifier>(); // start receiving MoCap data MoCapManager.Instance.AddSceneListener(this); } /// <summary> /// Creates copies of the bone template for all bones. /// </summary> /// <param name="bones">bone data from the MoCap system</param> /// private void CreateBones(Bone[] bones) { // create node for containing all the marker objects skeletonNode = new GameObject(); skeletonNode.name = "Bones"; skeletonNode.transform.parent = this.transform; skeletonNode.transform.localPosition = Vector3.zero; skeletonNode.transform.localRotation = Quaternion.identity; skeletonNode.transform.localScale = Vector3.one; // create copies of the marker template foreach (Bone bone in bones) { // add empty for position/orientation GameObject boneNode = new GameObject(); boneNode.name = bone.name; GameObject boneRepresentation = null; if (boneTemplate != null) { float scale = bone.length; if (scale <= 0) { scale = 1; } // add subnode for visual that can be scaled boneRepresentation = GameObject.Instantiate(boneTemplate); boneRepresentation.transform.parent = boneNode.transform; boneRepresentation.transform.localScale = scale * Vector3.one; boneRepresentation.transform.localRotation = new Quaternion(); boneRepresentation.name = bone.name + "_visual"; boneRepresentation.SetActive(true); } if (bone.parent != null) { // attach to parent node GameObject parentObject = boneList[bone.parent].node; boneNode.transform.parent = parentObject.transform; } else { // no parent > attach to base skeleton node boneNode.transform.parent = skeletonNode.transform; } boneList[bone] = new BoneObject() { node = boneNode, visual = boneRepresentation }; bone.buffer.EnsureCapacityForModifiers(modifiers); boneTemplate.SetActive(false); } } //// <summary> /// Called once per frame. /// </summary> /// void Update() { // create marker position array if necessary // but only when tracking is OK, otherwise the bone lengths are undefined if ((skeletonNode == null) && (actor != null) && actor.bones[0].tracked) { CreateBones(actor.bones); } if (skeletonNode == null) return; // update bones foreach (KeyValuePair<Bone, BoneObject> entry in boneList) { BoneObject obj = entry.Value; Bone bone = entry.Key; MoCapData data = bone.buffer.RunModifiers(modifiers); // update bone game object if (data.tracked) { obj.node.transform.localPosition = data.pos; obj.node.transform.localRotation = data.rot; // update length of representation GameObject boneRepresentation = obj.visual; if (boneRepresentation != null) { boneRepresentation.transform.localScale = data.length * Vector3.one; } obj.node.SetActive(true); if (bone.parent != null) { Debug.DrawLine( obj.node.transform.parent.position, obj.node.transform.position, Color.red); } } else { // bone not tracked anymore obj.node.SetActive(false); } } } public void SceneDataUpdated(Scene scene) { // nothing to do here } public void SceneDefinitionChanged(Scene scene) { // actor has changed > rebuild skeleton on next update if (skeletonNode != null) { // if necessary, destroy old container GameObject.Destroy(skeletonNode); skeletonNode = null; } actor = scene.FindActor(actorName); if (actor != null) { Debug.Log("Skeleton Renderer '" + this.name + "' controlled by MoCap actor '" + actorName + "'."); } else { Debug.LogWarning("Skeleton Renderer '" + this.name + "' cannot find MoCap actor '" + actorName + "'."); } } struct BoneObject { public GameObject node; public GameObject visual; } private GameObject skeletonNode; private Actor actor; private Dictionary<Bone, BoneObject> boneList; private IMoCapDataModifier[] modifiers; // list of modifiers for this renderer } }
// 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. #nullable disable using SharpCompress.Common.Zip; using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; namespace SharpCompress.Compressors.Deflate64 { public sealed class Deflate64Stream : Stream { private const int DEFAULT_BUFFER_SIZE = 8192; private Stream _stream; private CompressionMode _mode; private InflaterManaged _inflater; private byte[] _buffer; public Deflate64Stream(Stream stream, CompressionMode mode) { if (stream is null) { throw new ArgumentNullException(nameof(stream)); } if (mode != CompressionMode.Decompress) { throw new NotImplementedException("Deflate64: this implementation only supports decompression"); } if (!stream.CanRead) { throw new ArgumentException("Deflate64: input stream is not readable", nameof(stream)); } InitializeInflater(stream, ZipCompressionMethod.Deflate64); } /// <summary> /// Sets up this DeflateManagedStream to be used for Inflation/Decompression /// </summary> private void InitializeInflater(Stream stream, ZipCompressionMethod method = ZipCompressionMethod.Deflate) { Debug.Assert(stream != null); Debug.Assert(method == ZipCompressionMethod.Deflate || method == ZipCompressionMethod.Deflate64); if (!stream.CanRead) { throw new ArgumentException("Deflate64: input stream is not readable", nameof(stream)); } _inflater = new InflaterManaged(method == ZipCompressionMethod.Deflate64); _stream = stream; _mode = CompressionMode.Decompress; _buffer = new byte[DEFAULT_BUFFER_SIZE]; } public override bool CanRead { get { if (_stream is null) { return false; } return (_mode == CompressionMode.Decompress && _stream.CanRead); } } public override bool CanWrite { get { if (_stream is null) { return false; } return (_mode == CompressionMode.Compress && _stream.CanWrite); } } public override bool CanSeek => false; public override long Length { get { throw new NotSupportedException("Deflate64: not supported"); } } public override long Position { get { throw new NotSupportedException("Deflate64: not supported"); } set { throw new NotSupportedException("Deflate64: not supported"); } } public override void Flush() { EnsureNotDisposed(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Deflate64: not supported"); } public override void SetLength(long value) { throw new NotSupportedException("Deflate64: not supported"); } public override int Read(byte[] array, int offset, int count) { EnsureDecompressionMode(); ValidateParameters(array, offset, count); EnsureNotDisposed(); int bytesRead; int currentOffset = offset; int remainingCount = count; while (true) { bytesRead = _inflater.Inflate(array, currentOffset, remainingCount); currentOffset += bytesRead; remainingCount -= bytesRead; if (remainingCount == 0) { break; } if (_inflater.Finished()) { // if we finished decompressing, we can't have anything left in the outputwindow. Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!"); break; } int bytes = _stream.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { break; } else if (bytes > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException("Deflate64: invalid data"); } _inflater.SetInput(_buffer, 0, bytes); } return count - remainingCount; } private void ValidateParameters(byte[] array, int offset, int count) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (array.Length - offset < count) { throw new ArgumentException("Deflate64: invalid offset/count combination"); } } private void EnsureNotDisposed() { if (_stream is null) { ThrowStreamClosedException(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowStreamClosedException() { throw new ObjectDisposedException(null, "Deflate64: stream has been disposed"); } private void EnsureDecompressionMode() { if (_mode != CompressionMode.Decompress) { ThrowCannotReadFromDeflateManagedStreamException(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotReadFromDeflateManagedStreamException() { throw new InvalidOperationException("Deflate64: cannot read from this stream"); } private void EnsureCompressionMode() { if (_mode != CompressionMode.Compress) { ThrowCannotWriteToDeflateManagedStreamException(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotWriteToDeflateManagedStreamException() { throw new InvalidOperationException("Deflate64: cannot write to this stream"); } public override void Write(byte[] array, int offset, int count) { ThrowCannotWriteToDeflateManagedStreamException(); } // This is called by Dispose: private void PurgeBuffers(bool disposing) { if (!disposing) { return; } if (_stream is null) { return; } Flush(); } protected override void Dispose(bool disposing) { try { PurgeBuffers(disposing); } finally { // Close the underlying stream even if PurgeBuffers threw. // Stream.Close() may throw here (may or may not be due to the same error). // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { if (disposing) { _stream?.Dispose(); } } finally { _stream = null; try { _inflater?.Dispose(); } finally { _inflater = null; base.Dispose(disposing); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Reflection; using System.Numerics.Hashing; using Microsoft.CSharp.RuntimeBinder.Errors; namespace Microsoft.CSharp.RuntimeBinder { internal static class BinderHelper { private static MethodInfo s_DoubleIsNaN; private static MethodInfo s_SingleIsNaN; internal static DynamicMetaObject Bind( ICSharpBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable<CSharpArgumentInfo> arginfos, DynamicMetaObject onBindingError) { Expression[] parameters = new Expression[args.Length]; BindingRestrictions restrictions = BindingRestrictions.Empty; ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder; ParameterExpression tempForIncrement = null; IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator(); for (int index = 0; index < args.Length; ++index) { DynamicMetaObject o = args[index]; // Our contract with the DLR is such that we will not enter a bind unless we have // values for the meta-objects involved. Debug.Assert(o.HasValue); CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null; if (index == 0 && IsIncrementOrDecrementActionOnLocal(action)) { // We have an inc or a dec operation. Insert the temp local instead. // // We need to do this because for value types, the object will come // in boxed, and we'd need to unbox it to get the original type in order // to increment. The only way to do that is to create a new temporary. object value = o.Value; tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0"); parameters[0] = tempForIncrement; } else { parameters[index] = o.Expression; } BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info); restrictions = restrictions.Merge(r); // Here we check the argument info. If the argument info shows that the current argument // is a literal constant, then we also add an instance restriction on the value of // the constant. if (info != null && info.LiteralConstant) { if (o.Value is double && double.IsNaN((double)o.Value)) { MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN")); Expression e = Expression.Call(null, isNaN, o.Expression); restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e)); } else if (o.Value is float && float.IsNaN((float)o.Value)) { MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN")); Expression e = Expression.Call(null, isNaN, o.Expression); restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e)); } else { Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type)); r = BindingRestrictions.GetExpressionRestriction(e); restrictions = restrictions.Merge(r); } } } // Get the bound expression. try { Expression expression = binder.Bind(action, parameters, args, out DynamicMetaObject deferredBinding); if (deferredBinding != null) { expression = ConvertResult(deferredBinding.Expression, action); restrictions = deferredBinding.Restrictions.Merge(restrictions); return new DynamicMetaObject(expression, restrictions); } if (tempForIncrement != null) { // If we have a ++ or -- payload, we need to do some temp rewriting. // We rewrite to the following: // // temp = (type)o; // temp++; // o = temp; // return o; DynamicMetaObject arg0 = args[0]; expression = Expression.Block( new[] { tempForIncrement }, Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())), expression, Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type))); } expression = ConvertResult(expression, action); return new DynamicMetaObject(expression, restrictions); } catch (RuntimeBinderException e) { if (onBindingError != null) { return onBindingError; } return new DynamicMetaObject( Expression.Throw( Expression.New( typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }), Expression.Constant(e.Message) ), GetTypeForErrorMetaObject(action, args) ), restrictions ); } } public static void ValidateBindArgument(DynamicMetaObject argument, string paramName) { if (argument == null) { throw Error.ArgumentNull(paramName); } if (!argument.HasValue) { throw Error.DynamicArgumentNeedsValue(paramName); } } public static void ValidateBindArgument(DynamicMetaObject[] arguments, string paramName) { if (arguments != null) // null is treated as empty, so not invalid { for (int i = 0; i != arguments.Length; ++i) { ValidateBindArgument(arguments[i], $"{paramName}[{i}]"); } } } ///////////////////////////////////////////////////////////////////////////////// private static bool IsTypeOfStaticCall( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload) { return parameterIndex == 0 && callPayload != null && callPayload.StaticCall; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsComObject(object obj) { return obj != null && Marshal.IsComObject(obj); } ///////////////////////////////////////////////////////////////////////////////// // Try to determine if this object represents a WindowsRuntime object - i.e. it either // is coming from a WinMD file or is derived from a class coming from a WinMD. // The logic here matches the CLR's logic of finding a WinRT object. internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj) { Type curType = obj?.RuntimeType; while (curType != null) { TypeAttributes attributes = curType.Attributes; if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime) { // Found a WinRT COM object return true; } if ((attributes & TypeAttributes.Import) == TypeAttributes.Import) { // Found a class that is actually imported from COM but not WinRT // this is definitely a non-WinRT COM object return false; } curType = curType.BaseType; } return false; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsTransparentProxy(object obj) { // In the full framework, this checks: // return obj != null && RemotingServices.IsTransparentProxy(obj); // but transparent proxies don't exist in .NET Core. return false; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info) { // This detects situations where, although the argument has a value with // a given type, that type is insufficient to determine, statically, the // set of reference conversions that are going to exist at bind time for // different values. For instance, one __ComObject may allow a conversion // to IFoo while another does not. bool isDynamicObject = info != null && !info.UseCompileTimeType && (IsComObject(argument.Value) || IsTransparentProxy(argument.Value)); return isDynamicObject; } ///////////////////////////////////////////////////////////////////////////////// private static BindingRestrictions DeduceArgumentRestriction( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload, DynamicMetaObject argument, CSharpArgumentInfo info) { // Here we deduce what predicates the DLR can apply to future calls in order to // determine whether to use the previously-computed-and-cached delegate, or // whether we need to bind the site again. Ideally we would like the // predicate to be as broad as is possible; if we can re-use analysis based // solely on the type of the argument, that is preferable to re-using analysis // based on object identity with a previously-analyzed argument. // The times when we need to restrict re-use to a particular instance, rather // than its type, are: // // * if the argument is a null reference then we have no type information. // // * if we are making a static call then the first argument is // going to be a Type object. In this scenario we should always check // for a specific Type object rather than restricting to the Type type. // // * if the argument was dynamic at compile time and it is a dynamic proxy // object that the runtime manages, such as COM RCWs and transparent // proxies. // // ** there is also a case for constant values (such as literals) to use // something like value restrictions, and that is accomplished in Bind(). bool useValueRestriction = argument.Value == null || IsTypeOfStaticCall(parameterIndex, callPayload) || IsDynamicallyTypedRuntimeProxy(argument, info); return useValueRestriction ? BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) : BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType); } ///////////////////////////////////////////////////////////////////////////////// private static Expression ConvertResult(Expression binding, ICSharpBinder action) { // Need to handle the following cases: // (1) Call to a constructor: no conversions. // (2) Call to a void-returning method: return null iff result is discarded. // (3) Call to a value-type returning method: box to object. // // In all other cases, binding.Type should be equivalent or // reference assignable to resultType. // No conversions needed for , the call site has the correct type. if (action is CSharpInvokeConstructorBinder) { return binding; } if (binding.Type == typeof(void)) { if (action is ICSharpInvokeOrInvokeMemberBinder invoke && invoke.ResultDiscarded) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Block(binding, Expression.Default(action.ReturnType)); } throw Error.BindToVoidMethodButExpectResult(); } if (binding.Type.IsValueType && !action.ReturnType.IsValueType) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Convert(binding, action.ReturnType); } return binding; } ///////////////////////////////////////////////////////////////////////////////// private static Type GetTypeForErrorMetaObject(ICSharpBinder action, DynamicMetaObject[] args) { // This is similar to ConvertResult but has fewer things to worry about. if (action is CSharpInvokeConstructorBinder) { Debug.Assert(args != null); Debug.Assert(args.Length != 0); Debug.Assert(args[0].Value is Type); return args[0].Value as Type; } return action.ReturnType; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsIncrementOrDecrementActionOnLocal(ICSharpBinder action) => action is CSharpUnaryOperationBinder operatorPayload && (operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement); ///////////////////////////////////////////////////////////////////////////////// internal static T[] Cons<T>(T sourceHead, T[] sourceTail) { if (sourceTail?.Length != 0) { T[] array = new T[sourceTail.Length + 1]; array[0] = sourceHead; sourceTail.CopyTo(array, 1); return array; } return new[] { sourceHead }; } internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast) { if (sourceMiddle?.Length != 0) { T[] array = new T[sourceMiddle.Length + 2]; array[0] = sourceHead; array[array.Length - 1] = sourceLast; sourceMiddle.CopyTo(array, 1); return array; } return new[] { sourceHead, sourceLast }; } ///////////////////////////////////////////////////////////////////////////////// internal static T[] ToArray<T>(IEnumerable<T> source) => source == null ? Array.Empty<T>() : source.ToArray(); ///////////////////////////////////////////////////////////////////////////////// internal static CallInfo CreateCallInfo(ref IEnumerable<CSharpArgumentInfo> argInfos, int discard) { // This function converts the C# Binder's notion of argument information to the // DLR's notion. The DLR counts arguments differently than C#. Here are some // examples: // Expression Binder C# ArgInfos DLR CallInfo // // d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3 // d(1, 2, 3); CSharpInvokeBinder 4 3 // d[1, 2] = 3; CSharpSetIndexBinder 4 2 // d[1, 2, 3] CSharpGetIndexBinder 4 3 // // The "discard" parameter tells this function how many of the C# arg infos it // should not count as DLR arguments. int argCount = 0; List<string> argNames = new List<string>(); CSharpArgumentInfo[] infoArray = ToArray(argInfos); argInfos = infoArray; // Write back the array to allow single enumeration. foreach (CSharpArgumentInfo info in infoArray) { if (info.NamedArgument) { argNames.Add(info.Name); } ++argCount; } Debug.Assert(discard <= argCount); Debug.Assert(argNames.Count <= argCount - discard); return new CallInfo(argCount - discard, argNames); } internal static string GetCLROperatorName(this ExpressionType p) => p switch { // Binary Operators ExpressionType.Add => SpecialNames.CLR_Add, ExpressionType.Subtract => SpecialNames.CLR_Subtract, ExpressionType.Multiply => SpecialNames.CLR_Multiply, ExpressionType.Divide => SpecialNames.CLR_Division, ExpressionType.Modulo => SpecialNames.CLR_Modulus, ExpressionType.LeftShift => SpecialNames.CLR_LShift, ExpressionType.RightShift => SpecialNames.CLR_RShift, ExpressionType.LessThan => SpecialNames.CLR_LT, ExpressionType.GreaterThan => SpecialNames.CLR_GT, ExpressionType.LessThanOrEqual => SpecialNames.CLR_LTE, ExpressionType.GreaterThanOrEqual => SpecialNames.CLR_GTE, ExpressionType.Equal => SpecialNames.CLR_Equality, ExpressionType.NotEqual => SpecialNames.CLR_Inequality, ExpressionType.And => SpecialNames.CLR_BitwiseAnd, ExpressionType.ExclusiveOr => SpecialNames.CLR_ExclusiveOr, ExpressionType.Or => SpecialNames.CLR_BitwiseOr, // "op_LogicalNot"; ExpressionType.AddAssign => SpecialNames.CLR_InPlaceAdd, ExpressionType.SubtractAssign => SpecialNames.CLR_InPlaceSubtract, ExpressionType.MultiplyAssign => SpecialNames.CLR_InPlaceMultiply, ExpressionType.DivideAssign => SpecialNames.CLR_InPlaceDivide, ExpressionType.ModuloAssign => SpecialNames.CLR_InPlaceModulus, ExpressionType.AndAssign => SpecialNames.CLR_InPlaceBitwiseAnd, ExpressionType.ExclusiveOrAssign => SpecialNames.CLR_InPlaceExclusiveOr, ExpressionType.OrAssign => SpecialNames.CLR_InPlaceBitwiseOr, ExpressionType.LeftShiftAssign => SpecialNames.CLR_InPlaceLShift, ExpressionType.RightShiftAssign => SpecialNames.CLR_InPlaceRShift, // Unary Operators ExpressionType.Negate => SpecialNames.CLR_UnaryNegation, ExpressionType.UnaryPlus => SpecialNames.CLR_UnaryPlus, ExpressionType.Not => SpecialNames.CLR_LogicalNot, ExpressionType.OnesComplement => SpecialNames.CLR_OnesComplement, ExpressionType.IsTrue => SpecialNames.CLR_True, ExpressionType.IsFalse => SpecialNames.CLR_False, ExpressionType.Increment => SpecialNames.CLR_Increment, ExpressionType.Decrement => SpecialNames.CLR_Decrement, _ => null, }; internal static int AddArgHashes(int hash, Type[] typeArguments, CSharpArgumentInfo[] argInfos) { foreach (var typeArg in typeArguments) { hash = HashHelpers.Combine(hash, typeArg.GetHashCode()); } return AddArgHashes(hash, argInfos); } internal static int AddArgHashes(int hash, CSharpArgumentInfo[] argInfos) { foreach (var argInfo in argInfos) { hash = HashHelpers.Combine(hash, (int)argInfo.Flags); var argName = argInfo.Name; if (!string.IsNullOrEmpty(argName)) { hash = HashHelpers.Combine(hash, argName.GetHashCode()); } } return hash; } internal static bool CompareArgInfos(Type[] typeArgs, Type[] otherTypeArgs, CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos) { for (int i = 0; i < typeArgs.Length; i++) { if (typeArgs[i] != otherTypeArgs[i]) { return false; } } return CompareArgInfos(argInfos, otherArgInfos); } internal static bool CompareArgInfos(CSharpArgumentInfo[] argInfos, CSharpArgumentInfo[] otherArgInfos) { for (int i = 0; i < argInfos.Length; i++) { var argInfo = argInfos[i]; var otherArgInfo = otherArgInfos[i]; if (argInfo.Flags != otherArgInfo.Flags || argInfo.Name != otherArgInfo.Name) { return false; } } return true; } #if !ENABLECOMBINDER internal static void ThrowIfUsingDynamicCom(DynamicMetaObject target) { if (!BinderHelper.IsWindowsRuntimeObject(target) && target.LimitType.IsCOMObject) { throw ErrorHandling.Error(ErrorCode.ERR_DynamicBindingComUnsupported); } } #endif } }
// // SlidingWindowPicker.cs // // Authors: // Karthik Kailash karthik.l.kailash@gmail.com // David Sanghera dsanghera@gmail.com // // Copyright (C) 2006 Karthik Kailash, David Sanghera // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Text; using OctoTorrent; using OctoTorrent.Common; using OctoTorrent.Client; using OctoTorrent.Client.Messages; using OctoTorrent.Client.Messages.Standard; using OctoTorrent.Client.Messages.FastPeer; using System.Diagnostics; namespace OctoTorrent.Client { /// <summary> /// Generates a sliding window with high, medium, and low priority sets. The high priority set is downloaded first and in order. /// The medium and low priority sets are downloaded rarest first. /// /// This is intended to be used with a BitTorrent streaming application. /// /// The high priority set represents pieces that are needed SOON. This set is updated by calling code, to adapt for events /// (e.g. user fast-forwards or seeks, etc.) /// </summary> public class SlidingWindowPicker : PiecePicker { #region Member Variables private int ratio = 4; // ratio from medium priority to high priority set size private int highPrioritySetSize; // size of high priority set, in pieces // this represents the last byte played in a video player, as the high priority // set designates pieces that are needed VERY SOON private int highPrioritySetStart; // gets updated by calling code, or as pieces get downloaded /// <summary> /// Gets or sets first "high priority" piece. The n pieces after this will be requested in-order, /// the rest of the file will be treated rarest-first /// </summary> public int HighPrioritySetStart { get { return this.highPrioritySetStart; } set { if (this.highPrioritySetStart < value) this.highPrioritySetStart = value; } } /// <summary> /// Gets or sets the size, in pieces, of the high priority set. /// </summary> public int HighPrioritySetSize { get { return this.highPrioritySetSize; } set { this.highPrioritySetSize = value; } } public int MediumPrioritySetStart { get { return HighPrioritySetStart + HighPrioritySetSize + 1; } } /// <summary> /// This is the size ratio between the medium and high priority sets. Equivalent to mu in Tribler's Give-to-get paper. /// Default value is 4. /// </summary> public int MediumToHighRatio { get { return ratio; } set { ratio = value; } } /// <summary> /// Read-only value for size of the medium priority set. To set the medium priority size, use MediumToHighRatio. /// </summary> public int MediumPrioritySetSize { get { return this.highPrioritySetSize * ratio; } } #endregion Member Variables #region Constructors /// <summary> /// Empty constructor for changing piece pickers /// </summary> public SlidingWindowPicker(PiecePicker picker) : base(picker) { } /// <summary> /// Creates a new piece picker with support for prioritization of files. The sliding window will be positioned to the start /// of the first file to be downloaded /// </summary> /// <param name="bitField">The bitfield associated with the torrent</param> /// <param name="torrentFiles">The files that are available in this torrent</param> /// <param name="highPrioritySetSize">Size of high priority set</param> internal SlidingWindowPicker(PiecePicker picker, int highPrioritySetSize) : this(picker, highPrioritySetSize, 4) { } /// <summary> /// Create a new SlidingWindowPicker with the given set sizes. The sliding window will be positioned to the start /// of the first file to be downloaded /// </summary> /// <param name="bitField">The bitfield associated with the torrent</param> /// <param name="torrentFiles">The files that are available in this torrent</param> /// <param name="highPrioritySetSize">Size of high priority set</param> /// <param name="mediumToHighRatio">Size of medium priority set as a multiple of the high priority set size</param> internal SlidingWindowPicker(PiecePicker picker, int highPrioritySetSize, int mediumToHighRatio) : base(picker) { this.highPrioritySetSize = highPrioritySetSize; this.ratio = mediumToHighRatio; } /// <summary> /// /// </summary> /// <param name="ownBitfield"></param> /// <param name="files"></param> /// <param name="requests"></param> /// <param name="unhashedPieces"></param> public override void Initialise(BitField bitfield, TorrentFile[] files, IEnumerable<Piece> requests) { base.Initialise(bitfield, files, requests); // set the high priority set start to the beginning of the first file that we have to download foreach (TorrentFile file in files) { if (file.Priority == Priority.DoNotDownload) this.highPrioritySetStart = file.EndPieceIndex; else break; } } #endregion #region Methods public override MessageBundle PickPiece(PeerId id, BitField peerBitfield, List<PeerId> otherPeers, int count, int startIndex, int endIndex) { MessageBundle bundle; int start, end; if (HighPrioritySetStart >= startIndex && HighPrioritySetStart <= endIndex) { start = HighPrioritySetStart; end = Math.Min(endIndex, HighPrioritySetStart + HighPrioritySetSize - 1); if ((bundle = base.PickPiece(id, peerBitfield, otherPeers, count, start, end)) != null) return bundle; } if (MediumPrioritySetStart >= startIndex && MediumPrioritySetStart <= endIndex) { start = MediumPrioritySetStart; end = Math.Min(endIndex, MediumPrioritySetStart + MediumPrioritySetSize - 1); if ((bundle = base.PickPiece(id, peerBitfield, otherPeers, count, start, end)) != null) return bundle; } return base.PickPiece(id, peerBitfield, otherPeers, count, startIndex, endIndex); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions.Interpreter { internal interface IInstructionProvider { void AddInstructions(LightCompiler compiler); } internal abstract partial class Instruction { public const int UnknownInstrIndex = int.MaxValue; public virtual int ConsumedStack { get { return 0; } } public virtual int ProducedStack { get { return 0; } } public virtual int ConsumedContinuations { get { return 0; } } public virtual int ProducedContinuations { get { return 0; } } public int StackBalance { get { return ProducedStack - ConsumedStack; } } public int ContinuationsBalance { get { return ProducedContinuations - ConsumedContinuations; } } public abstract int Run(InterpretedFrame frame); public abstract string InstructionName { get; } public override string ToString() { return InstructionName + "()"; } public virtual string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects) { return ToString(); } public virtual object GetDebugCookie(LightCompiler compiler) { return null; } // throws NRE when o is null protected static void NullCheck(object o) { if (o == null) { o.GetType(); } } } internal class NullCheckInstruction : Instruction { public static readonly Instruction Instance = new NullCheckInstruction(); private NullCheckInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Unbox"; } } public override int Run(InterpretedFrame frame) { if (frame.Peek() == null) { throw new NullReferenceException(); } return +1; } } internal abstract class NotInstruction : Instruction { public static Instruction _Bool, _Int64, _Int32, _Int16, _UInt64, _UInt32, _UInt16, _Byte, _SByte; private NotInstruction() { } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Not"; } } private class BoolNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((bool)value ? ScriptingRuntimeHelpers.False : ScriptingRuntimeHelpers.True); } return +1; } } private class Int64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int64)~(Int64)value); } return +1; } } private class Int32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int32)(~(Int32)value)); } return +1; } } private class Int16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((Int16)(~(Int16)value)); } return +1; } } private class UInt64Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt64)(~(UInt64)value)); } return +1; } } private class UInt32Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt32)(~(UInt32)value)); } return +1; } } private class UInt16Not : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((UInt16)(~(UInt16)value)); } return +1; } } private class ByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(Byte)(~(Byte)value)); } return +1; } } private class SByteNot : NotInstruction { public override int Run(InterpretedFrame frame) { var value = frame.Pop(); if (value == null) { frame.Push(null); } else { frame.Push((object)(SByte)(~(SByte)value)); } return +1; } } public static Instruction Create(Type t) { switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(t))) { case TypeCode.Boolean: return _Bool ?? (_Bool = new BoolNot()); case TypeCode.Int64: return _Int64 ?? (_Int64 = new Int64Not()); case TypeCode.Int32: return _Int32 ?? (_Int32 = new Int32Not()); case TypeCode.Int16: return _Int16 ?? (_Int16 = new Int16Not()); case TypeCode.UInt64: return _UInt64 ?? (_UInt64 = new UInt64Not()); case TypeCode.UInt32: return _UInt32 ?? (_UInt32 = new UInt32Not()); case TypeCode.UInt16: return _UInt16 ?? (_UInt16 = new UInt16Not()); case TypeCode.Byte: return _Byte ?? (_Byte = new ByteNot()); case TypeCode.SByte: return _SByte ?? (_SByte = new SByteNot()); default: throw new InvalidOperationException("Not for " + t.ToString()); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Objects that provide system or application data. /// </summary> public partial class ConfigurationSet { private string _adminPassword; /// <summary> /// Required. Specifies the string representing the administrator /// password to use for the virtual machine. /// </summary> public string AdminPassword { get { return this._adminPassword; } set { this._adminPassword = value; } } private string _adminUserName; /// <summary> /// Required. Specifies the name that is used to rename the default /// administrator account. This is a required parameter after version /// 2013-03-01. /// </summary> public string AdminUserName { get { return this._adminUserName; } set { this._adminUserName = value; } } private string _computerName; /// <summary> /// Optional. Specifies the computer name for the virtual machine. If /// the computer name is not specified, a name is created based on the /// name of the role. Computer names must be 1 to 15 characters in /// length. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public string ComputerName { get { return this._computerName; } set { this._computerName = value; } } private string _configurationSetType; /// <summary> /// Specifies the configuration type for the configuration set. /// </summary> public string ConfigurationSetType { get { return this._configurationSetType; } set { this._configurationSetType = value; } } private bool? _disableSshPasswordAuthentication; /// <summary> /// Optional. Specifies whether or not SSH authentication is disabled /// for the password. This element is only used with the /// LinuxProvisioningConfiguration set. By default this value is set /// to true. /// </summary> public bool? DisableSshPasswordAuthentication { get { return this._disableSshPasswordAuthentication; } set { this._disableSshPasswordAuthentication = value; } } private DomainJoinSettings _domainJoin; /// <summary> /// Optional. Contains properties that specify a domain to which the /// virtual machine will be joined. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public DomainJoinSettings DomainJoin { get { return this._domainJoin; } set { this._domainJoin = value; } } private bool? _enableAutomaticUpdates; /// <summary> /// Optional. Specifies whether automatic updates are enabled for the /// virtual machine. This element is only used with the /// WindowsProvisioningConfiguration set. The default value is false. /// </summary> public bool? EnableAutomaticUpdates { get { return this._enableAutomaticUpdates; } set { this._enableAutomaticUpdates = value; } } private string _hostName; /// <summary> /// Required. Specifies the host name for the VM. Host names are ASCII /// character strings 1 to 64 characters in length. This element is /// only used with the LinuxProvisioningConfiguration set. /// </summary> public string HostName { get { return this._hostName; } set { this._hostName = value; } } private IList<InputEndpoint> _inputEndpoints; /// <summary> /// Contains a collection of external endpoints for the virtual /// machine. This element is only used with the /// NetworkConfigurationSet type. /// </summary> public IList<InputEndpoint> InputEndpoints { get { return this._inputEndpoints; } set { this._inputEndpoints = value; } } private bool? _resetPasswordOnFirstLogon; /// <summary> /// Optional. Specifies whether password should be reset the first time /// the administrator logs in. /// </summary> public bool? ResetPasswordOnFirstLogon { get { return this._resetPasswordOnFirstLogon; } set { this._resetPasswordOnFirstLogon = value; } } private SshSettings _sshSettings; /// <summary> /// Optional. Specifies the SSH public keys and key pairs to populate /// in the image during provisioning. This element is only used with /// the LinuxProvisioningConfiguration set. /// </summary> public SshSettings SshSettings { get { return this._sshSettings; } set { this._sshSettings = value; } } private string _staticVirtualNetworkIPAddress; /// <summary> /// Optional. Specifies a Customer Address, i.e. an IP address assigned /// to a VM in a VNet's SubNet, for example: 10.0.0.4. /// </summary> public string StaticVirtualNetworkIPAddress { get { return this._staticVirtualNetworkIPAddress; } set { this._staticVirtualNetworkIPAddress = value; } } private IList<StoredCertificateSettings> _storedCertificateSettings; /// <summary> /// Optional. Contains a list of service certificates with which to /// provision to the new role. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public IList<StoredCertificateSettings> StoredCertificateSettings { get { return this._storedCertificateSettings; } set { this._storedCertificateSettings = value; } } private IList<string> _subnetNames; /// <summary> /// The list of Virtual Network subnet names that the deployment /// belongs to. This element is only used with the /// NetworkConfigurationSet type. /// </summary> public IList<string> SubnetNames { get { return this._subnetNames; } set { this._subnetNames = value; } } private string _timeZone; /// <summary> /// Optional. Specifies the time zone for the virtual machine. This /// element is only used with the WindowsProvisioningConfiguration /// set. For a complete list of supported time zone entries, you can: /// Refer to the values listed in the registry entry /// HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows /// NT\\CurrentVersion\\Time Zones on a computer running Windows 7, /// Windows Server 2008, and Windows Server 2008 R2. You can use the /// tzutil command-line tool to list the valid time. The tzutil tool /// is installed by default on Windows 7, Windows Server 2008, and /// Windows Server 2008 R2. /// </summary> public string TimeZone { get { return this._timeZone; } set { this._timeZone = value; } } private string _userName; /// <summary> /// Required. Specifies the name of a user to be created in the sudoer /// group of the virtual machine. User names are ASCII character /// strings 1 to 32 characters in length. This element is only used /// with the LinuxProvisioningConfiguration set. /// </summary> public string UserName { get { return this._userName; } set { this._userName = value; } } private string _userPassword; /// <summary> /// Required. Specifies the password for user name. Passwords are ASCII /// character strings 6 to 72 characters in length. This element is /// only used with the LinuxProvisioningConfiguration set. /// </summary> public string UserPassword { get { return this._userPassword; } set { this._userPassword = value; } } private WindowsRemoteManagementSettings _windowsRemoteManagement; /// <summary> /// Optional. Configures the Windows Remote Management service on the /// virtual machine, which enables remote Windows PowerShell. /// </summary> public WindowsRemoteManagementSettings WindowsRemoteManagement { get { return this._windowsRemoteManagement; } set { this._windowsRemoteManagement = value; } } /// <summary> /// Initializes a new instance of the ConfigurationSet class. /// </summary> public ConfigurationSet() { this._inputEndpoints = new List<InputEndpoint>(); this._storedCertificateSettings = new List<StoredCertificateSettings>(); this._subnetNames = new List<string>(); } } }
namespace Boxed.Templates.FunctionalTest { using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using ApiTemplate.ViewModels; using Boxed.AspNetCore; using Boxed.DotnetNewTest; using Xunit; using Xunit.Abstractions; [Trait("Template", "API")] public class ApiTemplateTest { private const string TemplateName = "api"; private const string SolutionFileName = "ApiTemplate.sln"; private static readonly string[] DefaultArguments = new string[] { "no-open-todo=true", }; public ApiTemplateTest(ITestOutputHelper testOutputHelper) { if (testOutputHelper is null) { throw new ArgumentNullException(nameof(testOutputHelper)); } TestLogger.WriteMessage = testOutputHelper.WriteLine; } [Theory] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "false")] [InlineData("ApiDefaults")] [InlineData("ApiNoForwardedHeaders", "forwarded-headers=false")] [InlineData("ApiNoHostFiltering", "host-filtering=false")] [InlineData("ApiNoFwdHdrsOrHostFilter", "forwarded-headers=false", "host-filtering=false")] [InlineData("ApiStyleCop", "style-cop=true")] public async Task RestoreBuildTest_ApiDefaults_SuccessfulAsync(string name, params string[] arguments) { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync(TemplateName, name, DefaultArguments.ToArguments(arguments)) .ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); } } [Theory] [Trait("IsUsingDocker", "true")] [Trait("IsUsingDotnetRun", "false")] [InlineData("ApiDefaults")] public async Task Cake_ApiDefaults_SuccessfulAsync(string name, params string[] arguments) { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync(TemplateName, name, DefaultArguments.ToArguments(arguments)) .ConfigureAwait(false); await project.DotnetToolRestoreAsync().ConfigureAwait(false); await project.DotnetCakeAsync(timeout: TimeSpan.FromMinutes(5)).ConfigureAwait(false); } } [Fact] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "true")] public async Task RestoreBuildTestRun_ApiDefaults_SuccessfulAsync() { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory.DotnetNewAsync(TemplateName, "ApiDefaults").ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); await project .DotnetRunAsync( Path.Join("Source", "ApiDefaults"), ReadinessCheck.StatusSelfAsync, async (httpClient, httpsClient) => { var httpResponse = await httpClient .GetAsync(new Uri("status", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); var statusResponse = await httpsClient .GetAsync(new Uri("status", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, statusResponse.StatusCode); Assert.Equal(ContentType.Text, statusResponse.Content.Headers.ContentType.MediaType); var statusSelfResponse = await httpsClient .GetAsync(new Uri("status/self", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, statusSelfResponse.StatusCode); Assert.Equal(ContentType.Text, statusSelfResponse.Content.Headers.ContentType.MediaType); var carsResponse = await httpsClient .GetAsync(new Uri("cars", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, carsResponse.StatusCode); Assert.Equal(ContentType.RestfulJson, carsResponse.Content.Headers.ContentType.MediaType); var postCarResponse = await httpsClient .PostAsJsonAsync(new Uri("cars", UriKind.Relative), new SaveCar()) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.BadRequest, postCarResponse.StatusCode); Assert.Equal(ContentType.ProblemJson, postCarResponse.Content.Headers.ContentType.MediaType); var notAcceptableCarsRequest = new HttpRequestMessage( HttpMethod.Get, new Uri("cars", UriKind.Relative)); notAcceptableCarsRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(ContentType.Text)); var notAcceptableCarsResponse = await httpsClient .SendAsync(notAcceptableCarsRequest) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.NotAcceptable, notAcceptableCarsResponse.StatusCode); var swaggerJsonResponse = await httpsClient .GetAsync(new Uri("swagger/v1/swagger.json", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, swaggerJsonResponse.StatusCode); Assert.Equal(ContentType.Json, swaggerJsonResponse.Content.Headers.ContentType.MediaType); var robotsTxtResponse = await httpsClient .GetAsync(new Uri("robots.txt", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, robotsTxtResponse.StatusCode); Assert.Equal(ContentType.Text, robotsTxtResponse.Content.Headers.ContentType.MediaType); var securityTxtResponse = await httpsClient .GetAsync(new Uri(".well-known/security.txt", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, securityTxtResponse.StatusCode); Assert.Equal(ContentType.Text, securityTxtResponse.Content.Headers.ContentType.MediaType); var humansTxtResponse = await httpsClient .GetAsync(new Uri("humans.txt", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, humansTxtResponse.StatusCode); Assert.Equal(ContentType.Text, humansTxtResponse.Content.Headers.ContentType.MediaType); }, timeout: TimeSpan.FromMinutes(2)) .ConfigureAwait(false); } } [Fact] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "true")] public async Task RestoreBuildTestRun_HealthCheckFalse_SuccessfulAsync() { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync( TemplateName, "ApiHealthCheckFalse", DefaultArguments.ToArguments(new string[] { "health-check=false" })) .ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); await project .DotnetRunAsync( Path.Join("Source", "ApiHealthCheckFalse"), ReadinessCheck.FaviconAsync, async (httpClient, httpsClient) => { var statusResponse = await httpsClient .GetAsync(new Uri("status", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.NotFound, statusResponse.StatusCode); var statusSelfResponse = await httpsClient .GetAsync(new Uri("status/self", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.NotFound, statusSelfResponse.StatusCode); }) .ConfigureAwait(false); } } [Fact] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "true")] public async Task RestoreBuildTestRun_HttpsEverywhereFalse_SuccessfulAsync() { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync( TemplateName, "ApiHttpsEverywhereFalse", DefaultArguments.ToArguments(new string[] { "https-everywhere=false" })) .ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); await project .DotnetRunAsync( Path.Join("Source", "ApiHttpsEverywhereFalse"), ReadinessCheck.StatusSelfOverHttpAsync, async (httpClient, httpsClient) => { var statusResponse = await httpClient .GetAsync(new Uri("status", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, statusResponse.StatusCode); }) .ConfigureAwait(false); var files = new DirectoryInfo(project.DirectoryPath).GetFiles("*.*", SearchOption.AllDirectories); var dockerfileInfo = files.First(x => x.Name == "Dockerfile"); var dockerfile = File.ReadAllText(dockerfileInfo.FullName); Assert.DoesNotContain("443", dockerfile, StringComparison.Ordinal); } } [Fact] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "true")] public async Task RestoreBuildTestRun_SwaggerFalse_SuccessfulAsync() { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync( TemplateName, "ApiSwaggerFalse", DefaultArguments.ToArguments(new string[] { "swagger=false" })) .ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); await project .DotnetRunAsync( Path.Join("Source", "ApiSwaggerFalse"), ReadinessCheck.StatusSelfAsync, async (httpClient, httpsClient) => { var swaggerJsonResponse = await httpsClient .GetAsync(new Uri("swagger/v1/swagger.json", UriKind.Relative)) .ConfigureAwait(false); Assert.Equal(HttpStatusCode.NotFound, swaggerJsonResponse.StatusCode); }) .ConfigureAwait(false); } } [Fact] [Trait("IsUsingDocker", "false")] [Trait("IsUsingDotnetRun", "false")] public async Task RestoreBuildTestRun_DockerFalse_SuccessfulAsync() { await InstallTemplateAsync().ConfigureAwait(false); using (var tempDirectory = TempDirectory.NewTempDirectory()) { var project = await tempDirectory .DotnetNewAsync( TemplateName, "ApiDockerFalse", DefaultArguments.ToArguments(new string[] { "docker=false" })) .ConfigureAwait(false); await project.DotnetRestoreAsync().ConfigureAwait(false); await project.DotnetBuildAsync().ConfigureAwait(false); await project.DotnetTestAsync().ConfigureAwait(false); await project.DotnetToolRestoreAsync().ConfigureAwait(false); await project.DotnetCakeAsync(timeout: TimeSpan.FromMinutes(3)).ConfigureAwait(false); var files = new DirectoryInfo(project.DirectoryPath).GetFiles("*.*", SearchOption.AllDirectories); Assert.DoesNotContain(files, x => x.Name == ".dockerignore"); Assert.DoesNotContain(files, x => x.Name == "Dockerfile"); var cake = await File.ReadAllTextAsync(files.Single(x => x.Name == "build.cake").FullName).ConfigureAwait(false); Assert.DoesNotContain(cake, "Docker", StringComparison.Ordinal); } } private static Task InstallTemplateAsync() => DotnetNew.InstallAsync<ApiTemplateTest>(SolutionFileName); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using Microsoft.TeamFoundation.Server; using Microsoft.TeamFoundation.VersionControl.Client; using Microsoft.TeamFoundation.WorkItemTracking.Client; using SEP.Extensions; using Sep.Git.Tfs.Commands; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Core.TfsInterop; using Sep.Git.Tfs.Util; using StructureMap; using ChangeType = Microsoft.TeamFoundation.Server.ChangeType; namespace Sep.Git.Tfs.VsCommon { public abstract class TfsHelperBase : ITfsHelper { private readonly TextWriter _stdout; private readonly TfsApiBridge _bridge; private readonly IContainer _container; public TfsHelperBase(TextWriter stdout, TfsApiBridge bridge, IContainer container) { _stdout = stdout; _bridge = bridge; _container = container; } public abstract string TfsClientLibraryVersion { get; } public string Url { get; set; } public string Username { get; set; } public string Password { get; set; } public bool HasCredentials { get { return !String.IsNullOrEmpty(Username); } } public abstract void EnsureAuthenticated(); private string[] _legacyUrls; public string[] LegacyUrls { get { return _legacyUrls ?? (_legacyUrls = new string[0]); } set { _legacyUrls = value; } } protected NetworkCredential GetCredential() { var idx = Username.IndexOf('\\'); if (idx >= 0) { string domain = Username.Substring(0, idx); string login = Username.Substring(idx + 1); return new NetworkCredential(login, Password, domain); } return new NetworkCredential(Username, Password); } protected abstract T GetService<T>(); protected VersionControlServer VersionControl { get { var versionControlServer = GetService<VersionControlServer>(); versionControlServer.NonFatalError += NonFatalError; return versionControlServer; } } private WorkItemStore WorkItems { get { return GetService<WorkItemStore>(); } } private void NonFatalError(object sender, ExceptionEventArgs e) { _stdout.WriteLine(e.Failure.Message); Trace.WriteLine("Failure: " + e.Failure.Inspect(), "tfs non-fatal error"); Trace.WriteLine("Exception: " + e.Exception.Inspect(), "tfs non-fatal error"); } private IGroupSecurityService GroupSecurityService { get { return GetService<IGroupSecurityService>(); } } public IEnumerable<ITfsChangeset> GetChangesets(string path, long startVersion, GitTfsRemote remote) { var changesets = VersionControl.QueryHistory(path, VersionSpec.Latest, 0, RecursionType.Full, null, new ChangesetVersionSpec((int) startVersion), VersionSpec.Latest, int.MaxValue, true, true, true); return changesets.Cast<Changeset>() .OrderBy(changeset => changeset.ChangesetId) .Select(changeset => BuildTfsChangeset(changeset, remote)); } private ITfsChangeset BuildTfsChangeset(Changeset changeset, GitTfsRemote remote) { var tfsChangeset = _container.With<ITfsHelper>(this).With<IChangeset>(_bridge.Wrap<WrapperForChangeset, Changeset>(changeset)).GetInstance<TfsChangeset>(); tfsChangeset.Summary = new TfsChangesetInfo {ChangesetId = changeset.ChangesetId, Remote = remote}; return tfsChangeset; } public void WithWorkspace(string localDirectory, IGitTfsRemote remote, TfsChangesetInfo versionToFetch, Action<ITfsWorkspace> action) { var workspace = GetWorkspace(localDirectory, remote.TfsRepositoryPath); try { var tfsWorkspace = _container.With("localDirectory").EqualTo(localDirectory) .With("remote").EqualTo(remote) .With("contextVersion").EqualTo(versionToFetch) .With("workspace").EqualTo(_bridge.Wrap<WrapperForWorkspace, Workspace>(workspace)) .With("tfsHelper").EqualTo(this) .GetInstance<TfsWorkspace>(); action(tfsWorkspace); } finally { workspace.Delete(); } } private Workspace GetWorkspace(string localDirectory, string repositoryPath) { try { var workspace = VersionControl.CreateWorkspace(GenerateWorkspaceName()); workspace.CreateMapping(new WorkingFolder(repositoryPath, localDirectory)); return workspace; } catch (MappingConflictException e) { throw new GitTfsException(e.Message, new[] {"Run 'git tfs cleanup-workspaces' to remove the workspace."}, e); } } private string GenerateWorkspaceName() { return "git-tfs-" + Guid.NewGuid(); } public abstract long ShowCheckinDialog(IWorkspace workspace, IPendingChange[] pendingChanges, IEnumerable<IWorkItemCheckedInfo> checkedInfos, string checkinComment); public void CleanupWorkspaces(string workingDirectory) { Trace.WriteLine("Looking for workspaces mapped to @\"" + workingDirectory + "\"...", "cleanup-workspaces"); var workspace = VersionControl.TryGetWorkspace(workingDirectory); if (workspace != null) { Trace.WriteLine("Found mapping in workspace \"" + workspace.DisplayName + "\".", "cleanup-workspaces"); if (workspace.Folders.Length == 1) { _stdout.WriteLine("Removing workspace \"" + workspace.DisplayName + "\"."); workspace.Delete(); } else { foreach (var mapping in workspace.Folders.Where(f => Path.GetFullPath(f.LocalItem).ToLower() == Path.GetFullPath(workingDirectory).ToLower())) { _stdout.WriteLine("Removing @\"" + mapping.LocalItem + "\" from workspace \"" + workspace.DisplayName + "\"."); workspace.DeleteMapping(mapping); } } } } public bool HasShelveset(string shelvesetName) { var matchingShelvesets = VersionControl.QueryShelvesets(shelvesetName, GetAuthenticatedUser()); return matchingShelvesets != null && matchingShelvesets.Length > 0; } protected abstract string GetAuthenticatedUser(); public abstract bool CanShowCheckinDialog { get; } public ITfsChangeset GetShelvesetData(IGitTfsRemote remote, string shelvesetOwner, string shelvesetName) { shelvesetOwner = shelvesetOwner == "all" ? null : (shelvesetOwner ?? GetAuthenticatedUser()); var shelvesets = VersionControl.QueryShelvesets(shelvesetName, shelvesetOwner); if (shelvesets.Length != 1) { throw new GitTfsException("Unable to find " + shelvesetOwner + "'s shelveset \"" + shelvesetName + "\" (" + shelvesets.Length + " matches).") .WithRecommendation("Try providing the shelveset owner."); } var shelveset = shelvesets.First(); var change = VersionControl.QueryShelvedChanges(shelveset).Single(); var wrapperForVersionControlServer = _bridge.Wrap<WrapperForVersionControlServer, VersionControlServer>(VersionControl); // TODO - containerify this (no `new`)! var fakeChangeset = new FakeChangeset(shelveset, change, wrapperForVersionControlServer, _bridge); var tfsChangeset = new TfsChangeset(remote.Tfs, fakeChangeset, _stdout) { Summary = new TfsChangesetInfo { Remote = remote } }; return tfsChangeset; } public int ListShelvesets(ShelveList shelveList, IGitTfsRemote remote) { var shelvesetOwner = shelveList.Owner == "all" ? null : (shelveList.Owner ?? GetAuthenticatedUser()); IEnumerable<Shelveset> shelvesets; try { shelvesets = VersionControl.QueryShelvesets(null, shelvesetOwner); } catch(IdentityNotFoundException e) { _stdout.WriteLine("User '{0}' not found", shelveList.Owner); return GitTfsExitCodes.InvalidArguments; } if (shelvesets.Empty()) { _stdout.WriteLine("No changesets found."); return GitTfsExitCodes.OK; } string sortBy = shelveList.SortBy; if (sortBy != null) { switch (sortBy.ToLowerInvariant()) { case "date": shelvesets = shelvesets.OrderBy(s => s.CreationDate); break; case "owner": shelvesets = shelvesets.OrderBy(s => s.OwnerName); break; case "name": shelvesets = shelvesets.OrderBy(s => s.Name); break; case "comment": shelvesets = shelvesets.OrderBy(s => s.Comment); break; default: _stdout.WriteLine("ERROR: sorting criteria '{0}' is invalid. Possible values are: date, owner, name, comment", sortBy); return GitTfsExitCodes.InvalidArguments; } } if (shelveList.FullFormat) WriteShelvesetsToStdoutDetailed(shelvesets); else WriteShelvesetsToStdout(shelvesets); return GitTfsExitCodes.OK; } private void WriteShelvesetsToStdout(IEnumerable<Shelveset> shelvesets) { foreach (var shelveset in shelvesets) { _stdout.WriteLine(" {0,-20} {1,-20}", shelveset.OwnerName, shelveset.Name); } } private void WriteShelvesetsToStdoutDetailed(IEnumerable<Shelveset> shelvesets) { foreach (var shelveset in shelvesets) { _stdout.WriteLine("Name : {0}", shelveset.Name); _stdout.WriteLine("Owner : {0}", shelveset.OwnerName); _stdout.WriteLine("Date : {0:g}", shelveset.CreationDate); _stdout.WriteLine("Comment: {0}", shelveset.Comment); _stdout.WriteLine(); } } #region Fake classes for unshelve private class FakeChangeset : IChangeset { private readonly Shelveset _shelveset; private readonly PendingSet _pendingSet; private readonly IVersionControlServer _versionControlServer; private readonly TfsApiBridge _bridge; private readonly IChange[] _changes; public FakeChangeset(Shelveset shelveset, PendingSet pendingSet, IVersionControlServer versionControlServer, TfsApiBridge bridge) { _shelveset = shelveset; _versionControlServer = versionControlServer; _bridge = bridge; _pendingSet = pendingSet; _changes = _pendingSet.PendingChanges.Select(x => new FakeChange(x, _bridge, versionControlServer)).Cast<IChange>().ToArray(); } public IChange[] Changes { get { return _changes; } } public string Committer { get { return _pendingSet.OwnerName; } } public DateTime CreationDate { get { return _shelveset.CreationDate; } } public string Comment { get { return _shelveset.Comment; } } public int ChangesetId { get { return -1; } } public IVersionControlServer VersionControlServer { get { return _versionControlServer; } } } private class FakeChange : IChange { private readonly PendingChange _pendingChange; private readonly TfsApiBridge _bridge; private readonly FakeItem _fakeItem; public FakeChange(PendingChange pendingChange, TfsApiBridge bridge, IVersionControlServer versionControlServer) { _pendingChange = pendingChange; _bridge = bridge; _fakeItem = new FakeItem(_pendingChange, _bridge, versionControlServer); } public TfsChangeType ChangeType { get { return _bridge.Convert<TfsChangeType>(_pendingChange.ChangeType); } } public IItem Item { get { return _fakeItem; } } } private class FakeItem : IItem { private readonly PendingChange _pendingChange; private readonly TfsApiBridge _bridge; private readonly IVersionControlServer _versionControlServer; private long _contentLength = -1; public FakeItem(PendingChange pendingChange, TfsApiBridge bridge, IVersionControlServer versionControlServer) { _pendingChange = pendingChange; _bridge = bridge; _versionControlServer = versionControlServer; } public IVersionControlServer VersionControlServer { get { return _versionControlServer; } } public int ChangesetId { get { // some operations like applying rename gets previous item state // via looking at version of item minus 1. So will try to emulate // that this shelve is real revision. return _pendingChange.Version + 1; } } public string ServerItem { get { return _pendingChange.ServerItem; } } public decimal DeletionId { get { return _pendingChange.DeletionId; } } public TfsItemType ItemType { get { return _bridge.Convert<TfsItemType>(_pendingChange.ItemType); } } public int ItemId { get { return _pendingChange.ItemId; } } public long ContentLength { get { if (_contentLength < 0) throw new InvalidOperationException("You can't query ContentLength before downloading the file"); // It is not great solution, but at least makes the contract explicit. // We can't actually save downloaded file in this class, because if nobody asks // for it - we won't know when it is safe to delete it and it will stay in the // system forever, which is bad. Implementing finalizer to delete file is also bad solution: // suppose process was killed in the middle of many-megabyte operation on thousands of files // if we delete them as soon as they are not used - only current file will remain. Otherwise // all of them. // With this exception at least it would be evident asap that something went wrong, so we could fix it. return _contentLength; } } public Stream DownloadFile() { string temp = Path.GetTempFileName(); _pendingChange.DownloadShelvedFile(temp); var stream = new TemporaryFileStream(temp); _contentLength = stream.Length; return stream; } } #endregion public IShelveset CreateShelveset(IWorkspace workspace, string shelvesetName) { var shelveset = new Shelveset(_bridge.Unwrap<Workspace>(workspace).VersionControlServer, shelvesetName, workspace.OwnerName); return _bridge.Wrap<WrapperForShelveset, Shelveset>(shelveset); } public IIdentity GetIdentity(string username) { return _bridge.Wrap<WrapperForIdentity, Identity>(GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)); } public ITfsChangeset GetLatestChangeset(GitTfsRemote remote) { var history = VersionControl.QueryHistory(remote.TfsRepositoryPath, VersionSpec.Latest, 0, RecursionType.Full, null, null, VersionSpec.Latest, 1, true, false, false).Cast<Changeset>().ToList(); if (history.Empty()) throw new GitTfsException("error: remote TFS repository path was not found"); return BuildTfsChangeset(history.Single(), remote); } public IChangeset GetChangeset(int changesetId) { return _bridge.Wrap<WrapperForChangeset, Changeset>(VersionControl.GetChangeset(changesetId)); } public ITfsChangeset GetChangeset(int changesetId, GitTfsRemote remote) { return BuildTfsChangeset(VersionControl.GetChangeset(changesetId), remote); } public bool MatchesUrl(string tfsUrl) { return Url == tfsUrl || LegacyUrls.Contains(tfsUrl); } public IEnumerable<IWorkItemCheckinInfo> GetWorkItemInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { return GetWorkItemInfosHelper<IWorkItemCheckinInfo, WrapperForWorkItemCheckinInfo, WorkItemCheckinInfo>( workItems, checkinAction, GetWorkItemInfo); } public IEnumerable<IWorkItemCheckedInfo> GetWorkItemCheckedInfos(IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction) { return GetWorkItemInfosHelper<IWorkItemCheckedInfo, WrapperForWorkItemCheckedInfo, WorkItemCheckedInfo>( workItems, checkinAction, GetWorkItemCheckedInfo); } private IEnumerable<TInterface> GetWorkItemInfosHelper<TInterface, TWrapper, TInstance>( IEnumerable<string> workItems, TfsWorkItemCheckinAction checkinAction, Func<string, WorkItemCheckinAction, TInstance> func ) where TWrapper : class { return (from workItem in workItems select _bridge.Wrap<TWrapper, TInstance>( func(workItem, _bridge.Convert<WorkItemCheckinAction>(checkinAction)))) .Cast<TInterface>(); } private WorkItemCheckinInfo GetWorkItemInfo(string workItem, WorkItemCheckinAction checkinAction) { return new WorkItemCheckinInfo(WorkItems.GetWorkItem(Convert.ToInt32(workItem)), checkinAction); } private static WorkItemCheckedInfo GetWorkItemCheckedInfo(string workitem, WorkItemCheckinAction checkinAction) { return new WorkItemCheckedInfo(Convert.ToInt32(workitem), true, checkinAction); } } }
namespace android.opengl { [global::MonoJavaBridge.JavaClass()] public partial class GLSurfaceView : android.view.SurfaceView, android.view.SurfaceHolder_Callback { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GLSurfaceView() { InitJNI(); } protected GLSurfaceView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.opengl.GLSurfaceView.EGLConfigChooser_))] public interface EGLConfigChooser : global::MonoJavaBridge.IJavaObject { global::javax.microedition.khronos.egl.EGLConfig chooseConfig(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.opengl.GLSurfaceView.EGLConfigChooser))] public sealed partial class EGLConfigChooser_ : java.lang.Object, EGLConfigChooser { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static EGLConfigChooser_() { InitJNI(); } internal EGLConfigChooser_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _chooseConfig6058; global::javax.microedition.khronos.egl.EGLConfig android.opengl.GLSurfaceView.EGLConfigChooser.chooseConfig(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLConfigChooser_._chooseConfig6058, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as javax.microedition.khronos.egl.EGLConfig; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLConfigChooser_.staticClass, global::android.opengl.GLSurfaceView.EGLConfigChooser_._chooseConfig6058, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as javax.microedition.khronos.egl.EGLConfig; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.EGLConfigChooser_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView$EGLConfigChooser")); global::android.opengl.GLSurfaceView.EGLConfigChooser_._chooseConfig6058 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.EGLConfigChooser_.staticClass, "chooseConfig", "(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;)Ljavax/microedition/khronos/egl/EGLConfig;"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.opengl.GLSurfaceView.EGLContextFactory_))] public interface EGLContextFactory : global::MonoJavaBridge.IJavaObject { global::javax.microedition.khronos.egl.EGLContext createContext(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLConfig arg2); void destroyContext(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLContext arg2); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.opengl.GLSurfaceView.EGLContextFactory))] public sealed partial class EGLContextFactory_ : java.lang.Object, EGLContextFactory { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static EGLContextFactory_() { InitJNI(); } internal EGLContextFactory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _createContext6059; global::javax.microedition.khronos.egl.EGLContext android.opengl.GLSurfaceView.EGLContextFactory.createContext(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLConfig arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLContextFactory_._createContext6059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as javax.microedition.khronos.egl.EGLContext; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLContextFactory_.staticClass, global::android.opengl.GLSurfaceView.EGLContextFactory_._createContext6059, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as javax.microedition.khronos.egl.EGLContext; } internal static global::MonoJavaBridge.MethodId _destroyContext6060; void android.opengl.GLSurfaceView.EGLContextFactory.destroyContext(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLContext arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLContextFactory_._destroyContext6060, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLContextFactory_.staticClass, global::android.opengl.GLSurfaceView.EGLContextFactory_._destroyContext6060, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.EGLContextFactory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView$EGLContextFactory")); global::android.opengl.GLSurfaceView.EGLContextFactory_._createContext6059 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.EGLContextFactory_.staticClass, "createContext", "(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLConfig;)Ljavax/microedition/khronos/egl/EGLContext;"); global::android.opengl.GLSurfaceView.EGLContextFactory_._destroyContext6060 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.EGLContextFactory_.staticClass, "destroyContext", "(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLContext;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_))] public interface EGLWindowSurfaceFactory : global::MonoJavaBridge.IJavaObject { global::javax.microedition.khronos.egl.EGLSurface createWindowSurface(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLConfig arg2, java.lang.Object arg3); void destroySurface(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLSurface arg2); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory))] public sealed partial class EGLWindowSurfaceFactory_ : java.lang.Object, EGLWindowSurfaceFactory { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static EGLWindowSurfaceFactory_() { InitJNI(); } internal EGLWindowSurfaceFactory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _createWindowSurface6061; global::javax.microedition.khronos.egl.EGLSurface android.opengl.GLSurfaceView.EGLWindowSurfaceFactory.createWindowSurface(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLConfig arg2, java.lang.Object arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._createWindowSurface6061, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as javax.microedition.khronos.egl.EGLSurface; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_.staticClass, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._createWindowSurface6061, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as javax.microedition.khronos.egl.EGLSurface; } internal static global::MonoJavaBridge.MethodId _destroySurface6062; void android.opengl.GLSurfaceView.EGLWindowSurfaceFactory.destroySurface(javax.microedition.khronos.egl.EGL10 arg0, javax.microedition.khronos.egl.EGLDisplay arg1, javax.microedition.khronos.egl.EGLSurface arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._destroySurface6062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_.staticClass, global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._destroySurface6062, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView$EGLWindowSurfaceFactory")); global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._createWindowSurface6061 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_.staticClass, "createWindowSurface", "(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLConfig;Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLSurface;"); global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_._destroySurface6062 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.EGLWindowSurfaceFactory_.staticClass, "destroySurface", "(Ljavax/microedition/khronos/egl/EGL10;Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSurface;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.opengl.GLSurfaceView.GLWrapper_))] public interface GLWrapper : global::MonoJavaBridge.IJavaObject { global::javax.microedition.khronos.opengles.GL wrap(javax.microedition.khronos.opengles.GL arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.opengl.GLSurfaceView.GLWrapper))] public sealed partial class GLWrapper_ : java.lang.Object, GLWrapper { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static GLWrapper_() { InitJNI(); } internal GLWrapper_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _wrap6063; global::javax.microedition.khronos.opengles.GL android.opengl.GLSurfaceView.GLWrapper.wrap(javax.microedition.khronos.opengles.GL arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::javax.microedition.khronos.opengles.GL>(@__env.CallObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.GLWrapper_._wrap6063, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as javax.microedition.khronos.opengles.GL; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::javax.microedition.khronos.opengles.GL>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.GLWrapper_.staticClass, global::android.opengl.GLSurfaceView.GLWrapper_._wrap6063, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as javax.microedition.khronos.opengles.GL; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.GLWrapper_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView$GLWrapper")); global::android.opengl.GLSurfaceView.GLWrapper_._wrap6063 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.GLWrapper_.staticClass, "wrap", "(Ljavax/microedition/khronos/opengles/GL;)Ljavax/microedition/khronos/opengles/GL;"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.opengl.GLSurfaceView.Renderer_))] public interface Renderer : global::MonoJavaBridge.IJavaObject { void onSurfaceCreated(javax.microedition.khronos.opengles.GL10 arg0, javax.microedition.khronos.egl.EGLConfig arg1); void onSurfaceChanged(javax.microedition.khronos.opengles.GL10 arg0, int arg1, int arg2); void onDrawFrame(javax.microedition.khronos.opengles.GL10 arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.opengl.GLSurfaceView.Renderer))] public sealed partial class Renderer_ : java.lang.Object, Renderer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Renderer_() { InitJNI(); } internal Renderer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onSurfaceCreated6064; void android.opengl.GLSurfaceView.Renderer.onSurfaceCreated(javax.microedition.khronos.opengles.GL10 arg0, javax.microedition.khronos.egl.EGLConfig arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_._onSurfaceCreated6064, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_.staticClass, global::android.opengl.GLSurfaceView.Renderer_._onSurfaceCreated6064, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onSurfaceChanged6065; void android.opengl.GLSurfaceView.Renderer.onSurfaceChanged(javax.microedition.khronos.opengles.GL10 arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_._onSurfaceChanged6065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_.staticClass, global::android.opengl.GLSurfaceView.Renderer_._onSurfaceChanged6065, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _onDrawFrame6066; void android.opengl.GLSurfaceView.Renderer.onDrawFrame(javax.microedition.khronos.opengles.GL10 arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_._onDrawFrame6066, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.Renderer_.staticClass, global::android.opengl.GLSurfaceView.Renderer_._onDrawFrame6066, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.Renderer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView$Renderer")); global::android.opengl.GLSurfaceView.Renderer_._onSurfaceCreated6064 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.Renderer_.staticClass, "onSurfaceCreated", "(Ljavax/microedition/khronos/opengles/GL10;Ljavax/microedition/khronos/egl/EGLConfig;)V"); global::android.opengl.GLSurfaceView.Renderer_._onSurfaceChanged6065 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.Renderer_.staticClass, "onSurfaceChanged", "(Ljavax/microedition/khronos/opengles/GL10;II)V"); global::android.opengl.GLSurfaceView.Renderer_._onDrawFrame6066 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.Renderer_.staticClass, "onDrawFrame", "(Ljavax/microedition/khronos/opengles/GL10;)V"); } } internal static global::MonoJavaBridge.MethodId _onResume6067; public virtual void onResume() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._onResume6067); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._onResume6067); } internal static global::MonoJavaBridge.MethodId _onPause6068; public virtual void onPause() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._onPause6068); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._onPause6068); } internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow6069; protected override void onDetachedFromWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._onDetachedFromWindow6069); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._onDetachedFromWindow6069); } internal static global::MonoJavaBridge.MethodId _setGLWrapper6070; public virtual void setGLWrapper(android.opengl.GLSurfaceView.GLWrapper arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setGLWrapper6070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setGLWrapper6070, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setDebugFlags6071; public virtual void setDebugFlags(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setDebugFlags6071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setDebugFlags6071, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDebugFlags6072; public virtual int getDebugFlags() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._getDebugFlags6072); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._getDebugFlags6072); } internal static global::MonoJavaBridge.MethodId _setRenderer6073; public virtual void setRenderer(android.opengl.GLSurfaceView.Renderer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setRenderer6073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setRenderer6073, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEGLContextFactory6074; public virtual void setEGLContextFactory(android.opengl.GLSurfaceView.EGLContextFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLContextFactory6074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLContextFactory6074, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEGLWindowSurfaceFactory6075; public virtual void setEGLWindowSurfaceFactory(android.opengl.GLSurfaceView.EGLWindowSurfaceFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLWindowSurfaceFactory6075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLWindowSurfaceFactory6075, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEGLConfigChooser6076; public virtual void setEGLConfigChooser(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLConfigChooser6076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLConfigChooser6076, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEGLConfigChooser6077; public virtual void setEGLConfigChooser(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLConfigChooser6077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLConfigChooser6077, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } internal static global::MonoJavaBridge.MethodId _setEGLConfigChooser6078; public virtual void setEGLConfigChooser(android.opengl.GLSurfaceView.EGLConfigChooser arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLConfigChooser6078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLConfigChooser6078, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setEGLContextClientVersion6079; public virtual void setEGLContextClientVersion(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setEGLContextClientVersion6079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setEGLContextClientVersion6079, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setRenderMode6080; public virtual void setRenderMode(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._setRenderMode6080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._setRenderMode6080, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getRenderMode6081; public virtual int getRenderMode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._getRenderMode6081); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._getRenderMode6081); } internal static global::MonoJavaBridge.MethodId _requestRender6082; public virtual void requestRender() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._requestRender6082); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._requestRender6082); } internal static global::MonoJavaBridge.MethodId _surfaceCreated6083; public virtual void surfaceCreated(android.view.SurfaceHolder arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._surfaceCreated6083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._surfaceCreated6083, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _surfaceDestroyed6084; public virtual void surfaceDestroyed(android.view.SurfaceHolder arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._surfaceDestroyed6084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._surfaceDestroyed6084, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _surfaceChanged6085; public virtual void surfaceChanged(android.view.SurfaceHolder arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._surfaceChanged6085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._surfaceChanged6085, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } internal static global::MonoJavaBridge.MethodId _queueEvent6086; public virtual void queueEvent(java.lang.Runnable arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView._queueEvent6086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._queueEvent6086, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _GLSurfaceView6087; public GLSurfaceView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._GLSurfaceView6087, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _GLSurfaceView6088; public GLSurfaceView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.opengl.GLSurfaceView.staticClass, global::android.opengl.GLSurfaceView._GLSurfaceView6088, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int RENDERMODE_WHEN_DIRTY { get { return 0; } } public static int RENDERMODE_CONTINUOUSLY { get { return 1; } } public static int DEBUG_CHECK_GL_ERROR { get { return 1; } } public static int DEBUG_LOG_GL_CALLS { get { return 2; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.opengl.GLSurfaceView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/opengl/GLSurfaceView")); global::android.opengl.GLSurfaceView._onResume6067 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "onResume", "()V"); global::android.opengl.GLSurfaceView._onPause6068 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "onPause", "()V"); global::android.opengl.GLSurfaceView._onDetachedFromWindow6069 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "onDetachedFromWindow", "()V"); global::android.opengl.GLSurfaceView._setGLWrapper6070 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setGLWrapper", "(Landroid/opengl/GLSurfaceView$GLWrapper;)V"); global::android.opengl.GLSurfaceView._setDebugFlags6071 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setDebugFlags", "(I)V"); global::android.opengl.GLSurfaceView._getDebugFlags6072 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "getDebugFlags", "()I"); global::android.opengl.GLSurfaceView._setRenderer6073 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setRenderer", "(Landroid/opengl/GLSurfaceView$Renderer;)V"); global::android.opengl.GLSurfaceView._setEGLContextFactory6074 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLContextFactory", "(Landroid/opengl/GLSurfaceView$EGLContextFactory;)V"); global::android.opengl.GLSurfaceView._setEGLWindowSurfaceFactory6075 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLWindowSurfaceFactory", "(Landroid/opengl/GLSurfaceView$EGLWindowSurfaceFactory;)V"); global::android.opengl.GLSurfaceView._setEGLConfigChooser6076 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLConfigChooser", "(Z)V"); global::android.opengl.GLSurfaceView._setEGLConfigChooser6077 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLConfigChooser", "(IIIIII)V"); global::android.opengl.GLSurfaceView._setEGLConfigChooser6078 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLConfigChooser", "(Landroid/opengl/GLSurfaceView$EGLConfigChooser;)V"); global::android.opengl.GLSurfaceView._setEGLContextClientVersion6079 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setEGLContextClientVersion", "(I)V"); global::android.opengl.GLSurfaceView._setRenderMode6080 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "setRenderMode", "(I)V"); global::android.opengl.GLSurfaceView._getRenderMode6081 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "getRenderMode", "()I"); global::android.opengl.GLSurfaceView._requestRender6082 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "requestRender", "()V"); global::android.opengl.GLSurfaceView._surfaceCreated6083 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "surfaceCreated", "(Landroid/view/SurfaceHolder;)V"); global::android.opengl.GLSurfaceView._surfaceDestroyed6084 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "surfaceDestroyed", "(Landroid/view/SurfaceHolder;)V"); global::android.opengl.GLSurfaceView._surfaceChanged6085 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "surfaceChanged", "(Landroid/view/SurfaceHolder;III)V"); global::android.opengl.GLSurfaceView._queueEvent6086 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "queueEvent", "(Ljava/lang/Runnable;)V"); global::android.opengl.GLSurfaceView._GLSurfaceView6087 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.opengl.GLSurfaceView._GLSurfaceView6088 = @__env.GetMethodIDNoThrow(global::android.opengl.GLSurfaceView.staticClass, "<init>", "(Landroid/content/Context;)V"); } } }
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 TeamOrganiser.Web.Api.Areas.HelpPage.Models; namespace TeamOrganiser.Web.Api.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); } } } }
namespace LaTuerca.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialC : DbMigration { public override void Up() { CreateTable( "dbo.Categorias", c => new { Id = c.Int(nullable: false, identity: true), Nombre = c.String(nullable: false, maxLength: 60), Estado = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Clientes", c => new { Id = c.Int(nullable: false, identity: true), RazonSocial = c.String(nullable: false), Documento = c.String(nullable: false), Direccion = c.String(nullable: false), Telefono = c.String(nullable: false), Celular = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Empresas", c => new { Id = c.Int(nullable: false, identity: true), Nombre = c.String(nullable: false), NombreCorto = c.String(nullable: false), Ruc = c.Int(nullable: false), Departamento = c.String(), Ciudad = c.String(), Pais = c.String(), Email = c.String(), Direccion = c.String(), Telefono = c.String(), Web = c.String(), Estado = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Marcas", c => new { Id = c.Int(nullable: false, identity: true), Nombre = c.String(nullable: false, maxLength: 60), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Modeloes", c => new { Id = c.Int(nullable: false, identity: true), NombreModelo = c.String(nullable: false, maxLength: 60), MarcaId = c.Int(nullable: false), Estado = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Marcas", t => t.MarcaId, cascadeDelete: true) .Index(t => t.MarcaId); CreateTable( "dbo.Repuestoes", c => new { Id = c.Int(nullable: false, identity: true), Nombre = c.String(nullable: false, maxLength: 60), ProveedorId = c.Int(nullable: false), ModeloId = c.Int(nullable: false), CategoriaId = c.Int(nullable: false), Stock = c.Int(nullable: false), StockMinimo = c.Int(nullable: false), StockMaximo = c.Int(nullable: false), PrecioCosto = c.Single(nullable: false), PrecioVenta1 = c.Single(nullable: false), PrecioVenta2 = c.Single(nullable: false), PrecioVenta3 = c.Single(nullable: false), Marca_Id = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Categorias", t => t.CategoriaId, cascadeDelete: true) .ForeignKey("dbo.Modeloes", t => t.ModeloId, cascadeDelete: true) .ForeignKey("dbo.Proveedors", t => t.ProveedorId, cascadeDelete: true) .ForeignKey("dbo.Marcas", t => t.Marca_Id) .Index(t => t.ProveedorId) .Index(t => t.ModeloId) .Index(t => t.CategoriaId); CreateTable( "dbo.Proveedors", c => new { Id = c.Int(nullable: false, identity: true), RazonSocial = c.String(nullable: false, maxLength: 60), Ruc = c.String(nullable: false, maxLength: 10), Direccion = c.String(nullable: false), Telefono = c.String(nullable: false), Celular = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Menus", c => new { Id = c.Int(nullable: false, identity: true), ParentId = c.Int(nullable: false), Name = c.String(nullable: false), Description = c.String(nullable: false), Action = c.String(), Controller = c.String(), Active = c.Boolean(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.Repuestoes", "Marca_Id", "dbo.Marcas"); DropForeignKey("dbo.Repuestoes", "ProveedorId", "dbo.Proveedors"); DropForeignKey("dbo.Repuestoes", "ModeloId", "dbo.Modeloes"); DropForeignKey("dbo.Repuestoes", "CategoriaId", "dbo.Categorias"); DropForeignKey("dbo.Modeloes", "MarcaId", "dbo.Marcas"); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Repuestoes", new[] { "Marca_Id" }); DropIndex("dbo.Repuestoes", new[] { "CategoriaId" }); DropIndex("dbo.Repuestoes", new[] { "ModeloId" }); DropIndex("dbo.Repuestoes", new[] { "ProveedorId" }); DropIndex("dbo.Modeloes", new[] { "MarcaId" }); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetRoles"); DropTable("dbo.Menus"); DropTable("dbo.Proveedors"); DropTable("dbo.Repuestoes"); DropTable("dbo.Modeloes"); DropTable("dbo.Marcas"); DropTable("dbo.Empresas"); DropTable("dbo.Clientes"); DropTable("dbo.Categorias"); } } }
// 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.Web.UI.StateBag.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 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.Web.UI { sealed public partial class StateBag : IStateManager, System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public StateItem Add (string key, Object value) { Contract.Requires (!string.IsNullOrEmpty(key)); return default(StateItem); } public void Clear () { } public System.Collections.IDictionaryEnumerator GetEnumerator () { return default(System.Collections.IDictionaryEnumerator); } public bool IsItemDirty (string key) { return default(bool); } public void Remove (string key) { } public void SetDirty (bool dirty) { } public void SetItemDirty (string key, bool dirty) { } public StateBag (bool ignoreCase) { } public StateBag () { } void System.Collections.ICollection.CopyTo (Array array, int index) { } void System.Collections.IDictionary.Add (Object key, Object value) { } bool System.Collections.IDictionary.Contains (Object key) { return default(bool); } void System.Collections.IDictionary.Remove (Object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return default(System.Collections.IEnumerator); } void System.Web.UI.IStateManager.LoadViewState (Object state) { } Object System.Web.UI.IStateManager.SaveViewState () { return default(Object); } void System.Web.UI.IStateManager.TrackViewState () { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public Object this [string key] { get { Contract.Requires (!string.IsNullOrEmpty(key)); return default(Object); } set { Contract.Requires (!string.IsNullOrEmpty(key)); } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } Object System.Collections.IDictionary.this [Object key] { get { return default(Object); } set { } } bool System.Web.UI.IStateManager.IsTrackingViewState { get { return default(bool); } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } #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. /*============================================================ ** ** ** ** ** ** ** Purpose: Used for binding and retrieving info about an assembly ** ** ===========================================================*/ namespace System.Reflection { using System; using System.IO; using System.Configuration.Assemblies; using System.Runtime.CompilerServices; using CultureInfo = System.Globalization.CultureInfo; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Text; [Serializable] public sealed class AssemblyName : ICloneable, ISerializable, IDeserializationCallback { // // READ ME // If you modify any of these fields, you must also update the // AssemblyBaseObject structure in object.h // private String _Name; // Name private byte[] _PublicKey; private byte[] _PublicKeyToken; private CultureInfo _CultureInfo; private String _CodeBase; // Potential location to get the file private Version _Version; private StrongNameKeyPair _StrongNameKeyPair; private SerializationInfo m_siInfo; //A temporary variable which we need during deserialization. private byte[] _HashForControl; private AssemblyHashAlgorithm _HashAlgorithm; private AssemblyHashAlgorithm _HashAlgorithmForControl; private AssemblyVersionCompatibility _VersionCompatibility; private AssemblyNameFlags _Flags; public AssemblyName() { _HashAlgorithm = AssemblyHashAlgorithm.None; _VersionCompatibility = AssemblyVersionCompatibility.SameMachine; _Flags = AssemblyNameFlags.None; } // Set and get the name of the assembly. If this is a weak Name // then it optionally contains a site. For strong assembly names, // the name partitions up the strong name's namespace public String Name { get { return _Name; } set { _Name = value; } } public Version Version { get { return _Version; } set { _Version = value; } } // Locales, internally the LCID is used for the match. public CultureInfo CultureInfo { get { return _CultureInfo; } set { _CultureInfo = value; } } public String CultureName { get { return (_CultureInfo == null) ? null : _CultureInfo.Name; } set { _CultureInfo = (value == null) ? null : new CultureInfo(value); } } public String CodeBase { get { return _CodeBase; } set { _CodeBase = value; } } public String EscapedCodeBase { get { if (_CodeBase == null) return null; else return EscapeCodeBase(_CodeBase); } } public ProcessorArchitecture ProcessorArchitecture { get { int x = (((int)_Flags) & 0x70) >> 4; if (x > 5) x = 0; return (ProcessorArchitecture)x; } set { int x = ((int)value) & 0x07; if (x <= 5) { _Flags = (AssemblyNameFlags)((int)_Flags & 0xFFFFFF0F); _Flags |= (AssemblyNameFlags)(x << 4); } } } public AssemblyContentType ContentType { get { int x = (((int)_Flags) & 0x00000E00) >> 9; if (x > 1) x = 0; return (AssemblyContentType)x; } set { int x = ((int)value) & 0x07; if (x <= 1) { _Flags = (AssemblyNameFlags)((int)_Flags & 0xFFFFF1FF); _Flags |= (AssemblyNameFlags)(x << 9); } } } // Make a copy of this assembly name. public Object Clone() { AssemblyName name = new AssemblyName(); name.Init(_Name, _PublicKey, _PublicKeyToken, _Version, _CultureInfo, _HashAlgorithm, _VersionCompatibility, _CodeBase, _Flags, _StrongNameKeyPair); name._HashForControl = _HashForControl; name._HashAlgorithmForControl = _HashAlgorithmForControl; return name; } /* * Get the AssemblyName for a given file. This will only work * if the file contains an assembly manifest. This method causes * the file to be opened and closed. */ static public AssemblyName GetAssemblyName(String assemblyFile) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); Contract.EndContractBlock(); // Assembly.GetNameInternal() will not demand path discovery // permission, so do that first. string fullPath = Path.GetFullPath(assemblyFile); return nGetFileInformation(fullPath); } internal void SetHashControl(byte[] hash, AssemblyHashAlgorithm hashAlgorithm) { _HashForControl = hash; _HashAlgorithmForControl = hashAlgorithm; } // The public key that is used to verify an assemblies // inclusion into the namespace. If the public key associated // with the namespace cannot verify the assembly the assembly // will fail to load. public byte[] GetPublicKey() { return _PublicKey; } public void SetPublicKey(byte[] publicKey) { _PublicKey = publicKey; if (publicKey == null) _Flags &= ~AssemblyNameFlags.PublicKey; else _Flags |= AssemblyNameFlags.PublicKey; } // The compressed version of the public key formed from a truncated hash. // Will throw a SecurityException if _PublicKey is invalid public byte[] GetPublicKeyToken() { if (_PublicKeyToken == null) _PublicKeyToken = nGetPublicKeyToken(); return _PublicKeyToken; } public void SetPublicKeyToken(byte[] publicKeyToken) { _PublicKeyToken = publicKeyToken; } // Flags modifying the name. So far the only flag is PublicKey, which // indicates that a full public key and not the compressed version is // present. // Processor Architecture flags are set only through ProcessorArchitecture // property and can't be set or retrieved directly // Content Type flags are set only through ContentType property and can't be // set or retrieved directly public AssemblyNameFlags Flags { get { return (AssemblyNameFlags)((uint)_Flags & 0xFFFFF10F); } set { _Flags &= unchecked((AssemblyNameFlags)0x00000EF0); _Flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F)); } } public AssemblyHashAlgorithm HashAlgorithm { get { return _HashAlgorithm; } set { _HashAlgorithm = value; } } public AssemblyVersionCompatibility VersionCompatibility { get { return _VersionCompatibility; } set { _VersionCompatibility = value; } } public StrongNameKeyPair KeyPair { get { return _StrongNameKeyPair; } set { _StrongNameKeyPair = value; } } public String FullName { get { return nToString(); } } // Returns the stringized version of the assembly name. public override String ToString() { String s = FullName; if (s == null) return base.ToString(); else return s; } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); //Allocate the serialization info and serialize our static data. info.AddValue("_Name", _Name); info.AddValue("_PublicKey", _PublicKey, typeof(byte[])); info.AddValue("_PublicKeyToken", _PublicKeyToken, typeof(byte[])); #if FEATURE_USE_LCID info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 : _CultureInfo.LCID); #endif info.AddValue("_CodeBase", _CodeBase); info.AddValue("_Version", _Version); info.AddValue("_HashAlgorithm", _HashAlgorithm, typeof(AssemblyHashAlgorithm)); info.AddValue("_HashAlgorithmForControl", _HashAlgorithmForControl, typeof(AssemblyHashAlgorithm)); info.AddValue("_StrongNameKeyPair", _StrongNameKeyPair, typeof(StrongNameKeyPair)); info.AddValue("_VersionCompatibility", _VersionCompatibility, typeof(AssemblyVersionCompatibility)); info.AddValue("_Flags", _Flags, typeof(AssemblyNameFlags)); info.AddValue("_HashForControl", _HashForControl, typeof(byte[])); } public void OnDeserialization(Object sender) { // Deserialization has already been performed if (m_siInfo == null) return; _Name = m_siInfo.GetString("_Name"); _PublicKey = (byte[])m_siInfo.GetValue("_PublicKey", typeof(byte[])); _PublicKeyToken = (byte[])m_siInfo.GetValue("_PublicKeyToken", typeof(byte[])); #if FEATURE_USE_LCID int lcid = (int)m_siInfo.GetInt32("_CultureInfo"); if (lcid != -1) _CultureInfo = new CultureInfo(lcid); #endif _CodeBase = m_siInfo.GetString("_CodeBase"); _Version = (Version)m_siInfo.GetValue("_Version", typeof(Version)); _HashAlgorithm = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm)); _StrongNameKeyPair = (StrongNameKeyPair)m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair)); _VersionCompatibility = (AssemblyVersionCompatibility)m_siInfo.GetValue("_VersionCompatibility", typeof(AssemblyVersionCompatibility)); _Flags = (AssemblyNameFlags)m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags)); try { _HashAlgorithmForControl = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm)); _HashForControl = (byte[])m_siInfo.GetValue("_HashForControl", typeof(byte[])); } catch (SerializationException) { // RTM did not have these defined _HashAlgorithmForControl = AssemblyHashAlgorithm.None; _HashForControl = null; } m_siInfo = null; } // Constructs a new AssemblyName during deserialization. internal AssemblyName(SerializationInfo info, StreamingContext context) { //The graph is not valid until OnDeserialization() has been called. m_siInfo = info; } public AssemblyName(String assemblyName) { if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); Contract.EndContractBlock(); if ((assemblyName.Length == 0) || (assemblyName[0] == '\0')) throw new ArgumentException(SR.Format_StringZeroLength); _Name = assemblyName; nInit(); } /// <summary> /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not /// match the intent of this api, this api has been broken this way since its debut and we cannot /// change its behavior now. /// </summary> public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition) { if (object.ReferenceEquals(reference, definition)) return true; if (reference == null) throw new ArgumentNullException(nameof(reference)); if (definition == null) throw new ArgumentNullException(nameof(definition)); string refName = reference.Name ?? string.Empty; string defName = definition.Name ?? string.Empty; return refName.Equals(defName, StringComparison.OrdinalIgnoreCase); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent); internal void nInit() { RuntimeAssembly dummy = null; nInit(out dummy, false, false); } internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _Flags); } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if (((uint)flags & 0xF0) == 0x70) return ProcessorArchitecture.None; if ((pek & System.Reflection.PortableExecutableKinds.PE32Plus) == System.Reflection.PortableExecutableKinds.PE32Plus) { switch (ifm) { case System.Reflection.ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case System.Reflection.ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case System.Reflection.ImageFileMachine.I386: if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; break; } } else { if (ifm == System.Reflection.ImageFileMachine.I386) { if ((pek & System.Reflection.PortableExecutableKinds.Required32Bit) == System.Reflection.PortableExecutableKinds.Required32Bit) return ProcessorArchitecture.X86; if ((pek & System.Reflection.PortableExecutableKinds.ILOnly) == System.Reflection.PortableExecutableKinds.ILOnly) return ProcessorArchitecture.MSIL; return ProcessorArchitecture.X86; } if (ifm == System.Reflection.ImageFileMachine.ARM) { return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.None; } internal void Init(String name, byte[] publicKey, byte[] publicKeyToken, Version version, CultureInfo cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, String codeBase, AssemblyNameFlags flags, StrongNameKeyPair keyPair) // Null if ref, matching Assembly if def { _Name = name; if (publicKey != null) { _PublicKey = new byte[publicKey.Length]; Array.Copy(publicKey, _PublicKey, publicKey.Length); } if (publicKeyToken != null) { _PublicKeyToken = new byte[publicKeyToken.Length]; Array.Copy(publicKeyToken, _PublicKeyToken, publicKeyToken.Length); } if (version != null) _Version = (Version)version.Clone(); _CultureInfo = cultureInfo; _HashAlgorithm = hashAlgorithm; _VersionCompatibility = versionCompatibility; _CodeBase = codeBase; _Flags = flags; _StrongNameKeyPair = keyPair; } // This call opens and closes the file, but does not add the // assembly to the domain. [MethodImplAttribute(MethodImplOptions.InternalCall)] static internal extern AssemblyName nGetFileInformation(String s); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern String nToString(); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern byte[] nGetPublicKeyToken(); static internal String EscapeCodeBase(String codebase) { if (codebase == null) return string.Empty; int position = 0; char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return codebase; return new string(dest, 0, position); } // This implementation of EscapeString has been copied from System.Private.Uri from corefx repo // - forceX characters are always escaped if found // - rsvd character will remain unescaped // // start - starting offset from input // end - the exclusive ending offset in input // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { int i = start; int prevInputPos = start; byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 fixed (char* pStr = input) { for (; i < end; ++i) { char ch = pStr[i]; // a Unicode ? if (ch > '\x7F') { short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); short count = 1; for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) ; // Is the last a high surrogate? if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) { // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair if (count == 1 || count == end - i) throw new FormatException(SR.Arg_FormatException); // need to grab one more char as a Surrogate except when it's a bogus input ++count; } dest = EnsureDestinationSize(pStr, dest, i, (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, ref destPos, prevInputPos); short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); // This is the only exception that built in UriParser can throw after a Uri ctor. // Should not happen unless the app tries to feed an invalid Unicode String if (numberOfBytes == 0) throw new FormatException(SR.Arg_FormatException); i += (count - 1); for (count = 0; count < numberOfBytes; ++count) EscapeAsciiChar((char)bytes[count], dest, ref destPos); prevInputPos = i + 1; } else if (ch == '%' && rsvd == '%') { // Means we don't reEncode '%' but check for the possible escaped sequence dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != c_DummyChar) { // leave it escaped dest[destPos++] = '%'; dest[destPos++] = pStr[i + 1]; dest[destPos++] = pStr[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } prevInputPos = i + 1; } else if (ch == force1 || ch == force2) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } } if (prevInputPos != i) { // need to fill up the dest array ? if (prevInputPos != start || dest != null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } return dest; } // // ensure destination array has enough space and contains all the needed input stuff // private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if ((object)dest != null && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } // ensuring we copied everything form the input string left before last escaping while (prevInputPos != currentInputPos) dest[destPos++] = pStr[prevInputPos++]; return dest; } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; to[pos++] = s_hexUpperChars[ch & 0xf]; } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } private static unsafe bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return (RFC3986ReservedMarks.IndexOf(c) >= 0); } internal static unsafe bool IsUnreserved(char c) { if (IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } //Only consider ASCII characters internal static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } internal static bool IsAsciiLetterOrDigit(char character) { return IsAsciiLetter(character) || (character >= '0' && character <= '9'); } private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; internal const char c_DummyChar = (char)0xFFFF; //An Invalid Unicode character used as a dummy char passed into the parameter private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC3986UnreservedMarks = @"-._~"; } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.Set, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssOsProfile", SupportsShouldProcess = true)] [OutputType(typeof(PSVirtualMachineScaleSet))] public partial class SetAzureRmVmssOsProfileCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public string ComputerNamePrefix { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public string AdminUsername { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public string AdminPassword { get; set; } [Parameter( Mandatory = false, Position = 4, ValueFromPipelineByPropertyName = true)] public string CustomData { get; set; } [Parameter( Mandatory = false, Position = 5, ValueFromPipelineByPropertyName = true)] public bool? WindowsConfigurationProvisionVMAgent { get; set; } [Parameter( Mandatory = false, Position = 6, ValueFromPipelineByPropertyName = true)] public bool? WindowsConfigurationEnableAutomaticUpdate { get; set; } [Parameter( Mandatory = false, Position = 7, ValueFromPipelineByPropertyName = true)] public string TimeZone { get; set; } [Parameter( Mandatory = false, Position = 8, ValueFromPipelineByPropertyName = true)] public AdditionalUnattendContent[] AdditionalUnattendContent { get; set; } [Parameter( Mandatory = false, Position = 9, ValueFromPipelineByPropertyName = true)] public WinRMListener[] Listener { get; set; } [Parameter( Mandatory = false, Position = 10, ValueFromPipelineByPropertyName = true)] public bool? LinuxConfigurationDisablePasswordAuthentication { get; set; } [Parameter( Mandatory = false, Position = 11, ValueFromPipelineByPropertyName = true)] public SshPublicKey[] PublicKey { get; set; } [Parameter( Mandatory = false, Position = 12, ValueFromPipelineByPropertyName = true)] public VaultSecretGroup[] Secret { get; set; } protected override void ProcessRecord() { if (ShouldProcess("VirtualMachineScaleSet", "Set")) { Run(); } } private void Run() { if (this.MyInvocation.BoundParameters.ContainsKey("ComputerNamePrefix")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.ComputerNamePrefix = this.ComputerNamePrefix; } if (this.MyInvocation.BoundParameters.ContainsKey("AdminUsername")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminUsername = this.AdminUsername; } if (this.MyInvocation.BoundParameters.ContainsKey("AdminPassword")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminPassword = this.AdminPassword; } if (this.MyInvocation.BoundParameters.ContainsKey("CustomData")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.CustomData = this.CustomData; } if (this.MyInvocation.BoundParameters.ContainsKey("WindowsConfigurationProvisionVMAgent")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.WindowsConfigurationProvisionVMAgent; } if (this.MyInvocation.BoundParameters.ContainsKey("WindowsConfigurationEnableAutomaticUpdate")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.WindowsConfigurationEnableAutomaticUpdate; } if (this.MyInvocation.BoundParameters.ContainsKey("TimeZone")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone; } if (this.MyInvocation.BoundParameters.ContainsKey("AdditionalUnattendContent")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.AdditionalUnattendContent = this.AdditionalUnattendContent; } if (this.MyInvocation.BoundParameters.ContainsKey("Listener")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // WindowsConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new WindowsConfiguration(); } // WinRM if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM = new WinRMConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM.Listeners = this.Listener; } if (this.MyInvocation.BoundParameters.ContainsKey("LinuxConfigurationDisablePasswordAuthentication")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // LinuxConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.LinuxConfigurationDisablePasswordAuthentication; } if (this.MyInvocation.BoundParameters.ContainsKey("PublicKey")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } // LinuxConfiguration if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new LinuxConfiguration(); } // Ssh if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh = new SshConfiguration(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh.PublicKeys = this.PublicKey; } if (this.MyInvocation.BoundParameters.ContainsKey("Secret")) { // VirtualMachineProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile = new VirtualMachineScaleSetVMProfile(); } // OsProfile if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null) { this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new VirtualMachineScaleSetOSProfile(); } this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.Secrets = this.Secret; } WriteObject(this.VirtualMachineScaleSet); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Generators; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Metadata; namespace Avalonia.Controls { /// <summary> /// Displays a collection of items. /// </summary> public class ItemsControl : TemplatedControl, IItemsPresenterHost { /// <summary> /// The default value for the <see cref="ItemsPanel"/> property. /// </summary> private static readonly FuncTemplate<IPanel> DefaultPanel = new FuncTemplate<IPanel>(() => new StackPanel()); /// <summary> /// Defines the <see cref="Items"/> property. /// </summary> public static readonly DirectProperty<ItemsControl, IEnumerable> ItemsProperty = AvaloniaProperty.RegisterDirect<ItemsControl, IEnumerable>(nameof(Items), o => o.Items, (o, v) => o.Items = v); /// <summary> /// Defines the <see cref="ItemsPanel"/> property. /// </summary> public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty = AvaloniaProperty.Register<ItemsControl, ITemplate<IPanel>>(nameof(ItemsPanel), DefaultPanel); /// <summary> /// Defines the <see cref="ItemTemplate"/> property. /// </summary> public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty = AvaloniaProperty.Register<ItemsControl, IDataTemplate>(nameof(ItemTemplate)); /// <summary> /// Defines the <see cref="MemberSelector"/> property. /// </summary> public static readonly StyledProperty<IMemberSelector> MemberSelectorProperty = AvaloniaProperty.Register<ItemsControl, IMemberSelector>(nameof(MemberSelector)); private IEnumerable _items = new AvaloniaList<object>(); private IItemContainerGenerator _itemContainerGenerator; private IDisposable _itemsCollectionChangedSubscription; /// <summary> /// Initializes static members of the <see cref="ItemsControl"/> class. /// </summary> static ItemsControl() { ItemsProperty.Changed.AddClassHandler<ItemsControl>(x => x.ItemsChanged); } /// <summary> /// Initializes a new instance of the <see cref="ItemsControl"/> class. /// </summary> public ItemsControl() { PseudoClasses.Add(":empty"); SubscribeToItems(_items); ItemTemplateProperty.Changed.AddClassHandler<ItemsControl>(x => x.ItemTemplateChanged); } /// <summary> /// Gets the <see cref="IItemContainerGenerator"/> for the control. /// </summary> public IItemContainerGenerator ItemContainerGenerator { get { if (_itemContainerGenerator == null) { _itemContainerGenerator = CreateItemContainerGenerator(); if (_itemContainerGenerator != null) { _itemContainerGenerator.ItemTemplate = ItemTemplate; _itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e); _itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e); _itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e); } } return _itemContainerGenerator; } } /// <summary> /// Gets or sets the items to display. /// </summary> [Content] public IEnumerable Items { get { return _items; } set { SetAndRaise(ItemsProperty, ref _items, value); } } public int ItemCount { get; private set; } /// <summary> /// Gets or sets the panel used to display the items. /// </summary> public ITemplate<IPanel> ItemsPanel { get { return GetValue(ItemsPanelProperty); } set { SetValue(ItemsPanelProperty, value); } } /// <summary> /// Gets or sets the data template used to display the items in the control. /// </summary> public IDataTemplate ItemTemplate { get { return GetValue(ItemTemplateProperty); } set { SetValue(ItemTemplateProperty, value); } } /// <summary> /// Selects a member from <see cref="Items"/> to use as the list item. /// </summary> public IMemberSelector MemberSelector { get { return GetValue(MemberSelectorProperty); } set { SetValue(MemberSelectorProperty, value); } } /// <summary> /// Gets the items presenter control. /// </summary> public IItemsPresenter Presenter { get; protected set; } /// <inheritdoc/> void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter) { Presenter = presenter; } /// <summary> /// Gets the item at the specified index in a collection. /// </summary> /// <param name="items">The collection.</param> /// <param name="index">The index.</param> /// <returns>The index of the item or -1 if the item was not found.</returns> protected static object ElementAt(IEnumerable items, int index) { if (index != -1 && index < items.Count()) { return items.ElementAt(index) ?? null; } else { return null; } } /// <summary> /// Gets the index of an item in a collection. /// </summary> /// <param name="items">The collection.</param> /// <param name="item">The item.</param> /// <returns>The index of the item or -1 if the item was not found.</returns> protected static int IndexOf(IEnumerable items, object item) { if (items != null && item != null) { var list = items as IList; if (list != null) { return list.IndexOf(item); } else { int index = 0; foreach (var i in items) { if (Equals(i, item)) { return index; } ++index; } } } return -1; } /// <summary> /// Creates the <see cref="ItemContainerGenerator"/> for the control. /// </summary> /// <returns> /// An <see cref="IItemContainerGenerator"/> or null. /// </returns> /// <remarks> /// Certain controls such as <see cref="TabControl"/> don't actually create item /// containers; however they want it to be ItemsControls so that they have an Items /// property etc. In this case, a derived class can override this method to return null /// in order to disable the creation of item containers. /// </remarks> protected virtual IItemContainerGenerator CreateItemContainerGenerator() { return new ItemContainerGenerator(this); } /// <summary> /// Called when new containers are materialized for the <see cref="ItemsControl"/> by its /// <see cref="ItemContainerGenerator"/>. /// </summary> /// <param name="e">The details of the containers.</param> protected virtual void OnContainersMaterialized(ItemContainerEventArgs e) { foreach (var container in e.Containers) { // If the item is its own container, then it will be added to the logical tree when // it was added to the Items collection. if (container.ContainerControl != null && container.ContainerControl != container.Item) { if (ItemContainerGenerator.ContainerType == null) { var containerControl = container.ContainerControl as ContentPresenter; if (containerControl != null) { ((ISetLogicalParent)containerControl).SetParent(this); containerControl.SetValue(TemplatedParentProperty, null); containerControl.UpdateChild(); if (containerControl.Child != null) { LogicalChildren.Add(containerControl.Child); } } } else { LogicalChildren.Add(container.ContainerControl); } } } } /// <summary> /// Called when containers are dematerialized for the <see cref="ItemsControl"/> by its /// <see cref="ItemContainerGenerator"/>. /// </summary> /// <param name="e">The details of the containers.</param> protected virtual void OnContainersDematerialized(ItemContainerEventArgs e) { foreach (var container in e.Containers) { // If the item is its own container, then it will be removed from the logical tree // when it is removed from the Items collection. if (container?.ContainerControl != container?.Item) { if (ItemContainerGenerator.ContainerType == null) { var containerControl = container.ContainerControl as ContentPresenter; if (containerControl != null) { ((ISetLogicalParent)containerControl).SetParent(null); if (containerControl.Child != null) { LogicalChildren.Remove(containerControl.Child); } } } else { LogicalChildren.Remove(container.ContainerControl); } } } } /// <summary> /// Called when containers are recycled for the <see cref="ItemsControl"/> by its /// <see cref="ItemContainerGenerator"/>. /// </summary> /// <param name="e">The details of the containers.</param> protected virtual void OnContainersRecycled(ItemContainerEventArgs e) { var toRemove = new List<ILogical>(); foreach (var container in e.Containers) { // If the item is its own container, then it will be removed from the logical tree // when it is removed from the Items collection. if (container?.ContainerControl != container?.Item) { toRemove.Add(container.ContainerControl); } } LogicalChildren.RemoveAll(toRemove); } /// <summary> /// Caled when the <see cref="Items"/> property changes. /// </summary> /// <param name="e">The event args.</param> protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e) { _itemsCollectionChangedSubscription?.Dispose(); _itemsCollectionChangedSubscription = null; var oldValue = e.OldValue as IEnumerable; var newValue = e.NewValue as IEnumerable; RemoveControlItemsFromLogicalChildren(oldValue); AddControlItemsToLogicalChildren(newValue); SubscribeToItems(newValue); } /// <summary> /// Called when the <see cref="INotifyCollectionChanged.CollectionChanged"/> event is /// raised on <see cref="Items"/>. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> protected virtual void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: AddControlItemsToLogicalChildren(e.NewItems); break; case NotifyCollectionChangedAction.Remove: RemoveControlItemsFromLogicalChildren(e.OldItems); break; } int? count = (Items as IList)?.Count; if (count != null) ItemCount = (int)count; var collection = sender as ICollection; PseudoClasses.Set(":empty", collection == null || collection.Count == 0); } /// <summary> /// Given a collection of items, adds those that are controls to the logical children. /// </summary> /// <param name="items">The items.</param> private void AddControlItemsToLogicalChildren(IEnumerable items) { var toAdd = new List<ILogical>(); if (items != null) { foreach (var i in items) { var control = i as IControl; if (control != null && !LogicalChildren.Contains(control)) { toAdd.Add(control); } } } LogicalChildren.AddRange(toAdd); } /// <summary> /// Given a collection of items, removes those that are controls to from logical children. /// </summary> /// <param name="items">The items.</param> private void RemoveControlItemsFromLogicalChildren(IEnumerable items) { var toRemove = new List<ILogical>(); if (items != null) { foreach (var i in items) { var control = i as IControl; if (control != null) { toRemove.Add(control); } } } LogicalChildren.RemoveAll(toRemove); } /// <summary> /// Subscribes to an <see cref="Items"/> collection. /// </summary> /// <param name="items">The items collection.</param> private void SubscribeToItems(IEnumerable items) { PseudoClasses.Set(":empty", items == null || items.Count() == 0); var incc = items as INotifyCollectionChanged; if (incc != null) { _itemsCollectionChangedSubscription = incc.WeakSubscribe(ItemsCollectionChanged); } } /// <summary> /// Called when the <see cref="ItemTemplate"/> changes. /// </summary> /// <param name="e">The event args.</param> private void ItemTemplateChanged(AvaloniaPropertyChangedEventArgs e) { if (_itemContainerGenerator != null) { _itemContainerGenerator.ItemTemplate = (IDataTemplate)e.NewValue; // TODO: Rebuild the item containers. } } } }
/* ** License Applicability. Except to the extent portions of this file are ** made subject to an alternative license as permitted in the SGI Free ** Software License B, Version 1.1 (the "License"), the contents of this ** file are subject only to the provisions of the License. You may not use ** this file except in compliance with the License. You may obtain a copy ** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 ** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: ** ** http://oss.sgi.com/projects/FreeB ** ** Note that, as provided in the License, the Software is distributed on an ** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS ** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND ** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A ** PARTICULAR PURPOSE, AND NON-INFRINGEMENT. ** ** Original Code. The Original Code is: OpenGL Sample Implementation, ** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, ** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. ** Copyright in any portions created by third parties is as indicated ** elsewhere herein. All Rights Reserved. ** ** Additional Notice Provisions: The application programming interfaces ** established by SGI in conjunction with the Original Code are The ** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released ** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version ** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X ** Window System(R) (Version 1.3), released October 19, 1998. This software ** was created using the OpenGL(R) version 1.2.1 Sample Implementation ** published by SGI, but has not been independently verified as being ** compliant with the OpenGL(R) version 1.2.1 Specification. ** */ /* ** Author: Eric Veach, July 1994. // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 ** */ /* The mesh structure is similar in spirit, notation, and operations * to the "quad-edge" structure (see L. Guibas and J. Stolfi, Primitives * for the manipulation of general subdivisions and the computation of * Voronoi diagrams, ACM Transactions on Graphics, 4(2):74-123, April 1985). * For a simplified description, see the course notes for CS348a, * "Mathematical Foundations of Computer Graphics", available at the * Stanford bookstore (and taught during the fall quarter). * The implementation also borrows a tiny subset of the graph-based approach * use in Mantyla's Geometric Work Bench (see M. Mantyla, An Introduction * to Sold Modeling, Computer Science Press, Rockville, Maryland, 1988). * * The fundamental data structure is the "half-edge". Two half-edges * go together to make an edge, but they point in opposite directions. * Each half-edge has a pointer to its mate (the "symmetric" half-edge Sym), * its origin vertex (Org), the face on its left side (Lface), and the * adjacent half-edges in the CCW direction around the origin vertex * (Onext) and around the left face (Lnext). There is also a "next" * pointer for the global edge list (see below). * * The notation used for mesh navigation: * Sym = the mate of a half-edge (same edge, but opposite direction) * Onext = edge CCW around origin vertex (keep same origin) * Dnext = edge CCW around destination vertex (keep same dest) * Lnext = edge CCW around left face (dest becomes new origin) * Rnext = edge CCW around right face (origin becomes new dest) * * "prev" means to substitute CW for CCW in the definitions above. * * The mesh keeps global lists of all vertices, faces, and edges, * stored as doubly-linked circular lists with a dummy header node. * The mesh stores pointers to these dummy headers (vHead, fHead, eHead). * * The circular edge list is special; since half-edges always occur * in pairs (e and e.Sym), each half-edge stores a pointer in only * one direction. Starting at eHead and following the e.next pointers * will visit each *edge* once (ie. e or e.Sym, but not both). * e.Sym stores a pointer in the opposite direction, thus it is * always true that e.Sym.next.Sym.next == e. * * Each vertex has a pointer to next and previous vertices in the * circular list, and a pointer to a half-edge with this vertex as * the origin (null if this is the dummy header). There is also a * field "data" for client data. * * Each face has a pointer to the next and previous faces in the * circular list, and a pointer to a half-edge with this face as * the left face (null if this is the dummy header). There is also * a field "data" for client data. * * Note that what we call a "face" is really a loop; faces may consist * of more than one loop (ie. not simply connected), but there is no * record of this in the data structure. The mesh may consist of * several disconnected regions, so it may not be possible to visit * the entire mesh by starting at a half-edge and traversing the edge * structure. * * The mesh does NOT support isolated vertices; a vertex is deleted along * with its last edge. Similarly when two faces are merged, one of the * faces is deleted. For mesh operations, * all face (loop) and vertex pointers must not be null. However, once * mesh manipulation is finished, ZapFace can be used to delete * faces of the mesh, one at a time. All external faces can be "zapped" * before the mesh is returned to the client; then a null face indicates * a region which is not part of the output polygon. */ namespace Manssiere.Core.Graphics.Tesselation.Tesselator { using System; // the mesh class /* The mesh operations below have three motivations: completeness, * convenience, and efficiency. The basic mesh operations are MakeEdge, * Splice, and Delete. All the other edge operations can be implemented * in terms of these. The other operations are provided for convenience * and/or efficiency. * * When a face is split or a vertex is added, they are inserted into the * global list *before* the existing vertex or face (ie. e.Org or e.Lface). * This makes it easier to process all vertices or faces in the global lists * without worrying about processing the same data twice. As a convenience, * when a face is split, the "inside" flag is copied from the old face. * Other internal data (v.data, v.activeRegion, f.data, f.marked, * f.trail, e.winding) is set to zero. * * ********************** Basic Edge Operations ************************** * * MakeEdge() creates one edge, two vertices, and a loop. * The loop (face) consists of the two new half-edges. * * Splice( eOrg, eDst ) is the basic operation for changing the * mesh connectivity and topology. It changes the mesh so that * eOrg.Onext <- OLD( eDst.Onext ) * eDst.Onext <- OLD( eOrg.Onext ) * where OLD(...) means the value before the meshSplice operation. * * This can have two effects on the vertex structure: * - if eOrg.Org != eDst.Org, the two vertices are merged together * - if eOrg.Org == eDst.Org, the origin is split into two vertices * In both cases, eDst.Org is changed and eOrg.Org is untouched. * * Similarly (and independently) for the face structure, * - if eOrg.Lface == eDst.Lface, one loop is split into two * - if eOrg.Lface != eDst.Lface, two distinct loops are joined into one * In both cases, eDst.Lface is changed and eOrg.Lface is unaffected. * * __gl_meshDelete( eDel ) removes the edge eDel. There are several cases: * if (eDel.Lface != eDel.Rface), we join two loops into one; the loop * eDel.Lface is deleted. Otherwise, we are splitting one loop into two; * the newly created loop will contain eDel.Dst. If the deletion of eDel * would create isolated vertices, those are deleted as well. * * ********************** Other Edge Operations ************************** * * __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that * eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex. * eOrg and eNew will have the same left face. * * __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew, * such that eNew == eOrg.Lnext. The new vertex is eOrg.Dst == eNew.Org. * eOrg and eNew will have the same left face. * * __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Dst * to eDst.Org, and returns the corresponding half-edge eNew. * If eOrg.Lface == eDst.Lface, this splits one loop into two, * and the newly created loop is eNew.Lface. Otherwise, two disjoint * loops are merged into one, and the loop eDst.Lface is destroyed. * * ************************ Other Operations ***************************** * * __gl_meshNewMesh() creates a new mesh with no edges, no vertices, * and no loops (what we usually call a "face"). * * __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in * both meshes, and returns the new mesh (the old meshes are destroyed). * * __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh. * * __gl_meshZapFace( fZap ) destroys a face and removes it from the * global face list. All edges of fZap will have a null pointer as their * left face. Any edges which also have a null pointer as their right face * are deleted entirely (along with any isolated vertices this produces). * An entire mesh can be deleted by zapping its faces, one at a time, * in any order. Zapped faces cannot be used in further mesh operations! * * __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency. */ public class Mesh { private static int faceIndex; private readonly HalfEdge otherHalfOfThisEdgeHead = new HalfEdge(); /* and its symmetric counterpart */ public Face faceHead = new Face(); /* dummy header for face list */ public HalfEdge halfEdgeHead = new HalfEdge(); /* dummy header for edge list */ public ContourVertex vertexHead = new ContourVertex(); /* dummy header for vertex list */ /* Creates a new mesh with no edges, no vertices, * and no loops (what we usually call a "face"). */ public Mesh() { HalfEdge otherHalfOfThisEdge = otherHalfOfThisEdgeHead; vertexHead.nextVertex = vertexHead.prevVertex = vertexHead; vertexHead.edgeThisIsOriginOf = null; vertexHead.clientIndex = 0; faceHead.nextFace = faceHead.prevFace = faceHead; faceHead.halfEdgeThisIsLeftFaceOf = null; faceHead.trail = null; faceHead.marked = false; faceHead.isInterior = false; halfEdgeHead.nextHalfEdge = halfEdgeHead; halfEdgeHead.otherHalfOfThisEdge = otherHalfOfThisEdge; halfEdgeHead.nextEdgeCCWAroundOrigin = null; halfEdgeHead.nextEdgeCCWAroundLeftFace = null; halfEdgeHead.originVertex = null; halfEdgeHead.leftFace = null; halfEdgeHead.winding = 0; halfEdgeHead.regionThisIsUpperEdgeOf = null; otherHalfOfThisEdge.nextHalfEdge = otherHalfOfThisEdge; otherHalfOfThisEdge.otherHalfOfThisEdge = halfEdgeHead; otherHalfOfThisEdge.nextEdgeCCWAroundOrigin = null; otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace = null; otherHalfOfThisEdge.originVertex = null; otherHalfOfThisEdge.leftFace = null; otherHalfOfThisEdge.winding = 0; otherHalfOfThisEdge.regionThisIsUpperEdgeOf = null; } /* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left * face of all edges in the face loop to which eOrig belongs. "fNext" gives * a place to insert the new face in the global face list. We insert * the new face *before* fNext so that algorithms which walk the face * list will not see the newly created faces. */ private static void MakeFace(Face newFace, HalfEdge eOrig, Face fNext) { HalfEdge e; Face fPrev; Face fNew = newFace; fNew.indexDebug = faceIndex++; // insert in circular doubly-linked list before fNext fPrev = fNext.prevFace; fNew.prevFace = fPrev; fPrev.nextFace = fNew; fNew.nextFace = fNext; fNext.prevFace = fNew; fNew.halfEdgeThisIsLeftFaceOf = eOrig; fNew.trail = null; fNew.marked = false; // The new face is marked "inside" if the old one was. This is a // convenience for the common case where a face has been split in two. fNew.isInterior = fNext.isInterior; // fix other edges on this face loop e = eOrig; do { e.leftFace = fNew; e = e.nextEdgeCCWAroundLeftFace; } while (e != eOrig); } // __gl_meshMakeEdge creates one edge, two vertices, and a loop (face). // The loop consists of the two new half-edges. public HalfEdge MakeEdge() { var newVertex1 = new ContourVertex(); var newVertex2 = new ContourVertex(); var newFace = new Face(); HalfEdge e; e = MakeEdge(halfEdgeHead); MakeVertex(newVertex1, e, vertexHead); MakeVertex(newVertex2, e.otherHalfOfThisEdge, vertexHead); MakeFace(newFace, e, faceHead); return e; } /* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the * origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives * a place to insert the new vertex in the global vertex list. We insert * the new vertex *before* vNext so that algorithms which walk the vertex * list will not see the newly created vertices. */ private static void MakeVertex(ContourVertex newVertex, HalfEdge eOrig, ContourVertex vNext) { HalfEdge e; ContourVertex vPrev; ContourVertex vNew = newVertex; /* insert in circular doubly-linked list before vNext */ vPrev = vNext.prevVertex; vNew.prevVertex = vPrev; vPrev.nextVertex = vNew; vNew.nextVertex = vNext; vNext.prevVertex = vNew; vNew.edgeThisIsOriginOf = eOrig; vNew.clientIndex = 0; /* leave coords, s, t undefined */ /* fix other edges on this vertex loop */ e = eOrig; do { e.originVertex = vNew; e = e.nextEdgeCCWAroundOrigin; } while (e != eOrig); } /* KillVertex( vDel ) destroys a vertex and removes it from the global * vertex list. It updates the vertex loop to point to a given new vertex. */ private static void KillVertex(ContourVertex vDel, ContourVertex newOrg) { HalfEdge e, eStart = vDel.edgeThisIsOriginOf; ContourVertex vPrev, vNext; /* change the origin of all affected edges */ e = eStart; do { e.originVertex = newOrg; e = e.nextEdgeCCWAroundOrigin; } while (e != eStart); /* delete from circular doubly-linked list */ vPrev = vDel.prevVertex; vNext = vDel.nextVertex; vNext.prevVertex = vPrev; vPrev.nextVertex = vNext; } /* KillFace( fDel ) destroys a face and removes it from the global face * list. It updates the face loop to point to a given new face. */ private static void KillFace(Face fDel, Face newLface) { HalfEdge e, eStart = fDel.halfEdgeThisIsLeftFaceOf; Face fPrev, fNext; /* change the left face of all affected edges */ e = eStart; do { e.leftFace = newLface; e = e.nextEdgeCCWAroundLeftFace; } while (e != eStart); /* delete from circular doubly-linked list */ fPrev = fDel.prevFace; fNext = fDel.nextFace; fNext.prevFace = fPrev; fPrev.nextFace = fNext; } /* Splice( a, b ) is best described by the Guibas/Stolfi paper or the * CS348a notes (see mesh.h). Basically it modifies the mesh so that * a.Onext and b.Onext are exchanged. This can have various effects * depending on whether a and b belong to different face or vertex rings. * For more explanation see __gl_meshSplice() below. */ private static void Splice(HalfEdge a, HalfEdge b) { HalfEdge aOnext = a.nextEdgeCCWAroundOrigin; HalfEdge bOnext = b.nextEdgeCCWAroundOrigin; aOnext.otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace = b; bOnext.otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace = a; a.nextEdgeCCWAroundOrigin = bOnext; b.nextEdgeCCWAroundOrigin = aOnext; } /* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the * mesh connectivity and topology. It changes the mesh so that * eOrg.Onext <- OLD( eDst.Onext ) * eDst.Onext <- OLD( eOrg.Onext ) * where OLD(...) means the value before the meshSplice operation. * * This can have two effects on the vertex structure: * - if eOrg.Org != eDst.Org, the two vertices are merged together * - if eOrg.Org == eDst.Org, the origin is split into two vertices * In both cases, eDst.Org is changed and eOrg.Org is untouched. * * Similarly (and independently) for the face structure, * - if eOrg.Lface == eDst.Lface, one loop is split into two * - if eOrg.Lface != eDst.Lface, two distinct loops are joined into one * In both cases, eDst.Lface is changed and eOrg.Lface is unaffected. * * Some special cases: * If eDst == eOrg, the operation has no effect. * If eDst == eOrg.Lnext, the new face will have a single edge. * If eDst == eOrg.Lprev, the old face will have a single edge. * If eDst == eOrg.Onext, the new vertex will have a single edge. * If eDst == eOrg.Oprev, the old vertex will have a single edge. */ public static void meshSplice(HalfEdge eOrg, HalfEdge eDst) { bool joiningLoops = false; bool joiningVertices = false; if (eOrg == eDst) return; if (eDst.originVertex != eOrg.originVertex) { /* We are merging two disjoint vertices -- destroy eDst.Org */ joiningVertices = true; KillVertex(eDst.originVertex, eOrg.originVertex); } if (eDst.leftFace != eOrg.leftFace) { /* We are connecting two disjoint loops -- destroy eDst.Lface */ joiningLoops = true; KillFace(eDst.leftFace, eOrg.leftFace); } /* Change the edge structure */ Splice(eDst, eOrg); if (!joiningVertices) { var newVertex = new ContourVertex(); /* We split one vertex into two -- the new vertex is eDst.Org. * Make sure the old vertex points to a valid half-edge. */ MakeVertex(newVertex, eDst, eOrg.originVertex); eOrg.originVertex.edgeThisIsOriginOf = eOrg; } if (!joiningLoops) { var newFace = new Face(); /* We split one loop into two -- the new loop is eDst.Lface. * Make sure the old face points to a valid half-edge. */ MakeFace(newFace, eDst, eOrg.leftFace); eOrg.leftFace.halfEdgeThisIsLeftFaceOf = eOrg; } } /* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel.Sym), * and removes from the global edge list. */ private static void KillEdge(HalfEdge eDel) { HalfEdge ePrev, eNext; /* Half-edges are allocated in pairs, see EdgePair above */ if (eDel.otherHalfOfThisEdge.isFirstHalfEdge) { eDel = eDel.otherHalfOfThisEdge; } /* delete from circular doubly-linked list */ eNext = eDel.nextHalfEdge; ePrev = eDel.otherHalfOfThisEdge.nextHalfEdge; eNext.otherHalfOfThisEdge.nextHalfEdge = ePrev; ePrev.otherHalfOfThisEdge.nextHalfEdge = eNext; } /* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases: * if (eDel.Lface != eDel.Rface), we join two loops into one; the loop * eDel.Lface is deleted. Otherwise, we are splitting one loop into two; * the newly created loop will contain eDel.Dst. If the deletion of eDel * would create isolated vertices, those are deleted as well. * * This function could be implemented as two calls to __gl_meshSplice * plus a few calls to free, but this would allocate and delete * unnecessary vertices and faces. */ public static void DeleteHalfEdge(HalfEdge edgeToDelete) { HalfEdge otherHalfOfEdgeToDelete = edgeToDelete.otherHalfOfThisEdge; bool joiningLoops = false; // First step: disconnect the origin vertex eDel.Org. We make all // changes to get a consistent mesh in this "intermediate" state. if (edgeToDelete.leftFace != edgeToDelete.rightFace) { // We are joining two loops into one -- remove the left face joiningLoops = true; KillFace(edgeToDelete.leftFace, edgeToDelete.rightFace); } if (edgeToDelete.nextEdgeCCWAroundOrigin == edgeToDelete) { KillVertex(edgeToDelete.originVertex, null); } else { // Make sure that eDel.Org and eDel.Rface point to valid half-edges edgeToDelete.rightFace.halfEdgeThisIsLeftFaceOf = edgeToDelete.Oprev; edgeToDelete.originVertex.edgeThisIsOriginOf = edgeToDelete.nextEdgeCCWAroundOrigin; Splice(edgeToDelete, edgeToDelete.Oprev); if (!joiningLoops) { var newFace = new Face(); // We are splitting one loop into two -- create a new loop for eDel. MakeFace(newFace, edgeToDelete, edgeToDelete.leftFace); } } // Claim: the mesh is now in a consistent state, except that eDel.Org // may have been deleted. Now we disconnect eDel.Dst. if (otherHalfOfEdgeToDelete.nextEdgeCCWAroundOrigin == otherHalfOfEdgeToDelete) { KillVertex(otherHalfOfEdgeToDelete.originVertex, null); KillFace(otherHalfOfEdgeToDelete.leftFace, null); } else { // Make sure that eDel.Dst and eDel.Lface point to valid half-edges edgeToDelete.leftFace.halfEdgeThisIsLeftFaceOf = otherHalfOfEdgeToDelete.Oprev; otherHalfOfEdgeToDelete.originVertex.edgeThisIsOriginOf = otherHalfOfEdgeToDelete.nextEdgeCCWAroundOrigin; Splice(otherHalfOfEdgeToDelete, otherHalfOfEdgeToDelete.Oprev); } // Any isolated vertices or faces have already been freed. KillEdge(edgeToDelete); } /* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that * eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex. * eOrg and eNew will have the same left face. */ private static HalfEdge meshAddEdgeVertex(HalfEdge eOrg) { HalfEdge eNewSym; HalfEdge eNew = MakeEdge(eOrg); eNewSym = eNew.otherHalfOfThisEdge; /* Connect the new edge appropriately */ Splice(eNew, eOrg.nextEdgeCCWAroundLeftFace); /* Set the vertex and face information */ eNew.originVertex = eOrg.directionVertex; { var newVertex = new ContourVertex(); MakeVertex(newVertex, eNewSym, eNew.originVertex); } eNew.leftFace = eNewSym.leftFace = eOrg.leftFace; return eNew; } /* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew, * such that eNew == eOrg.Lnext. The new vertex is eOrg.Dst == eNew.Org. * eOrg and eNew will have the same left face. */ public static HalfEdge meshSplitEdge(HalfEdge eOrg) { HalfEdge eNew; HalfEdge tempHalfEdge = meshAddEdgeVertex(eOrg); eNew = tempHalfEdge.otherHalfOfThisEdge; /* Disconnect eOrg from eOrg.Dst and connect it to eNew.Org */ Splice(eOrg.otherHalfOfThisEdge, eOrg.otherHalfOfThisEdge.Oprev); Splice(eOrg.otherHalfOfThisEdge, eNew); /* Set the vertex and face information */ eOrg.directionVertex = eNew.originVertex; eNew.directionVertex.edgeThisIsOriginOf = eNew.otherHalfOfThisEdge; /* may have pointed to eOrg.Sym */ eNew.rightFace = eOrg.rightFace; eNew.winding = eOrg.winding; /* copy old winding information */ eNew.otherHalfOfThisEdge.winding = eOrg.otherHalfOfThisEdge.winding; return eNew; } /* Allocate and free half-edges in pairs for efficiency. * The *only* place that should use this fact is allocation/free. */ /* MakeEdge creates a new pair of half-edges which form their own loop. * No vertex or face structures are allocated, but these must be assigned * before the current edge operation is completed. */ private static HalfEdge MakeEdge(HalfEdge eNext) { HalfEdge ePrev; var pair = new EdgePair(); /* Make sure eNext points to the first edge of the edge pair */ if (eNext.otherHalfOfThisEdge.isFirstHalfEdge) { eNext = eNext.otherHalfOfThisEdge; } /* Insert in circular doubly-linked list before eNext. * Note that the prev pointer is stored in Sym.next. */ ePrev = eNext.otherHalfOfThisEdge.nextHalfEdge; pair.eSym.nextHalfEdge = ePrev; ePrev.otherHalfOfThisEdge.nextHalfEdge = pair.e; pair.e.nextHalfEdge = eNext; eNext.otherHalfOfThisEdge.nextHalfEdge = pair.eSym; pair.e.isFirstHalfEdge = true; pair.e.otherHalfOfThisEdge = pair.eSym; pair.e.nextEdgeCCWAroundOrigin = pair.e; pair.e.nextEdgeCCWAroundLeftFace = pair.eSym; pair.e.originVertex = null; pair.e.leftFace = null; pair.e.winding = 0; pair.e.regionThisIsUpperEdgeOf = null; pair.eSym.isFirstHalfEdge = false; pair.eSym.otherHalfOfThisEdge = pair.e; pair.eSym.nextEdgeCCWAroundOrigin = pair.eSym; pair.eSym.nextEdgeCCWAroundLeftFace = pair.e; pair.eSym.originVertex = null; pair.eSym.leftFace = null; pair.eSym.winding = 0; pair.eSym.regionThisIsUpperEdgeOf = null; return pair.e; } /* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Dst * to eDst.Org, and returns the corresponding half-edge eNew. * If eOrg.Lface == eDst.Lface, this splits one loop into two, * and the newly created loop is eNew.Lface. Otherwise, two disjoint * loops are merged into one, and the loop eDst.Lface is destroyed. * * If (eOrg == eDst), the new face will have only two edges. * If (eOrg.Lnext == eDst), the old face is reduced to a single edge. * If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges. */ public static HalfEdge meshConnect(HalfEdge eOrg, HalfEdge eDst) { HalfEdge eNewSym; bool joiningLoops = false; HalfEdge eNew = MakeEdge(eOrg); eNewSym = eNew.otherHalfOfThisEdge; if (eDst.leftFace != eOrg.leftFace) { /* We are connecting two disjoint loops -- destroy eDst.Lface */ joiningLoops = true; KillFace(eDst.leftFace, eOrg.leftFace); } /* Connect the new edge appropriately */ Splice(eNew, eOrg.nextEdgeCCWAroundLeftFace); Splice(eNewSym, eDst); /* Set the vertex and face information */ eNew.originVertex = eOrg.directionVertex; eNewSym.originVertex = eDst.originVertex; eNew.leftFace = eNewSym.leftFace = eOrg.leftFace; /* Make sure the old face points to a valid half-edge */ eOrg.leftFace.halfEdgeThisIsLeftFaceOf = eNewSym; if (!joiningLoops) { var newFace = new Face(); /* We split one loop into two -- the new loop is eNew.Lface */ MakeFace(newFace, eNew, eOrg.leftFace); } return eNew; } /* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in * both meshes, and returns the new mesh (the old meshes are destroyed). */ private Mesh meshUnion(Mesh mesh1, Mesh mesh2) { Face f1 = mesh1.faceHead; ContourVertex v1 = mesh1.vertexHead; HalfEdge e1 = mesh1.halfEdgeHead; Face f2 = mesh2.faceHead; ContourVertex v2 = mesh2.vertexHead; HalfEdge e2 = mesh2.halfEdgeHead; /* Add the faces, vertices, and edges of mesh2 to those of mesh1 */ if (f2.nextFace != f2) { f1.prevFace.nextFace = f2.nextFace; f2.nextFace.prevFace = f1.prevFace; f2.prevFace.nextFace = f1; f1.prevFace = f2.prevFace; } if (v2.nextVertex != v2) { v1.prevVertex.nextVertex = v2.nextVertex; v2.nextVertex.prevVertex = v1.prevVertex; v2.prevVertex.nextVertex = v1; v1.prevVertex = v2.prevVertex; } if (e2.nextHalfEdge != e2) { e1.otherHalfOfThisEdge.nextHalfEdge.otherHalfOfThisEdge.nextHalfEdge = e2.nextHalfEdge; e2.nextHalfEdge.otherHalfOfThisEdge.nextHalfEdge = e1.otherHalfOfThisEdge.nextHalfEdge; e2.otherHalfOfThisEdge.nextHalfEdge.otherHalfOfThisEdge.nextHalfEdge = e1; e1.otherHalfOfThisEdge.nextHalfEdge = e2.otherHalfOfThisEdge.nextHalfEdge; } mesh2 = null; return mesh1; } /* __gl_meshZapFace( fZap ) destroys a face and removes it from the * global face list. All edges of fZap will have a null pointer as their * left face. Any edges which also have a null pointer as their right face * are deleted entirely (along with any isolated vertices this produces). * An entire mesh can be deleted by zapping its faces, one at a time, * in any order. Zapped faces cannot be used in further mesh operations! */ public static void meshZapFace(Face fZap) { HalfEdge eStart = fZap.halfEdgeThisIsLeftFaceOf; HalfEdge e, eNext, eSym; Face fPrev, fNext; /* walk around face, deleting edges whose right face is also null */ eNext = eStart.nextEdgeCCWAroundLeftFace; do { e = eNext; eNext = e.nextEdgeCCWAroundLeftFace; e.leftFace = null; if (e.rightFace == null) { /* delete the edge -- see __gl_MeshDelete above */ if (e.nextEdgeCCWAroundOrigin == e) { KillVertex(e.originVertex, null); } else { /* Make sure that e.Org points to a valid half-edge */ e.originVertex.edgeThisIsOriginOf = e.nextEdgeCCWAroundOrigin; Splice(e, e.Oprev); } eSym = e.otherHalfOfThisEdge; if (eSym.nextEdgeCCWAroundOrigin == eSym) { KillVertex(eSym.originVertex, null); } else { /* Make sure that eSym.Org points to a valid half-edge */ eSym.originVertex.edgeThisIsOriginOf = eSym.nextEdgeCCWAroundOrigin; Splice(eSym, eSym.Oprev); } KillEdge(e); } } while (e != eStart); /* delete from circular doubly-linked list */ fPrev = fZap.prevFace; fNext = fZap.nextFace; fNext.prevFace = fPrev; fPrev.nextFace = fNext; fZap = null; } /* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency. */ public void CheckMesh() { Face fHead = faceHead; ContourVertex vHead = vertexHead; HalfEdge eHead = halfEdgeHead; Face f, fPrev; ContourVertex v, vPrev; HalfEdge e, ePrev; fPrev = fHead; for (fPrev = fHead; (f = fPrev.nextFace) != fHead; fPrev = f) { if (f.prevFace != fPrev) { throw new Exception(); } e = f.halfEdgeThisIsLeftFaceOf; do { if (e.otherHalfOfThisEdge == e) { throw new Exception(); } if (e.otherHalfOfThisEdge.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.nextEdgeCCWAroundLeftFace.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace != e) { throw new Exception(); } if (e.leftFace != f) { throw new Exception(); } e = e.nextEdgeCCWAroundLeftFace; } while (e != f.halfEdgeThisIsLeftFaceOf); } if (f.prevFace != fPrev || f.halfEdgeThisIsLeftFaceOf != null) { throw new Exception(); } vPrev = vHead; for (vPrev = vHead; (v = vPrev.nextVertex) != vHead; vPrev = v) { if (v.prevVertex != vPrev) { throw new Exception(); } e = v.edgeThisIsOriginOf; do { if (e.otherHalfOfThisEdge == e) { throw new Exception(); } if (e.otherHalfOfThisEdge.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.nextEdgeCCWAroundLeftFace.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace != e) { throw new Exception(); } if (e.originVertex != v) { throw new Exception(); } e = e.nextEdgeCCWAroundOrigin; } while (e != v.edgeThisIsOriginOf); } if (v.prevVertex != vPrev || v.edgeThisIsOriginOf != null || v.clientIndex != 0) { throw new Exception(); } ePrev = eHead; for (ePrev = eHead; (e = ePrev.nextHalfEdge) != eHead; ePrev = e) { if (e.otherHalfOfThisEdge.nextHalfEdge != ePrev.otherHalfOfThisEdge) { throw new Exception(); } if (e.otherHalfOfThisEdge == e) { throw new Exception(); } if (e.otherHalfOfThisEdge.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.originVertex == null) { throw new Exception(); } if (e.directionVertex == null) { throw new Exception(); } if (e.nextEdgeCCWAroundLeftFace.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge != e) { throw new Exception(); } if (e.nextEdgeCCWAroundOrigin.otherHalfOfThisEdge.nextEdgeCCWAroundLeftFace != e) { throw new Exception(); } } if (e.otherHalfOfThisEdge.nextHalfEdge != ePrev.otherHalfOfThisEdge || e.otherHalfOfThisEdge != otherHalfOfThisEdgeHead || e.otherHalfOfThisEdge.otherHalfOfThisEdge != e || e.originVertex != null || e.directionVertex != null || e.leftFace != null || e.rightFace != null) { throw new Exception(); } } /* SetWindingNumber( value, keepOnlyBoundary ) resets the * winding numbers on all edges so that regions marked "inside" the * polygon have a winding number of "value", and regions outside * have a winding number of 0. * * If keepOnlyBoundary is TRUE, it also deletes all edges which do not * separate an interior region from an exterior one. */ public bool SetWindingNumber(int value, bool keepOnlyBoundary) { HalfEdge e, eNext; for (e = halfEdgeHead.nextHalfEdge; e != halfEdgeHead; e = eNext) { eNext = e.nextHalfEdge; if (e.rightFace.isInterior != e.leftFace.isInterior) { /* This is a boundary edge (one side is interior, one is exterior). */ e.winding = (e.leftFace.isInterior) ? value : -value; } else { /* Both regions are interior, or both are exterior. */ if (!keepOnlyBoundary) { e.winding = 0; } else { DeleteHalfEdge(e); } } } return true; } /* DiscardExterior() zaps (ie. sets to NULL) all faces * which are not marked "inside" the polygon. Since further mesh operations * on NULL faces are not allowed, the main purpose is to clean up the * mesh so that exterior loops are not represented in the data structure. */ public void DiscardExterior() { Face f, next; for (f = faceHead.nextFace; f != faceHead; f = next) { /* Since f will be destroyed, save its next pointer. */ next = f.nextFace; if (!f.isInterior) { meshZapFace(f); } } } /* TessellateInterior() tessellates each region of * the mesh which is marked "inside" the polygon. Each such region * must be monotone. */ public bool TessellateInterior() { Face f, next; for (f = faceHead.nextFace; f != faceHead; f = next) { /* Make sure we don''t try to tessellate the new triangles. */ next = f.nextFace; if (f.isInterior) { if (!f.TessellateMonoRegion()) { return false; } } } return true; } #region Nested type: EdgePair private class EdgePair { private static int debugIndex; public readonly HalfEdge e = new HalfEdge(); public readonly HalfEdge eSym = new HalfEdge(); public EdgePair() { e.debugIndex = debugIndex++; eSym.debugIndex = debugIndex++; } } ; #endregion } ; }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/table/v1/bigtable_table_service_messages.proto #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.Bigtable.Admin.Table.V1 { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class BigtableTableServiceMessages { #region Descriptor public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static BigtableTableServiceMessages() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkRnb29nbGUvYmlndGFibGUvYWRtaW4vdGFibGUvdjEvYmlndGFibGVfdGFi", "bGVfc2VydmljZV9tZXNzYWdlcy5wcm90bxIeZ29vZ2xlLmJpZ3RhYmxlLmFk", "bWluLnRhYmxlLnYxGjhnb29nbGUvYmlndGFibGUvYWRtaW4vdGFibGUvdjEv", "YmlndGFibGVfdGFibGVfZGF0YS5wcm90byKGAQoSQ3JlYXRlVGFibGVSZXF1", "ZXN0EgwKBG5hbWUYASABKAkSEAoIdGFibGVfaWQYAiABKAkSNAoFdGFibGUY", "AyABKAsyJS5nb29nbGUuYmlndGFibGUuYWRtaW4udGFibGUudjEuVGFibGUS", "GgoSaW5pdGlhbF9zcGxpdF9rZXlzGAQgAygJIiEKEUxpc3RUYWJsZXNSZXF1", "ZXN0EgwKBG5hbWUYASABKAkiSwoSTGlzdFRhYmxlc1Jlc3BvbnNlEjUKBnRh", "YmxlcxgBIAMoCzIlLmdvb2dsZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MS5U", "YWJsZSIfCg9HZXRUYWJsZVJlcXVlc3QSDAoEbmFtZRgBIAEoCSIiChJEZWxl", "dGVUYWJsZVJlcXVlc3QSDAoEbmFtZRgBIAEoCSIyChJSZW5hbWVUYWJsZVJl", "cXVlc3QSDAoEbmFtZRgBIAEoCRIOCgZuZXdfaWQYAiABKAkiiAEKGUNyZWF0", "ZUNvbHVtbkZhbWlseVJlcXVlc3QSDAoEbmFtZRgBIAEoCRIYChBjb2x1bW5f", "ZmFtaWx5X2lkGAIgASgJEkMKDWNvbHVtbl9mYW1pbHkYAyABKAsyLC5nb29n", "bGUuYmlndGFibGUuYWRtaW4udGFibGUudjEuQ29sdW1uRmFtaWx5IikKGURl", "bGV0ZUNvbHVtbkZhbWlseVJlcXVlc3QSDAoEbmFtZRgBIAEoCUJJCiJjb20u", "Z29vZ2xlLmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYxQiFCaWd0YWJsZVRhYmxl", "U2VydmljZU1lc3NhZ2VzUHJvdG9QAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbr::FileDescriptor[] { global::Google.Bigtable.Admin.Table.V1.BigtableTableData.Descriptor, }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.CreateTableRequest), new[]{ "Name", "TableId", "Table", "InitialSplitKeys" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.ListTablesRequest), new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.ListTablesResponse), new[]{ "Tables" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GetTableRequest), new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.DeleteTableRequest), new[]{ "Name" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.RenameTableRequest), new[]{ "Name", "NewId" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.CreateColumnFamilyRequest), new[]{ "Name", "ColumnFamilyId", "ColumnFamily" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.DeleteColumnFamilyRequest), new[]{ "Name" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class CreateTableRequest : pb::IMessage<CreateTableRequest> { private static readonly pb::MessageParser<CreateTableRequest> _parser = new pb::MessageParser<CreateTableRequest>(() => new CreateTableRequest()); public static pb::MessageParser<CreateTableRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public CreateTableRequest() { OnConstruction(); } partial void OnConstruction(); public CreateTableRequest(CreateTableRequest other) : this() { name_ = other.name_; tableId_ = other.tableId_; Table = other.table_ != null ? other.Table.Clone() : null; initialSplitKeys_ = other.initialSplitKeys_.Clone(); } public CreateTableRequest Clone() { return new CreateTableRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int TableIdFieldNumber = 2; private string tableId_ = ""; public string TableId { get { return tableId_; } set { tableId_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int TableFieldNumber = 3; private global::Google.Bigtable.Admin.Table.V1.Table table_; public global::Google.Bigtable.Admin.Table.V1.Table Table { get { return table_; } set { table_ = value; } } public const int InitialSplitKeysFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_initialSplitKeys_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> initialSplitKeys_ = new pbc::RepeatedField<string>(); public pbc::RepeatedField<string> InitialSplitKeys { get { return initialSplitKeys_; } } public override bool Equals(object other) { return Equals(other as CreateTableRequest); } public bool Equals(CreateTableRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (TableId != other.TableId) return false; if (!object.Equals(Table, other.Table)) return false; if(!initialSplitKeys_.Equals(other.initialSplitKeys_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (TableId.Length != 0) hash ^= TableId.GetHashCode(); if (table_ != null) hash ^= Table.GetHashCode(); hash ^= initialSplitKeys_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (TableId.Length != 0) { output.WriteRawTag(18); output.WriteString(TableId); } if (table_ != null) { output.WriteRawTag(26); output.WriteMessage(Table); } initialSplitKeys_.WriteTo(output, _repeated_initialSplitKeys_codec); } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (TableId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TableId); } if (table_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Table); } size += initialSplitKeys_.CalculateSize(_repeated_initialSplitKeys_codec); return size; } public void MergeFrom(CreateTableRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.TableId.Length != 0) { TableId = other.TableId; } if (other.table_ != null) { if (table_ == null) { table_ = new global::Google.Bigtable.Admin.Table.V1.Table(); } Table.MergeFrom(other.Table); } initialSplitKeys_.Add(other.initialSplitKeys_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { TableId = input.ReadString(); break; } case 26: { if (table_ == null) { table_ = new global::Google.Bigtable.Admin.Table.V1.Table(); } input.ReadMessage(table_); break; } case 34: { initialSplitKeys_.AddEntriesFrom(input, _repeated_initialSplitKeys_codec); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ListTablesRequest : pb::IMessage<ListTablesRequest> { private static readonly pb::MessageParser<ListTablesRequest> _parser = new pb::MessageParser<ListTablesRequest>(() => new ListTablesRequest()); public static pb::MessageParser<ListTablesRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ListTablesRequest() { OnConstruction(); } partial void OnConstruction(); public ListTablesRequest(ListTablesRequest other) : this() { name_ = other.name_; } public ListTablesRequest Clone() { return new ListTablesRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as ListTablesRequest); } public bool Equals(ListTablesRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(ListTablesRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ListTablesResponse : pb::IMessage<ListTablesResponse> { private static readonly pb::MessageParser<ListTablesResponse> _parser = new pb::MessageParser<ListTablesResponse>(() => new ListTablesResponse()); public static pb::MessageParser<ListTablesResponse> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ListTablesResponse() { OnConstruction(); } partial void OnConstruction(); public ListTablesResponse(ListTablesResponse other) : this() { tables_ = other.tables_.Clone(); } public ListTablesResponse Clone() { return new ListTablesResponse(this); } public const int TablesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Bigtable.Admin.Table.V1.Table> _repeated_tables_codec = pb::FieldCodec.ForMessage(10, global::Google.Bigtable.Admin.Table.V1.Table.Parser); private readonly pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.Table> tables_ = new pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.Table>(); public pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.Table> Tables { get { return tables_; } } public override bool Equals(object other) { return Equals(other as ListTablesResponse); } public bool Equals(ListTablesResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!tables_.Equals(other.tables_)) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= tables_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { tables_.WriteTo(output, _repeated_tables_codec); } public int CalculateSize() { int size = 0; size += tables_.CalculateSize(_repeated_tables_codec); return size; } public void MergeFrom(ListTablesResponse other) { if (other == null) { return; } tables_.Add(other.tables_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { tables_.AddEntriesFrom(input, _repeated_tables_codec); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class GetTableRequest : pb::IMessage<GetTableRequest> { private static readonly pb::MessageParser<GetTableRequest> _parser = new pb::MessageParser<GetTableRequest>(() => new GetTableRequest()); public static pb::MessageParser<GetTableRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public GetTableRequest() { OnConstruction(); } partial void OnConstruction(); public GetTableRequest(GetTableRequest other) : this() { name_ = other.name_; } public GetTableRequest Clone() { return new GetTableRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as GetTableRequest); } public bool Equals(GetTableRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(GetTableRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DeleteTableRequest : pb::IMessage<DeleteTableRequest> { private static readonly pb::MessageParser<DeleteTableRequest> _parser = new pb::MessageParser<DeleteTableRequest>(() => new DeleteTableRequest()); public static pb::MessageParser<DeleteTableRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DeleteTableRequest() { OnConstruction(); } partial void OnConstruction(); public DeleteTableRequest(DeleteTableRequest other) : this() { name_ = other.name_; } public DeleteTableRequest Clone() { return new DeleteTableRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as DeleteTableRequest); } public bool Equals(DeleteTableRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(DeleteTableRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class RenameTableRequest : pb::IMessage<RenameTableRequest> { private static readonly pb::MessageParser<RenameTableRequest> _parser = new pb::MessageParser<RenameTableRequest>(() => new RenameTableRequest()); public static pb::MessageParser<RenameTableRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[5]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public RenameTableRequest() { OnConstruction(); } partial void OnConstruction(); public RenameTableRequest(RenameTableRequest other) : this() { name_ = other.name_; newId_ = other.newId_; } public RenameTableRequest Clone() { return new RenameTableRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int NewIdFieldNumber = 2; private string newId_ = ""; public string NewId { get { return newId_; } set { newId_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as RenameTableRequest); } public bool Equals(RenameTableRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (NewId != other.NewId) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (NewId.Length != 0) hash ^= NewId.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (NewId.Length != 0) { output.WriteRawTag(18); output.WriteString(NewId); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (NewId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NewId); } return size; } public void MergeFrom(RenameTableRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.NewId.Length != 0) { NewId = other.NewId; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { NewId = input.ReadString(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class CreateColumnFamilyRequest : pb::IMessage<CreateColumnFamilyRequest> { private static readonly pb::MessageParser<CreateColumnFamilyRequest> _parser = new pb::MessageParser<CreateColumnFamilyRequest>(() => new CreateColumnFamilyRequest()); public static pb::MessageParser<CreateColumnFamilyRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[6]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public CreateColumnFamilyRequest() { OnConstruction(); } partial void OnConstruction(); public CreateColumnFamilyRequest(CreateColumnFamilyRequest other) : this() { name_ = other.name_; columnFamilyId_ = other.columnFamilyId_; ColumnFamily = other.columnFamily_ != null ? other.ColumnFamily.Clone() : null; } public CreateColumnFamilyRequest Clone() { return new CreateColumnFamilyRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int ColumnFamilyIdFieldNumber = 2; private string columnFamilyId_ = ""; public string ColumnFamilyId { get { return columnFamilyId_; } set { columnFamilyId_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int ColumnFamilyFieldNumber = 3; private global::Google.Bigtable.Admin.Table.V1.ColumnFamily columnFamily_; public global::Google.Bigtable.Admin.Table.V1.ColumnFamily ColumnFamily { get { return columnFamily_; } set { columnFamily_ = value; } } public override bool Equals(object other) { return Equals(other as CreateColumnFamilyRequest); } public bool Equals(CreateColumnFamilyRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (ColumnFamilyId != other.ColumnFamilyId) return false; if (!object.Equals(ColumnFamily, other.ColumnFamily)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (ColumnFamilyId.Length != 0) hash ^= ColumnFamilyId.GetHashCode(); if (columnFamily_ != null) hash ^= ColumnFamily.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (ColumnFamilyId.Length != 0) { output.WriteRawTag(18); output.WriteString(ColumnFamilyId); } if (columnFamily_ != null) { output.WriteRawTag(26); output.WriteMessage(ColumnFamily); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (ColumnFamilyId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ColumnFamilyId); } if (columnFamily_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ColumnFamily); } return size; } public void MergeFrom(CreateColumnFamilyRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.ColumnFamilyId.Length != 0) { ColumnFamilyId = other.ColumnFamilyId; } if (other.columnFamily_ != null) { if (columnFamily_ == null) { columnFamily_ = new global::Google.Bigtable.Admin.Table.V1.ColumnFamily(); } ColumnFamily.MergeFrom(other.ColumnFamily); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { ColumnFamilyId = input.ReadString(); break; } case 26: { if (columnFamily_ == null) { columnFamily_ = new global::Google.Bigtable.Admin.Table.V1.ColumnFamily(); } input.ReadMessage(columnFamily_); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DeleteColumnFamilyRequest : pb::IMessage<DeleteColumnFamilyRequest> { private static readonly pb::MessageParser<DeleteColumnFamilyRequest> _parser = new pb::MessageParser<DeleteColumnFamilyRequest>(() => new DeleteColumnFamilyRequest()); public static pb::MessageParser<DeleteColumnFamilyRequest> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableServiceMessages.Descriptor.MessageTypes[7]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DeleteColumnFamilyRequest() { OnConstruction(); } partial void OnConstruction(); public DeleteColumnFamilyRequest(DeleteColumnFamilyRequest other) : this() { name_ = other.name_; } public DeleteColumnFamilyRequest Clone() { return new DeleteColumnFamilyRequest(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public override bool Equals(object other) { return Equals(other as DeleteColumnFamilyRequest); } public bool Equals(DeleteColumnFamilyRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } public void MergeFrom(DeleteColumnFamilyRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace NVelocity.Runtime { using System; using System.Collections; using System.Collections.Generic; using System.IO; using Directive; using Exception; using Log; using Parser; using Parser.Node; /// <summary> VelocimacroFactory.java /// /// manages the set of VMs in a running Velocity engine. /// /// </summary> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VelocimacroFactory.java 718442 2008-11-18 00:01:17Z nbubna $ /// </version> public class VelocimacroFactory { /// <summary> sets permission to have VMs local in scope to their declaring template note that this is /// really taken care of in the VMManager class, but we need it here for gating purposes in addVM /// eventually, I will slide this all into the manager, maybe. /// </summary> private bool TemplateLocalInline { get { return templateLocal; } set { templateLocal = value; } } /// <summary> Get the switch for automatic reloading of /// global library-based VMs /// </summary> /// <summary> set the switch for automatic reloading of /// global library-based VMs /// </summary> private bool Autoload { get { return autoReloadLibrary; } set { autoReloadLibrary = value; } } /// <summary> runtime services for this instance</summary> private IRuntimeServices rsvc; /// <summary> the Log for this instance</summary> private LogDisplayWrapper log; /// <summary> VMManager : deal with namespace management /// and actually keeps all the VM definitions /// </summary> private VelocimacroManager vmManager = null; /// <summary> determines if replacement of global VMs are allowed /// controlled by VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL /// </summary> private bool replaceAllowed = false; /// <summary> controls if new VMs can be added. Set by /// VM_PERM_ALLOW_INLINE Note the assumption that only /// through inline defs can this happen. /// additions through autoloaded VMs is allowed /// </summary> private bool addNewAllowed = true; /// <summary> sets if template-local namespace in used</summary> private bool templateLocal = false; /// <summary> determines if the libraries are auto-loaded /// when they change /// </summary> private bool autoReloadLibrary = false; /// <summary> vector of the library names</summary> private System.Collections.IList macroLibVec = null; /// <summary> map of the library Template objects /// used for reload determination /// </summary> private IDictionary<string, Twonk> libModMap; /// <summary> C'tor for the VelociMacro factory. /// /// </summary> /// <param name="rsvc">Reference to a runtime services object. /// </param> public VelocimacroFactory(IRuntimeServices rsvc) { this.rsvc = rsvc; this.log = new LogDisplayWrapper(rsvc.Log, "Velocimacro : ", rsvc.GetBoolean(RuntimeConstants.VM_MESSAGES_ON, true)); /* * we always access in a synchronized(), so we * can use an unsynchronized hashmap */ libModMap = new Dictionary<string, Twonk>(); vmManager = new VelocimacroManager(rsvc); } /// <summary> Initialize the factory - setup all permissions /// load all global libraries. /// </summary> public void InitVelocimacro() { /* * maybe I'm just paranoid... */ lock (this) { log.Trace("initialization starting."); /* * allow replacements while we Add the libraries, if exist */ SetReplacementPermission(true); /* * Add all library macros to the global namespace */ vmManager.NamespaceUsage = false; /* * now, if there is a global or local libraries specified, use them. * All we have to do is Get the template. The template will be parsed; * VM's are added during the parse phase */ object libfiles = rsvc.GetProperty(RuntimeConstants.VM_LIBRARY); if (libfiles == null) { log.Debug("\"" + RuntimeConstants.VM_LIBRARY + "\" is not set. Trying default library: " + NVelocity.Runtime.RuntimeConstants.VM_LIBRARY_DEFAULT); // try the default library. if (rsvc.GetLoaderNameForResource(RuntimeConstants.VM_LIBRARY_DEFAULT) != null) { libfiles = RuntimeConstants.VM_LIBRARY_DEFAULT; } else { log.Debug("Default library not found."); } } if (libfiles != null) { macroLibVec = new ArrayList(); if (libfiles is ArrayList) { var lbs = (ArrayList)libfiles; foreach (var lb in lbs) { macroLibVec.Add(lb); } } else if (libfiles is string) { macroLibVec.Add(libfiles); } for (int i = 0, is_Renamed = macroLibVec.Count; i < is_Renamed; i++) { string lib = (string)macroLibVec[i]; /* * only if it's a non-empty string do we bother */ if (!String.IsNullOrEmpty(lib)) { /* * let the VMManager know that the following is coming * from libraries - need to know for auto-load */ vmManager.RegisterFromLib = true; log.Debug("adding VMs from VM library : " + lib); try { Template template = rsvc.GetTemplate(lib); /* * save the template. This depends on the assumption * that the Template object won't change - currently * this is how the Resource manager works */ Twonk twonk = new Twonk(); twonk.template = template; twonk.modificationTime = template.LastModified; libModMap[lib] = twonk; } catch (System.Exception e) { string msg = "Velocimacro : Error using VM library : " + lib; log.Error(true, msg, e); } log.Trace("VM library registration complete."); vmManager.RegisterFromLib = false; } } } /* * now, the permissions */ /* * allowinline : anything after this will be an inline macro, I think * there is the question if a #include is an inline, and I think so * * default = true */ SetAddMacroPermission(true); if (!rsvc.GetBoolean(RuntimeConstants.VM_PERM_ALLOW_INLINE, true)) { SetAddMacroPermission(false); log.Debug("allowInline = false : VMs can NOT be defined inline in templates"); } else { log.Debug("allowInline = true : VMs can be defined inline in templates"); } /* * allowInlineToReplaceGlobal : allows an inline VM , if allowed at all, * to replace an existing global VM * * default = false */ SetReplacementPermission(false); if (rsvc.GetBoolean(RuntimeConstants.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, false)) { SetReplacementPermission(true); log.Debug("allowInlineToOverride = true : VMs " + "defined inline may replace previous VM definitions"); } else { log.Debug("allowInlineToOverride = false : VMs " + "defined inline may NOT replace previous VM definitions"); } /* * now turn on namespace handling as far as permissions allow in the * manager, and also set it here for gating purposes */ vmManager.NamespaceUsage = true; /* * template-local inline VM mode : default is off */ TemplateLocalInline = rsvc.GetBoolean(Runtime.RuntimeConstants.VM_PERM_INLINE_LOCAL, false); if (TemplateLocalInline) { log.Debug("allowInlineLocal = true : VMs " + "defined inline will be local to their defining template only."); } else { log.Debug("allowInlineLocal = false : VMs " + "defined inline will be global in scope if allowed."); } vmManager.TemplateLocalInlineVM = TemplateLocalInline; /* * autoload VM libraries */ Autoload = rsvc.GetBoolean(RuntimeConstants.VM_LIBRARY_AUTORELOAD, false); if (Autoload) { log.Debug("autoload on : VM system " + "will automatically reload global library macros"); } else { log.Debug("autoload off : VM system " + "will not automatically reload global library macros"); } log.Trace("Velocimacro : initialization complete."); } } /// <summary> Adds a macro to the factory. /// /// addVelocimacro(String, Node, String[] argArray, String) should be used internally /// instead of this. /// /// </summary> /// <param name="name">Name of the Macro to Add. /// </param> /// <param name="macroBody">String representation of the macro. /// </param> /// <param name="argArray">Macro arguments. First element is the macro name. /// </param> /// <param name="sourceTemplate">Source template from which the macro gets registered. /// /// </param> /// <returns> true if Macro was registered successfully. /// </returns> public bool AddVelocimacro(string name, string macroBody, string[] argArray, string sourceTemplate) { /* * maybe we should throw an exception, maybe just tell * the caller like this... * * I hate this : maybe exceptions are in order here... * They definitely would be if this was only called by directly * by users, but Velocity calls this internally. */ if (name == null || macroBody == null || argArray == null || sourceTemplate == null) { string msg = "VM '" + name + "' addition rejected : "; if (name == null) { msg += "name"; } else if (macroBody == null) { msg += "macroBody"; } else if (argArray == null) { msg += "argArray"; } else { msg += "sourceTemplate"; } msg += " argument was null"; log.Error(msg); throw new System.NullReferenceException(msg); } /* * see if the current ruleset allows this addition */ if (!CanAddVelocimacro(name, sourceTemplate)) { return false; } lock (this) { try { INode macroRootNode = rsvc.Parse(new StringReader(macroBody), sourceTemplate); vmManager.AddVM(name, macroRootNode, argArray, sourceTemplate, replaceAllowed); } catch (ParseException ex) { // to keep things 1.3 compatible call toString() here throw new System.SystemException(ex.ToString()); } } if (log.DebugEnabled) { System.Text.StringBuilder msg = new System.Text.StringBuilder("added "); Macro.MacroToString(msg, argArray); msg.Append(" : source = ").Append(sourceTemplate); log.Debug(msg.ToString()); } return true; } /// <summary> Adds a macro to the factory. /// /// </summary> /// <param name="name">Name of the Macro to Add. /// </param> /// <param name="macroBody">root node of the parsed macro AST /// </param> /// <param name="argArray">Name of the macro arguments. First element is the macro name. /// </param> /// <param name="sourceTemplate">Source template from which the macro gets registered. /// </param> /// <returns> true if Macro was registered successfully. /// </returns> /// <since> 1.6 /// </since> public bool AddVelocimacro(string name, INode macroBody, string[] argArray, string sourceTemplate) { // Called by RuntimeInstance.addVelocimacro /* * maybe we should throw an exception, maybe just tell * the caller like this... * * I hate this : maybe exceptions are in order here... * They definitely would be if this was only called by directly * by users, but Velocity calls this internally. */ if (name == null || macroBody == null || argArray == null || sourceTemplate == null) { string msg = "VM '" + name + "' addition rejected : "; if (name == null) { msg += "name"; } else if (macroBody == null) { msg += "macroBody"; } else if (argArray == null) { msg += "argArray"; } else { msg += "sourceTemplate"; } msg += " argument was null"; log.Error(msg); throw new System.NullReferenceException(msg); } /* * see if the current ruleset allows this addition */ if (!CanAddVelocimacro(name, sourceTemplate)) { return false; } lock (this) { vmManager.AddVM(name, macroBody, argArray, sourceTemplate, replaceAllowed); } return (true); } /// <summary> determines if a given macro/namespace (name, source) combo is allowed /// to be added /// /// </summary> /// <param name="name">Name of VM to Add /// </param> /// <param name="sourceTemplate">Source template that contains the defintion of the VM /// </param> /// <returns> true if it is allowed to be added, false otherwise /// </returns> private bool CanAddVelocimacro(string name, string sourceTemplate) { lock (this) { /* * short circuit and do it if autoloader is on, and the * template is one of the library templates */ if (autoReloadLibrary && (macroLibVec != null)) { if (macroLibVec.Contains(sourceTemplate)) return true; } /* * maybe the rules should be in manager? I dunno. It's to manage * the namespace issues first, are we allowed to Add VMs at all? * This trumps all. */ if (!addNewAllowed) { log.Warn("VM addition rejected : " + name + " : inline VMs not allowed."); return false; } /* * are they local in scope? Then it is ok to Add. */ if (!templateLocal) { /* * otherwise, if we have it already in global namespace, and they can't replace * since local templates are not allowed, the global namespace is implied. * remember, we don't know anything about namespace managment here, so lets * note do anything fancy like trying to give it the global namespace here * * so if we have it, and we aren't allowed to replace, bail */ if (!replaceAllowed && IsVelocimacro(name, sourceTemplate)) { /* * Concurrency fix: the Log entry was changed to Debug scope because it * causes false alarms when several concurrent threads simultaneously (re)parse * some macro */ if (log.DebugEnabled) log.Debug("VM addition rejected : " + name + " : inline not allowed to replace existing VM"); return false; } } return true; } } /// <summary> Tells the world if a given directive string is a Velocimacro</summary> /// <param name="vm">Name of the Macro. /// </param> /// <param name="sourceTemplate">Source template from which the macro should be loaded. /// </param> /// <returns> True if the given name is a macro. /// </returns> public virtual bool IsVelocimacro(string vm, string sourceTemplate) { // synchronization removed return (vmManager.Get(vm, sourceTemplate) != null); } /// <summary> parameters factory : creates a Directive that will /// behave correctly wrt getting the framework to /// dig out the correct # of args /// </summary> /// <param name="vmName">Name of the Macro. /// </param> /// <param name="sourceTemplate">Source template from which the macro should be loaded. /// </param> /// <returns> A directive representing the Macro. /// </returns> public virtual Directive.Directive GetVelocimacro(string vmName, string sourceTemplate) { return (GetVelocimacro(vmName, sourceTemplate, null)); } /// <since> 1.6 /// </since> public virtual Directive.Directive GetVelocimacro(string vmName, string sourceTemplate, string renderingTemplate) { VelocimacroProxy vp = null; vp = vmManager.Get(vmName, sourceTemplate, renderingTemplate); /* * if this exists, and autoload is on, we need to check where this VM came from */ if (vp != null && autoReloadLibrary) { lock (this) { /* * see if this VM came from a library. Need to pass sourceTemplate in the event * namespaces are set, as it could be masked by local */ string lib = vmManager.GetLibraryName(vmName, sourceTemplate); if (lib != null) { try { /* * Get the template from our map */ if (libModMap.ContainsKey(lib)) { Twonk tw = libModMap[lib]; Template template = tw.template; /* * now, Compare the last modified time of the resource with the last * modified time of the template if the file has changed, then reload. * Otherwise, we should be ok. */ long tt = tw.modificationTime; long ft = template.ResourceLoader.GetLastModified(template); if (ft > tt) { log.Debug("auto-reloading VMs from VM library : " + lib); /* * when there are VMs in a library that invoke each other, there are * calls into getVelocimacro() from the Init() process of the VM * directive. To stop the infinite loop we save the current time * reported by the resource loader and then be honest when the * reload is complete */ tw.modificationTime = ft; template = rsvc.GetTemplate(lib); /* * and now we be honest */ tw.template = template; tw.modificationTime = template.LastModified; /* * note that we don't need to Put this twonk * back into the map, as we can just use the * same reference and this block is synchronized */ } } } catch (System.Exception e) { string msg = "Velocimacro : Error using VM library : " + lib; //Log.Error(true, msg, e); throw new VelocityException(msg, e); } vp = vmManager.Get(vmName, sourceTemplate, renderingTemplate); } } } return vp; } /// <summary> tells the vmManager to dump the specified namespace /// /// </summary> /// <param name="namespace">Namespace to dump. /// </param> /// <returns> True if namespace has been dumped successfully. /// </returns> public virtual bool DumpVMNamespace(string namespace_Renamed) { return vmManager.DumpNamespace(namespace_Renamed); } /// <summary> sets the permission to Add new macros</summary> private bool SetAddMacroPermission(bool addNewAllowed) { bool b = this.addNewAllowed; this.addNewAllowed = addNewAllowed; return b; } /// <summary> sets the permission for allowing addMacro() calls to replace existing VM's</summary> private bool SetReplacementPermission(bool arg) { bool b = replaceAllowed; replaceAllowed = arg; vmManager.InlineReplacesGlobal = arg; return b; } /// <summary> small container class to hold the tuple /// of a template and modification time. /// We keep the modification time so we can /// 'override' it on a reload to prevent /// recursive reload due to inter-calling /// VMs in a library /// </summary> private class Twonk { /// <summary>Template kept in this container. </summary> public Template template; /// <summary>modification time of the template. </summary> public long modificationTime; } } }
// 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.Globalization; using System.IO; using System.Text; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return EnumerableHelpers.ToArray(EnumerateProcessIds()); } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { ThrowIfRemoteMachine(machineName); int[] procIds = GetProcessIds(machineName); // Iterate through all process IDs to load information about each process var reusableReader = new ReusableTextReader(); var processes = new List<ProcessInfo>(procIds.Length); foreach (int pid in procIds) { ProcessInfo pi = CreateProcessInfo(pid, reusableReader); if (pi != null) { processes.Add(pi); } } return processes.ToArray(); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> internal static ProcessModuleCollection GetModules(int processId) { var modules = new ProcessModuleCollection(0); // Process from the parsed maps file each entry representing a module foreach (Interop.procfs.ParsedMapsModule entry in Interop.procfs.ParseMapsModules(processId)) { int sizeOfImage = (int)(entry.AddressRange.Value - entry.AddressRange.Key); // A single module may be split across multiple map entries; consolidate based on // the name and address ranges of sequential entries. if (modules.Count > 0) { ProcessModule module = modules[modules.Count - 1]; if (module.FileName == entry.FileName && ((long)module.BaseAddress + module.ModuleMemorySize == entry.AddressRange.Key)) { // Merge this entry with the previous one module.ModuleMemorySize += sizeOfImage; continue; } } // It's not a continuation of a previous entry but a new one: add it. unsafe { modules.Add(new ProcessModule() { FileName = entry.FileName, ModuleName = Path.GetFileName(entry.FileName), BaseAddress = new IntPtr(unchecked((void*)entry.AddressRange.Key)), ModuleMemorySize = sizeOfImage, EntryPointAddress = IntPtr.Zero // unknown }); } } // Return the set of modules found return modules; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// Creates a ProcessInfo from the specified process ID. /// </summary> internal static ProcessInfo CreateProcessInfo(int pid, ReusableTextReader reusableReader = null) { if (reusableReader == null) { reusableReader = new ReusableTextReader(); } Interop.procfs.ParsedStat stat; return Interop.procfs.TryReadStatFile(pid, out stat, reusableReader) ? CreateProcessInfo(stat, reusableReader) : null; } /// <summary> /// Creates a ProcessInfo from the data parsed from a /proc/pid/stat file and the associated tasks directory. /// </summary> internal static ProcessInfo CreateProcessInfo(Interop.procfs.ParsedStat procFsStat, ReusableTextReader reusableReader) { int pid = procFsStat.pid; var pi = new ProcessInfo() { ProcessId = pid, ProcessName = procFsStat.comm, BasePriority = (int)procFsStat.nice, VirtualBytes = (long)procFsStat.vsize, WorkingSet = procFsStat.rss * Environment.SystemPageSize, SessionId = procFsStat.session, // We don't currently fill in the other values. // A few of these could probably be filled in from getrusage, // but only for the current process or its children, not for // arbitrary other processes. }; // Then read through /proc/pid/task/ to find each thread in the process... string tasksDir = Interop.procfs.GetTaskDirectoryPathForProcess(pid); try { foreach (string taskDir in Directory.EnumerateDirectories(tasksDir)) { // ...and read its associated /proc/pid/task/tid/stat file to create a ThreadInfo string dirName = Path.GetFileName(taskDir); int tid; Interop.procfs.ParsedStat stat; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out tid) && Interop.procfs.TryReadStatFile(pid, tid, out stat, reusableReader)) { unsafe { pi._threadInfoList.Add(new ThreadInfo() { _processId = pid, _threadId = (ulong)tid, _basePriority = pi.BasePriority, _currentPriority = (int)stat.nice, _startAddress = IntPtr.Zero, _threadState = ProcFsStateToThreadState(stat.state), _threadWaitReason = ThreadWaitReason.Unknown }); } } } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated // directories and files in procfs, the process could be gone. } // Finally return what we've built up return pi; } // ---------------------------------- // ---- Unix PAL layer ends here ---- // ---------------------------------- /// <summary>Enumerates the IDs of all processes on the current machine.</summary> internal static IEnumerable<int> EnumerateProcessIds() { // Parse /proc for any directory that's named with a number. Each such // directory represents a process. foreach (string procDir in Directory.EnumerateDirectories(Interop.procfs.RootPath)) { string dirName = Path.GetFileName(procDir); int pid; if (int.TryParse(dirName, NumberStyles.Integer, CultureInfo.InvariantCulture, out pid)) { Debug.Assert(pid >= 0); yield return pid; } } } /// <summary>Gets a ThreadState to represent the value returned from the status field of /proc/pid/stat.</summary> /// <param name="c">The status field value.</param> /// <returns></returns> private static ThreadState ProcFsStateToThreadState(char c) { switch (c) { case 'R': return ThreadState.Running; case 'S': case 'D': case 'T': return ThreadState.Wait; case 'Z': return ThreadState.Terminated; case 'W': return ThreadState.Transition; default: Debug.Fail("Unexpected status character"); return ThreadState.Unknown; } } } }
namespace InControl { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using UnityEngine; using DeviceHandle = System.UInt32; public class NativeInputDeviceManager : InputDeviceManager { public static Func<NativeDeviceInfo, ReadOnlyCollection<NativeInputDevice>, NativeInputDevice> CustomFindDetachedDevice; List<NativeInputDevice> attachedDevices; List<NativeInputDevice> detachedDevices; List<NativeInputDeviceProfile> systemDeviceProfiles; List<NativeInputDeviceProfile> customDeviceProfiles; public NativeInputDeviceManager() { attachedDevices = new List<NativeInputDevice>(); detachedDevices = new List<NativeInputDevice>(); systemDeviceProfiles = new List<NativeInputDeviceProfile>( NativeInputDeviceProfileList.Profiles.Length ); customDeviceProfiles = new List<NativeInputDeviceProfile>(); AddSystemDeviceProfiles(); var options = new NativeInputOptions(); options.enableXInput = InputManager.NativeInputEnableXInput; options.preventSleep = InputManager.NativeInputPreventSleep; if (InputManager.NativeInputUpdateRate > 0) { options.updateRate = (UInt16) InputManager.NativeInputUpdateRate; } else { options.updateRate = (UInt16) Mathf.FloorToInt( 1.0f / Time.fixedDeltaTime ); } Native.Init( options ); } public override void Destroy() { Native.Stop(); } public override void Update( ulong updateTick, float deltaTime ) { DeviceHandle deviceHandle; while (Native.AttachedDeviceQueue.Dequeue( out deviceHandle )) { var stringBuilder = new StringBuilder( 256 ); stringBuilder.Append( "Attached native device with handle " + deviceHandle + ":\n" ); NativeDeviceInfo deviceInfo; if (Native.GetDeviceInfo( deviceHandle, out deviceInfo )) { stringBuilder.AppendFormat( "Name: {0}\n", deviceInfo.name ); stringBuilder.AppendFormat( "Driver Type: {0}\n", deviceInfo.driverType ); stringBuilder.AppendFormat( "Location ID: {0}\n", deviceInfo.location ); stringBuilder.AppendFormat( "Serial Number: {0}\n", deviceInfo.serialNumber ); stringBuilder.AppendFormat( "Vendor ID: 0x{0:x}\n", deviceInfo.vendorID ); stringBuilder.AppendFormat( "Product ID: 0x{0:x}\n", deviceInfo.productID ); stringBuilder.AppendFormat( "Version Number: 0x{0:x}\n", deviceInfo.versionNumber ); stringBuilder.AppendFormat( "Buttons: {0}\n", deviceInfo.numButtons ); stringBuilder.AppendFormat( "Analogs: {0}\n", deviceInfo.numAnalogs ); DetectDevice( deviceHandle, deviceInfo ); } Debug.Log( stringBuilder.ToString() ); } while (Native.DetachedDeviceQueue.Dequeue( out deviceHandle )) { Debug.Log( "Detached native device with handle " + deviceHandle + ":" ); var device = FindAttachedDevice( deviceHandle ); if (device != null) { DetachDevice( device ); } else { Debug.Log( "Couldn't find device to detach with handle: " + deviceHandle ); } } } void DetectDevice( DeviceHandle deviceHandle, NativeDeviceInfo deviceInfo ) { // Try to find a matching profile for this device. NativeInputDeviceProfile deviceProfile = null; deviceProfile = deviceProfile ?? customDeviceProfiles.Find( profile => profile.Matches( deviceInfo ) ); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find( profile => profile.Matches( deviceInfo ) ); deviceProfile = deviceProfile ?? customDeviceProfiles.Find( profile => profile.LastResortMatches( deviceInfo ) ); deviceProfile = deviceProfile ?? systemDeviceProfiles.Find( profile => profile.LastResortMatches( deviceInfo ) ); // Find a matching previously attached device or create a new one. var device = FindDetachedDevice( deviceInfo ) ?? new NativeInputDevice(); device.Initialize( deviceHandle, deviceInfo, deviceProfile ); AttachDevice( device ); } void AttachDevice( NativeInputDevice device ) { detachedDevices.Remove( device ); attachedDevices.Add( device ); InputManager.AttachDevice( device ); } void DetachDevice( NativeInputDevice device ) { attachedDevices.Remove( device ); detachedDevices.Add( device ); InputManager.DetachDevice( device ); } NativeInputDevice FindAttachedDevice( DeviceHandle deviceHandle ) { var attachedDevicesCount = attachedDevices.Count; for (var i = 0; i < attachedDevicesCount; i++) { var device = attachedDevices[i]; if (device.Handle == deviceHandle) { return device; } } return null; } NativeInputDevice FindDetachedDevice( NativeDeviceInfo deviceInfo ) { var devices = new ReadOnlyCollection<NativeInputDevice>( detachedDevices ); if (CustomFindDetachedDevice != null) { return CustomFindDetachedDevice( deviceInfo, devices ); } return SystemFindDetachedDevice( deviceInfo, devices ); } static NativeInputDevice SystemFindDetachedDevice( NativeDeviceInfo deviceInfo, ReadOnlyCollection<NativeInputDevice> detachedDevices ) { var detachedDevicesCount = detachedDevices.Count; for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameSerialNumber( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameLocation( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameVendorID( deviceInfo ) && device.Info.HasSameProductID( deviceInfo ) && device.Info.HasSameVersionNumber( deviceInfo )) { return device; } } for (var i = 0; i < detachedDevicesCount; i++) { var device = detachedDevices[i]; if (device.Info.HasSameLocation( deviceInfo )) { return device; } } return null; } void AddSystemDeviceProfile( NativeInputDeviceProfile deviceProfile ) { if (deviceProfile.IsSupportedOnThisPlatform) { systemDeviceProfiles.Add( deviceProfile ); } } void AddSystemDeviceProfiles() { foreach (var typeName in NativeInputDeviceProfileList.Profiles) { var deviceProfile = (NativeInputDeviceProfile) Activator.CreateInstance( Type.GetType( typeName ) ); AddSystemDeviceProfile( deviceProfile ); } } public static bool CheckPlatformSupport( ICollection<string> errors ) { if (Application.platform != RuntimePlatform.OSXPlayer && Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor) { return false; } #if UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 if (!Application.HasProLicense()) { if (errors != null) { errors.Add( "Unity 4 Professional or Unity 5 is required for native input support." ); } return false; } #endif try { NativeVersionInfo versionInfo; Native.GetVersionInfo( out versionInfo ); Debug.Log( "InControl Native (version " + versionInfo.major + "." + versionInfo.minor + "." + versionInfo.patch + " build " + versionInfo.build + ")" ); } catch (DllNotFoundException e) { if (errors != null) { errors.Add( e.Message + Utility.PluginFileExtension() + " could not be found or is missing a dependency." ); } return false; } return true; } internal static bool Enable() { var errors = new List<string>(); if (CheckPlatformSupport( errors )) { InputManager.AddDeviceManager<NativeInputDeviceManager>(); return true; } foreach (var error in errors) { Debug.LogError( "Error enabling NativeInputDeviceManager: " + error ); } return false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Xunit; namespace System.Reflection.Emit.Tests { public class MethodBuilderDefineParameter1b { private const int MinStringLength = 1; private const int MaxStringLength = 256; private const string TestDynamicAssemblyName = "TestDynamicAssembly"; private const string TestDynamicModuleName = "TestDynamicModule"; private const string TestDynamicTypeName = "TestDynamicType"; private const string PosTestDynamicMethodName = "PosDynamicMethod"; private const string NegTestDynamicMethodName = "NegDynamicMethod"; private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run; private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private TypeBuilder GetTestTypeBuilder() { AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly( assemblyName, TestAssemblyBuilderAccess); ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName); return moduleBuilder.DefineType(TestDynamicTypeName, TypeAttributes.Abstract); } [Fact] public void TestWithHasDefault() { string strParamName = null; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] paramTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); ParameterBuilder paramBuilder = builder.DefineParameter( 1, ParameterAttributes.HasDefault, strParamName); Assert.NotNull(paramBuilder); VerifyParameterBuilder(paramBuilder, strParamName, ParameterAttributes.HasDefault, 1); } [Fact] public void TestForEveryParameterAtributeFlag() { string strParamName = null; ParameterAttributes[] attributes = new ParameterAttributes[] { ParameterAttributes.HasDefault, ParameterAttributes.HasFieldMarshal, ParameterAttributes.In, ParameterAttributes.None, ParameterAttributes.Optional, ParameterAttributes.Out, ParameterAttributes.Retval }; Type[] paramTypes = new Type[attributes.Length]; for (int i = 0; i < paramTypes.Length; ++i) { paramTypes[i] = typeof(int); } TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); for (int i = 1; i < attributes.Length; ++i) { strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); ParameterBuilder paramBuilder = builder.DefineParameter(i, attributes[i], strParamName); Assert.NotNull(paramBuilder); VerifyParameterBuilder(paramBuilder, strParamName, attributes[i], i); } } [Fact] public void TestForCombinationOfParamterAttributeFlags() { string strParamName = null; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] paramTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); ParameterAttributes attribute = ParameterAttributes.HasDefault | ParameterAttributes.HasFieldMarshal | ParameterAttributes.In | ParameterAttributes.None | ParameterAttributes.Optional | ParameterAttributes.Out | ParameterAttributes.Retval; ParameterBuilder paramBuilder = builder.DefineParameter( 1, attribute, strParamName); Assert.NotNull(paramBuilder); VerifyParameterBuilder(paramBuilder, strParamName, attribute, 1); } [Fact] public void TestForNegativeFlag() { string strParamName = null; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] paramTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); ParameterBuilder paramBuilder = builder.DefineParameter( 1, (ParameterAttributes)(-1), strParamName); } [Fact] public void TestThrowsExceptionWithNoParameter() { string strParamName = null; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes); Assert.Throws<ArgumentOutOfRangeException>(() => { ParameterBuilder paramBuilder = builder.DefineParameter(1, ParameterAttributes.HasDefault, strParamName); }); } [Fact] public void TestThrowsExceptionForNegativePosition() { string strParamName = null; int paramPos = 0; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); paramPos = _generator.GetInt32(); if (paramPos > 0) { paramPos = 0 - paramPos; } TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes); Assert.Throws<ArgumentOutOfRangeException>(() => { ParameterBuilder paramBuilder = builder.DefineParameter(paramPos, ParameterAttributes.HasDefault, strParamName); }); } [Fact] public void TestThrowsExceptionForPositionGreaterThanNumberOfParameters() { string strParamName = null; int paramPos = 0; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] paramTypes = new Type[] { typeof(int) }; while (paramPos < paramTypes.Length) { paramPos = _generator.GetInt32(); } TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); Assert.Throws<ArgumentOutOfRangeException>(() => { ParameterBuilder paramBuilder = builder.DefineParameter(paramPos, ParameterAttributes.HasDefault, strParamName); }); } [Fact] public void TestThrowsExceptionForCreateTypeCalled() { string strParamName = null; strParamName = _generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] paramTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod( PosTestDynamicMethodName, TestMethodAttributes, typeof(void), paramTypes); typeBuilder.CreateTypeInfo().AsType(); Assert.Throws<InvalidOperationException>(() => { ParameterBuilder paramBuilder = builder.DefineParameter(1, ParameterAttributes.HasDefault, strParamName); }); } private void VerifyParameterBuilder( ParameterBuilder actualBuilder, string desiredName, ParameterAttributes desiredAttributes, int desiredPosition) { const int ReservedMaskParameterAttribute = 0xF000; // This constant maps to ParameterAttributes.ReservedMask that is not available in the contract. Assert.Equal(desiredName, actualBuilder.Name); int removedReservedAttributes = (int)desiredAttributes & ~ReservedMaskParameterAttribute; Assert.Equal((int)removedReservedAttributes, (actualBuilder.Attributes & (int)removedReservedAttributes)); Assert.Equal(desiredPosition, actualBuilder.Position); } } }
using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Scripting.JavaScript.SafeHandles; namespace Microsoft.Scripting { internal sealed class ChakraApi { #region API method type definitions [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetFalseValue(out JavaScriptValueSafeHandle globalHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsHasException([MarshalAsAttribute(UnmanagedType.U1)] out bool has); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateObject(out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateExternalObject(IntPtr data, IntPtr finalizeCallback, out JavaScriptValueSafeHandle handle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateSymbol(JavaScriptValueSafeHandle descriptionHandle, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateArray(uint length, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateFunction(IntPtr callback, IntPtr extraData, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateNamedFunction(JavaScriptValueSafeHandle nameHandle, IntPtr callback, IntPtr extraData, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsIdle(out uint nextTick); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetAndClearException(out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetException(JavaScriptValueSafeHandle exception); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateRangeError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateReferenceError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateSyntaxError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateTypeError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateURIError(JavaScriptValueSafeHandle message, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsStartDebugging(); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsParseScript([MarshalAsAttribute(UnmanagedType.LPWStr)] string script, IntPtr sourceContextId, [MarshalAsAttribute(UnmanagedType.LPWStr)] string sourceUrl, out JavaScriptValueSafeHandle handle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsParseSerializedScript([MarshalAsAttribute(UnmanagedType.LPWStr)] string script, IntPtr buffer, IntPtr sourceContext, [MarshalAsAttribute(UnmanagedType.LPWStr)] string sourceUrl, out JavaScriptValueSafeHandle handle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSerializeScript([MarshalAsAttribute(UnmanagedType.LPWStr)] string script, IntPtr buffer, ref uint bufferSize); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsRunScript([MarshalAsAttribute(UnmanagedType.LPWStr)] string script, IntPtr sourceContextId, [MarshalAsAttribute(UnmanagedType.LPWStr)] string sourceUrl, out JavaScriptValueSafeHandle handle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsRunSerializedScript([MarshalAsAttribute(UnmanagedType.LPWStr)] string script, IntPtr buffer, IntPtr sourceContext, [MarshalAsAttribute(UnmanagedType.LPWStr)] string sourceUrl, out JavaScriptValueSafeHandle handle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCallFunction(JavaScriptValueSafeHandle fnHandle, [MarshalAsAttribute(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] arguments, ushort argCount, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsConstructObject(JavaScriptValueSafeHandle fnHandle, [MarshalAsAttribute(UnmanagedType.LPArray, SizeParamIndex = 2)] IntPtr[] arguments, ushort argCount, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetPropertyIdFromName([MarshalAsAttribute(UnmanagedType.LPWStr)] string propertyName, out IntPtr propertyId); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetPropertyIdFromSymbol(JavaScriptValueSafeHandle valueHandle, out IntPtr propertyId); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetProperty(JavaScriptValueSafeHandle obj, IntPtr propertyId, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetProperty(JavaScriptValueSafeHandle obj, IntPtr propertyId, JavaScriptValueSafeHandle propertyValue, [MarshalAsAttribute(UnmanagedType.U1)] bool useStrictSemantics); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDeleteProperty(JavaScriptValueSafeHandle obj, IntPtr propertyId, [MarshalAsAttribute(UnmanagedType.U1)] bool useStrictSemantics, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetIndexedProperty(JavaScriptValueSafeHandle obj, JavaScriptValueSafeHandle index, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetIndexedProperty(JavaScriptValueSafeHandle obj, JavaScriptValueSafeHandle index, JavaScriptValueSafeHandle value); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDeleteIndexedProperty(JavaScriptValueSafeHandle obj, JavaScriptValueSafeHandle index); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsHasProperty(JavaScriptValueSafeHandle obj, IntPtr propertyId, [MarshalAsAttribute(UnmanagedType.U1)] out bool has); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetOwnPropertyDescriptor(JavaScriptValueSafeHandle obj, IntPtr propertyId, out JavaScriptValueSafeHandle descriptor); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDefineProperty(JavaScriptValueSafeHandle obj, IntPtr propId, JavaScriptValueSafeHandle descriptorRef, [MarshalAsAttribute(UnmanagedType.U1)] out bool wasSet); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetOwnPropertyNames(JavaScriptValueSafeHandle obj, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetOwnPropertySymbols(JavaScriptValueSafeHandle obj, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsPreventExtension(JavaScriptValueSafeHandle obj); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetExtensionAllowed(JavaScriptValueSafeHandle obj, [MarshalAsAttribute(UnmanagedType.U1)] out bool allowed); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetPrototype(JavaScriptValueSafeHandle obj, out JavaScriptValueSafeHandle prototype); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetPrototype(JavaScriptValueSafeHandle obj, JavaScriptValueSafeHandle prototype); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetArrayBufferStorage(JavaScriptValueSafeHandle obj, out IntPtr buffer, out uint len); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetTypedArrayStorage(JavaScriptValueSafeHandle obj, out IntPtr buf, out uint len, out JavaScript.JavaScriptTypedArrayType type, out int elemSize); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetGlobalObject(out JavaScriptValueSafeHandle globalHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetUndefinedValue(out JavaScriptValueSafeHandle globalHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetNullValue(out JavaScriptValueSafeHandle globalHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetTrueValue(out JavaScriptValueSafeHandle globalHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsAddRef(IntPtr @ref, out uint count); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsRelease(IntPtr @ref, out uint count); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDisposeRuntime(IntPtr runtime); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateRuntime(JsRuntimeAttributes attributes, IntPtr threadService, out JavaScriptRuntimeSafeHandle runtime); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetRuntimeMemoryAllocationCallback(JavaScriptRuntimeSafeHandle runtime, IntPtr extraInformation, IntPtr pfnCallback); [System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.Winapi)] public delegate Microsoft.Scripting.JsErrorCode FnJsSetRuntimeMemoryAllocationCallbackWithIntPtr(IntPtr runtime, System.IntPtr extraInformation, System.IntPtr pfnCallback); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCollectGarbage(JavaScriptRuntimeSafeHandle runtime); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDisableRuntimeExecution(JavaScriptRuntimeSafeHandle runtime); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsEnableRuntimeExecution(JavaScriptRuntimeSafeHandle runtime); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetRuntimeMemoryUsage(JavaScriptRuntimeSafeHandle runtime, out ulong usage); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsIsRuntimeExecutionDisabled(JavaScriptRuntimeSafeHandle runtime, out bool isDisabled); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsCreateContext(JavaScriptRuntimeSafeHandle runtime, out JavaScriptEngineSafeHandle engine); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetCurrentContext(JavaScriptEngineSafeHandle contextHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsBooleanToBool(JavaScriptValueSafeHandle valueRef, [MarshalAsAttribute(UnmanagedType.U1)] out bool result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsConvertValueToBoolean(JavaScriptValueSafeHandle valueToConvert, out JavaScriptValueSafeHandle resultHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsNumberToDouble(JavaScriptValueSafeHandle valueRef, out double result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsDoubleToNumber(double value, out JavaScriptValueSafeHandle result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsConvertValueToNumber(JavaScriptValueSafeHandle valueToConvert, out JavaScriptValueSafeHandle resultHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetValueType(JavaScriptValueSafeHandle value, out JsValueType kind); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsNumberToInt(JavaScriptValueSafeHandle valueRef, out int result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsIntToNumber(int value, out JavaScriptValueSafeHandle result); // ***unsafe*** [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public unsafe delegate JsErrorCode FnJsPointerToString(void* psz, int length, out JavaScriptValueSafeHandle result); // ***unsafe*** [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public unsafe delegate JsErrorCode FnJsStringToPointer(JavaScriptValueSafeHandle str, out void* result, out uint strLen); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsConvertValueToString(JavaScriptValueSafeHandle valueToConvert, out JavaScriptValueSafeHandle resultHandle); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsEquals(JavaScriptValueSafeHandle obj1, JavaScriptValueSafeHandle obj2, [MarshalAsAttribute(UnmanagedType.U1)] out bool result); [UnmanagedFunctionPointerAttribute(CallingConvention.Winapi)] public delegate JsErrorCode FnJsStrictEquals(JavaScriptValueSafeHandle obj1, JavaScriptValueSafeHandle obj2, [MarshalAsAttribute(UnmanagedType.U1)] out bool result); [UnmanagedFunctionPointer(CallingConvention.Winapi)] public delegate JsErrorCode FnJsGetExternalData(JavaScriptValueSafeHandle @ref, out IntPtr externalData); [UnmanagedFunctionPointer(CallingConvention.Winapi)] public delegate JsErrorCode FnJsSetExternalData(JavaScriptValueSafeHandle @ref, IntPtr externalData); #endregion #region Field definitions public readonly FnJsGetFalseValue JsGetFalseValue; public readonly FnJsHasException JsHasException; public readonly FnJsCreateObject JsCreateObject; public readonly FnJsCreateExternalObject JsCreateExternalObject; public readonly FnJsCreateSymbol JsCreateSymbol; public readonly FnJsCreateArray JsCreateArray; public readonly FnJsCreateFunction JsCreateFunction; public readonly FnJsCreateNamedFunction JsCreateNamedFunction; public readonly FnJsIdle JsIdle; public readonly FnJsGetAndClearException JsGetAndClearException; public readonly FnJsSetException JsSetException; public readonly FnJsCreateError JsCreateError; public readonly FnJsCreateRangeError JsCreateRangeError; public readonly FnJsCreateReferenceError JsCreateReferenceError; public readonly FnJsCreateSyntaxError JsCreateSyntaxError; public readonly FnJsCreateTypeError JsCreateTypeError; public readonly FnJsCreateURIError JsCreateURIError; public readonly FnJsStartDebugging JsStartDebugging; public readonly FnJsParseScript JsParseScript; public readonly FnJsParseSerializedScript JsParseSerializedScript; public readonly FnJsSerializeScript JsSerializeScript; public readonly FnJsRunScript JsRunScript; public readonly FnJsRunSerializedScript JsRunSerializedScript; public readonly FnJsCallFunction JsCallFunction; public readonly FnJsConstructObject JsConstructObject; public readonly FnJsGetPropertyIdFromName JsGetPropertyIdFromName; public readonly FnJsGetPropertyIdFromSymbol JsGetPropertyIdFromSymbol; public readonly FnJsGetProperty JsGetProperty; public readonly FnJsSetProperty JsSetProperty; public readonly FnJsDeleteProperty JsDeleteProperty; public readonly FnJsGetIndexedProperty JsGetIndexedProperty; public readonly FnJsSetIndexedProperty JsSetIndexedProperty; public readonly FnJsDeleteIndexedProperty JsDeleteIndexedProperty; public readonly FnJsHasProperty JsHasProperty; public readonly FnJsGetOwnPropertyDescriptor JsGetOwnPropertyDescriptor; public readonly FnJsDefineProperty JsDefineProperty; public readonly FnJsGetOwnPropertyNames JsGetOwnPropertyNames; public readonly FnJsGetOwnPropertySymbols JsGetOwnPropertySymbols; public readonly FnJsPreventExtension JsPreventExtension; public readonly FnJsGetExtensionAllowed JsGetExtensionAllowed; public readonly FnJsGetPrototype JsGetPrototype; public readonly FnJsSetPrototype JsSetPrototype; public readonly FnJsGetArrayBufferStorage JsGetArrayBufferStorage; public readonly FnJsGetTypedArrayStorage JsGetTypedArrayStorage; public readonly FnJsGetGlobalObject JsGetGlobalObject; public readonly FnJsGetUndefinedValue JsGetUndefinedValue; public readonly FnJsGetNullValue JsGetNullValue; public readonly FnJsGetTrueValue JsGetTrueValue; public readonly FnJsAddRef JsAddRef; public readonly FnJsRelease JsRelease; public readonly FnJsDisposeRuntime JsDisposeRuntime; public readonly FnJsCreateRuntime JsCreateRuntime; public readonly FnJsSetRuntimeMemoryAllocationCallback JsSetRuntimeMemoryAllocationCallback; public readonly FnJsSetRuntimeMemoryAllocationCallbackWithIntPtr JsSetRuntimeMemoryAllocationCallbackWithIntPtr; public readonly FnJsCollectGarbage JsCollectGarbage; public readonly FnJsDisableRuntimeExecution JsDisableRuntimeExecution; public readonly FnJsEnableRuntimeExecution JsEnableRuntimeExecution; public readonly FnJsGetRuntimeMemoryUsage JsGetRuntimeMemoryUsage; public readonly FnJsIsRuntimeExecutionDisabled JsIsRuntimeExecutionDisabled; public readonly FnJsCreateContext JsCreateContext; public readonly FnJsSetCurrentContext JsSetCurrentContext; public JsErrorCode JsReleaseCurrentContext() { return JsSetCurrentContext(new JavaScriptEngineSafeHandle(IntPtr.Zero)); } public readonly FnJsBooleanToBool JsBooleanToBool; public readonly FnJsConvertValueToBoolean JsConvertValueToBoolean; public readonly FnJsNumberToDouble JsNumberToDouble; public readonly FnJsDoubleToNumber JsDoubleToNumber; public readonly FnJsConvertValueToNumber JsConvertValueToNumber; public readonly FnJsGetValueType JsGetValueType; public readonly FnJsNumberToInt JsNumberToInt; public readonly FnJsIntToNumber JsIntToNumber; public readonly FnJsPointerToString JsPointerToString; public readonly FnJsStringToPointer JsStringToPointer; public readonly FnJsConvertValueToString JsConvertValueToString; public readonly FnJsEquals JsEquals; public readonly FnJsStrictEquals JsStrictEquals; public readonly FnJsGetExternalData JsGetExternalData; public readonly FnJsSetExternalData JsSetExternalData; #endregion private static System.Lazy<ChakraApi> sharedInstance_ = new System.Lazy<ChakraApi>(Load); private static class NativeMethods { [DllImport("kernel32", SetLastError = true)] public static extern IntPtr LoadLibrary(string lpFileName); [DllImport("kernel32", SetLastError = true)] public static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags); [DllImport("kernel32", SetLastError = true)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); } internal ChakraApi(IntPtr hModule) { SetFn(ref JsAddRef, hModule, "JsAddRef"); SetFn(ref JsBooleanToBool, hModule, "JsBooleanToBool"); SetFn(ref JsCallFunction, hModule, "JsCallFunction"); SetFn(ref JsCollectGarbage, hModule, "JsCollectGarbage"); SetFn(ref JsConstructObject, hModule, "JsConstructObject"); SetFn(ref JsConvertValueToBoolean, hModule, "JsConvertValueToBoolean"); SetFn(ref JsConvertValueToNumber, hModule, "JsConvertValueToNumber"); SetFn(ref JsConvertValueToString, hModule, "JsConvertValueToString"); SetFn(ref JsCreateArray, hModule, "JsCreateArray"); SetFn(ref JsCreateContext, hModule, "JsCreateContext"); SetFn(ref JsCreateError, hModule, "JsCreateError"); SetFn(ref JsCreateExternalObject, hModule, "JsCreateExternalObject"); SetFn(ref JsCreateFunction, hModule, "JsCreateFunction"); SetFn(ref JsCreateNamedFunction, hModule, "JsCreateNamedFunction"); SetFn(ref JsCreateObject, hModule, "JsCreateObject"); SetFn(ref JsCreateRangeError, hModule, "JsCreateRangeError"); SetFn(ref JsCreateReferenceError, hModule, "JsCreateReferenceError"); SetFn(ref JsCreateRuntime, hModule, "JsCreateRuntime"); SetFn(ref JsCreateSymbol, hModule, "JsCreateSymbol"); SetFn(ref JsCreateSyntaxError, hModule, "JsCreateSyntaxError"); SetFn(ref JsCreateTypeError, hModule, "JsCreateTypeError"); SetFn(ref JsCreateURIError, hModule, "JsCreateURIError"); SetFn(ref JsDefineProperty, hModule, "JsDefineProperty"); SetFn(ref JsDeleteIndexedProperty, hModule, "JsDeleteIndexedProperty"); SetFn(ref JsDeleteProperty, hModule, "JsDeleteProperty"); SetFn(ref JsDisableRuntimeExecution, hModule, "JsDisableRuntimeExecution"); SetFn(ref JsDisposeRuntime, hModule, "JsDisposeRuntime"); SetFn(ref JsDoubleToNumber, hModule, "JsDoubleToNumber"); SetFn(ref JsEnableRuntimeExecution, hModule, "JsEnableRuntimeExecution"); SetFn(ref JsEquals, hModule, "JsEquals"); SetFn(ref JsGetAndClearException, hModule, "JsGetAndClearException"); SetFn(ref JsGetArrayBufferStorage, hModule, "JsGetArrayBufferStorage"); SetFn(ref JsGetExtensionAllowed, hModule, "JsGetExtensionAllowed"); SetFn(ref JsGetFalseValue, hModule, "JsGetFalseValue"); SetFn(ref JsGetGlobalObject, hModule, "JsGetGlobalObject"); SetFn(ref JsGetIndexedProperty, hModule, "JsGetIndexedProperty"); SetFn(ref JsGetNullValue, hModule, "JsGetNullValue"); SetFn(ref JsGetOwnPropertyDescriptor, hModule, "JsGetOwnPropertyDescriptor"); SetFn(ref JsGetOwnPropertyNames, hModule, "JsGetOwnPropertyNames"); SetFn(ref JsGetOwnPropertySymbols, hModule, "JsGetOwnPropertySymbols"); SetFn(ref JsGetProperty, hModule, "JsGetProperty"); SetFn(ref JsGetPropertyIdFromName, hModule, "JsGetPropertyIdFromName"); SetFn(ref JsGetPropertyIdFromSymbol, hModule, "JsGetPropertyIdFromSymbol"); SetFn(ref JsGetPrototype, hModule, "JsGetPrototype"); SetFn(ref JsGetRuntimeMemoryUsage, hModule, "JsGetRuntimeMemoryUsage"); SetFn(ref JsGetTrueValue, hModule, "JsGetTrueValue"); SetFn(ref JsGetTypedArrayStorage, hModule, "JsGetTypedArrayStorage"); SetFn(ref JsGetUndefinedValue, hModule, "JsGetUndefinedValue"); SetFn(ref JsGetValueType, hModule, "JsGetValueType"); SetFn(ref JsHasException, hModule, "JsHasException"); SetFn(ref JsHasProperty, hModule, "JsHasProperty"); SetFn(ref JsIdle, hModule, "JsIdle"); SetFn(ref JsIntToNumber, hModule, "JsIntToNumber"); SetFn(ref JsIsRuntimeExecutionDisabled, hModule, "JsIsRuntimeExecutionDisabled"); SetFn(ref JsNumberToDouble, hModule, "JsNumberToDouble"); SetFn(ref JsNumberToInt, hModule, "JsNumberToInt"); SetFn(ref JsParseScript, hModule, "JsParseScript"); SetFn(ref JsParseSerializedScript, hModule, "JsParseSerializedScript"); SetFn(ref JsPointerToString, hModule, "JsPointerToString"); SetFn(ref JsPreventExtension, hModule, "JsPreventExtension"); SetFn(ref JsRelease, hModule, "JsRelease"); SetFn(ref JsRunScript, hModule, "JsRunScript"); SetFn(ref JsRunSerializedScript, hModule, "JsRunSerializedScript"); SetFn(ref JsSerializeScript, hModule, "JsSerializeScript"); SetFn(ref JsSetCurrentContext, hModule, "JsSetCurrentContext"); SetFn(ref JsSetException, hModule, "JsSetException"); SetFn(ref JsSetIndexedProperty, hModule, "JsSetIndexedProperty"); SetFn(ref JsSetProperty, hModule, "JsSetProperty"); SetFn(ref JsSetPrototype, hModule, "JsSetPrototype"); SetFn(ref JsSetRuntimeMemoryAllocationCallback, hModule, "JsSetRuntimeMemoryAllocationCallback"); SetFn(ref JsStartDebugging, hModule, "JsStartDebugging", optional: true); SetFn(ref JsStrictEquals, hModule, "JsStrictEquals"); SetFn(ref JsStringToPointer, hModule, "JsStringToPointer"); SetFn(ref JsGetExternalData, hModule, "JsGetExternalData"); SetFn(ref JsSetExternalData, hModule, "JsSetExternalData"); } public static ChakraApi Instance { get { return sharedInstance_.Value; } } private static void ThrowForNative() { int hr = Marshal.GetHRForLastWin32Error(); throw Marshal.GetExceptionForHR(hr); } private static void SetFn<TDelegate>(ref TDelegate target, IntPtr hModule, string procName, bool optional = false) where TDelegate : class { IntPtr procAddr = NativeMethods.GetProcAddress(hModule, procName); if (IntPtr.Zero != procAddr) { target = Marshal.GetDelegateForFunctionPointer<TDelegate>(procAddr); } else if (!optional) { ThrowForNative(); } } private static ChakraApi Load() { string myPath = "."; string directory = Path.GetDirectoryName(myPath); string arch = "x86"; if (IntPtr.Size == 8) { arch = "x64"; } #if DEBUG string build = "dbg"; #else string build = "fre"; #endif string mainPath = Path.Combine(directory, "ChakraCore", build, arch, "ChakraCore.dll"); if (File.Exists(mainPath)) { return FromFile(mainPath); } string alternatePath = Path.Combine(directory, "ChakraCore", arch, "ChakraCore.dll"); if (File.Exists(alternatePath)) { return FromFile(alternatePath); } string localPath = Path.Combine(directory, "ChakraCore.dll"); if (File.Exists(localPath)) { return FromFile(localPath); } IntPtr hMod = NativeMethods.LoadLibrary("chakra.dll"); if (hMod != IntPtr.Zero) { return new ChakraApi(hMod); } throw new FileNotFoundException(string.Format("Could not locate a copy of ChakraCore.dll to load. The following paths were trie" + "d:\n\t{0}\n\t{1}\n\t{2}\n\nEnsure that an architecture-appropriate copy of ChakraCore.dl" + "l is included in your project. Also tried to load the system-provided Chakra.dll.", mainPath, alternatePath, localPath)); } public static ChakraApi FromFile(string filePath) { if ((false == File.Exists(filePath))) { throw new FileNotFoundException("The library could not be located at the specified path.", filePath); } IntPtr hMod = NativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, 0); if ((hMod == IntPtr.Zero)) { ThrowForNative(); } return new ChakraApi(hMod); } } }
using System; using System.Text; using System.Linq; namespace Phonix.Test { using NUnit.Framework; [TestFixture] public class SyllableBuilderTest { private readonly IMatrixMatcher SegmentA = new MatrixMatcher(FeatureMatrixTest.MatrixA); private readonly IMatrixMatcher SegmentB = new MatrixMatcher(FeatureMatrixTest.MatrixB); private readonly IMatrixMatcher SegmentC = new MatrixMatcher(FeatureMatrixTest.MatrixC); private Word GetTestWord() { var segs = new FeatureMatrix[] { FeatureMatrixTest.MatrixB, FeatureMatrixTest.MatrixC, FeatureMatrixTest.MatrixA, FeatureMatrixTest.MatrixC, FeatureMatrixTest.MatrixB, }; return new Word(segs); } private static string ShowSyllables(Word word) { return ShowSyllables(SymbolSetTest.GetTestSet(), word); } public static string ShowSyllables(SymbolSet symbols, Word word) { StringBuilder str = new StringBuilder(); Segment lastSyll = null; Segment lastSegment = null; foreach (var segment in word) { Segment thisSyll; if (segment.HasAncestor(Tier.Syllable)) { var ancestors = segment.FindAncestors(Tier.Syllable); Assert.AreEqual(1, ancestors.Count(), String.Format("{0} is linked to two syllables", symbols.Spell(segment.Matrix))); thisSyll = ancestors.First(); if (thisSyll != lastSyll) { if (lastSyll != null) { str.Append(">"); } str.Append("<"); lastSyll = thisSyll; } } else { if (lastSyll != null) { str.Append(">"); } lastSyll = null; } if (lastSegment != null) { if (segment.HasAncestor(Tier.Nucleus) && lastSegment.HasAncestor(Tier.Onset)) { str.Append(":"); } else if (segment.HasAncestor(Tier.Coda) && lastSegment.HasAncestor(Tier.Nucleus)) { str.Append("."); } } str.Append(symbols.Spell(segment.Matrix)); lastSegment = segment; } if (lastSyll != null) { str.Append(">"); } return str.ToString(); } [Test] public void Ctor() { var syll = new SyllableBuilder(); Assert.IsNotNull(syll.Onsets); Assert.IsNotNull(syll.Nuclei); Assert.IsNotNull(syll.Codas); } [Test] public void GetSyllableRule() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentB }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); Assert.AreEqual(rule.Name, "syllabify"); Assert.IsNotNull(rule.Description); Console.WriteLine(rule.Description); // negative tests syll.Nuclei.Clear(); try { rule = syll.GetSyllableRule(); Assert.Fail("should have thrown InvalidOperationException"); } catch (InvalidOperationException) { syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); } } [Test] public void RuleDescription() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentB }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); Assert.IsTrue(rule.Description.Contains("onset")); Assert.IsTrue(rule.Description.Contains("nucleus")); Assert.IsTrue(rule.Description.Contains("coda")); Assert.IsTrue(rule.Description.Contains(SegmentA.ToString())); Assert.IsTrue(rule.Description.Contains(SegmentB.ToString())); Assert.IsTrue(rule.Description.Contains(SegmentC.ToString())); Assert.IsFalse(rule.Description.Contains(Environment.NewLine)); } [Test] public void ShowApplication() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); // guarantee that this doesn't throw an exception rule.ShowApplication(word, word.Slice(Direction.Rightward).First(), new SymbolSet()); } [Test] public void CAC() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("b<c:a.c>b", ShowSyllables(word)); } [Test] public void ResyllabifyCAC() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); int applied = 0; rule.Applied += (r, w, s) => { applied++; }; rule.Apply(word); Assert.AreEqual(1, applied); var firstSyll = ShowSyllables(word); // now repeat and verify that we didn't change anything rule.Apply(word); Assert.AreEqual(firstSyll, ShowSyllables(word)); } [Test] public void MultiOnsetBCAC() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Onsets.Add(new IMatrixMatcher[] { SegmentB, SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("<bc:a.c>b", ShowSyllables(word)); } [Test] public void MultiCodaCACB() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC, SegmentB }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("b<c:a.cb>", ShowSyllables(word)); } [Test] public void MultiSyllBCCB() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentB }); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentB }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentC }); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("<b:c>a<c:b>", ShowSyllables(word)); } [Test] public void OverlappedCACCB() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentB }); syll.Codas.Add(new IMatrixMatcher[] { SegmentC }); syll.Codas.Add(new IMatrixMatcher[] {}); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("b<c:a><c:b>", ShowSyllables(word)); } [Test] public void Right() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentA }); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentC }); syll.Direction = SyllableBuilder.NucleusDirection.Right; var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("bc<a:c>b", ShowSyllables(word)); } [Test] public void Left() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] { SegmentA }); syll.Onsets.Add(new IMatrixMatcher[] { SegmentC }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentA }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentC }); syll.Direction = SyllableBuilder.NucleusDirection.Left; var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("b<c:a>cb", ShowSyllables(word)); } [Test] public void PreferOnset() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] {}); syll.Onsets.Add(new IMatrixMatcher[] { SegmentA }); syll.Onsets.Add(new IMatrixMatcher[] { SegmentB }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentC }); syll.Codas.Add(new IMatrixMatcher[] { SegmentA }); syll.Codas.Add(new IMatrixMatcher[] { SegmentB }); syll.Codas.Add(new IMatrixMatcher[] {}); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("<b:c><a:c.b>", ShowSyllables(word)); } [Test] public void MultiFeatureMatrix() { var syll = new SyllableBuilder(); syll.Onsets.Add(new IMatrixMatcher[] {}); syll.Onsets.Add(new IMatrixMatcher[] { new MatrixMatcher( new IMatchable[] { FeatureSetTest.GetTestSet().Get<BinaryFeature>("bn").PlusValue } ) }); syll.Nuclei.Add(new IMatrixMatcher[] { SegmentC }); syll.Codas.Add(new IMatrixMatcher[] {}); var rule = syll.GetSyllableRule(); var word = GetTestWord(); bool applied = false; rule.Applied += (r, w, s) => { applied = true; }; rule.Apply(word); Assert.IsTrue(applied); Assert.AreEqual("<b:c><a:c>b", ShowSyllables(word)); } } }
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using Potato.Core.Shared.Events; using Potato.Core.Shared.Models; using Potato.Database.Shared; using Potato.Net.Shared; using Potato.Net.Shared.Actions; using Potato.Net.Shared.Models; namespace Potato.Core.Shared { /// <summary> /// A single parameter to be used in a command /// </summary> [Serializable] public sealed class CommandParameter : ICommandParameter { /// <summary> /// Quick list to check if a type is known to us or not /// </summary> private static readonly List<Type> KnownTypes = new List<Type>() { typeof (String), typeof (ConnectionModel), typeof (ProtocolType), typeof (IProtocolAssemblyMetadata), typeof (Core.Shared.Models.GroupModel), typeof (AccountModel), typeof (AccessTokenTransportModel), typeof (PermissionModel), typeof (AccountPlayerModel), typeof (VariableModel), typeof (LanguageModel), typeof (TextCommandModel), typeof (TextCommandMatchModel), typeof (IGenericEvent), typeof (RepositoryModel), typeof (PackageWrapperModel), typeof (PluginModel), typeof (INetworkAction), typeof (ChatModel), typeof (PlayerModel), typeof (KillModel), typeof (MoveModel), typeof (SpawnModel), typeof (KickModel), typeof (BanModel), typeof (Settings), typeof (MapModel), typeof (ICommandResult), typeof (IDatabaseObject), typeof (IPacket) }; /// <summary> /// The data stored in this parameter. /// </summary> public ICommandData Data { get; set; } /// <summary> /// Initializes the parameter with default values. /// </summary> public CommandParameter() { this.Data = new CommandData(); } /// <summary> /// Fetches all of a type of list, cast to an Object. /// </summary> /// <param name="t"></param> /// <returns></returns> private List<Object> FetchAllByType(Type t) { List<Object> all = null; if (t == typeof(String) && this.Data.Content != null) { all = this.Data.Content.Cast<Object>().ToList(); } else if (t == typeof(ConnectionModel) && this.Data.Connections != null) { all = this.Data.Connections.Cast<Object>().ToList(); } else if (t == typeof(IProtocolAssemblyMetadata) && this.Data.ProtocolAssemblyMetadatas != null) { all = this.Data.ProtocolAssemblyMetadatas.Cast<Object>().ToList(); } else if (t == typeof(ProtocolType) && this.Data.ProtocolTypes != null) { all = this.Data.ProtocolTypes.Cast<Object>().ToList(); } else if (t == typeof(Core.Shared.Models.GroupModel) && this.Data.Groups != null) { all = this.Data.Groups.Cast<Object>().ToList(); } else if (t == typeof(AccountModel) && this.Data.Accounts != null) { all = this.Data.Accounts.Cast<Object>().ToList(); } else if (t == typeof(AccessTokenTransportModel) && this.Data.AccessTokens != null) { all = this.Data.AccessTokens.Cast<Object>().ToList(); } else if (t == typeof(PermissionModel) && this.Data.Permissions != null) { all = this.Data.Permissions.Cast<Object>().ToList(); } else if (t == typeof(AccountPlayerModel) && this.Data.AccountPlayers != null) { all = this.Data.AccountPlayers.Cast<Object>().ToList(); } else if (t == typeof(VariableModel) && this.Data.Variables != null) { all = this.Data.Variables.Cast<Object>().ToList(); } else if (t == typeof(LanguageModel) && this.Data.Languages != null) { all = this.Data.Languages.Cast<Object>().ToList(); } else if (t == typeof(TextCommandModel) && this.Data.TextCommands != null) { all = this.Data.TextCommands.Cast<Object>().ToList(); } else if (t == typeof(TextCommandMatchModel) && this.Data.TextCommandMatches != null) { all = this.Data.TextCommandMatches.Cast<Object>().ToList(); } else if (t == typeof(IGenericEvent) && this.Data.Events != null) { all = this.Data.Events.Cast<Object>().ToList(); } else if (t == typeof(RepositoryModel) && this.Data.Repositories != null) { all = this.Data.Repositories.Cast<Object>().ToList(); } else if (t == typeof(PackageWrapperModel) && this.Data.Packages != null) { all = this.Data.Packages.Cast<Object>().ToList(); } else if (t == typeof(PluginModel) && this.Data.Plugins != null) { all = this.Data.Plugins.Cast<Object>().ToList(); } else if (t == typeof(INetworkAction) && this.Data.NetworkActions != null) { all = this.Data.NetworkActions.Cast<Object>().ToList(); } else if (t == typeof(ChatModel) && this.Data.Chats != null) { all = this.Data.Chats.Cast<Object>().ToList(); } else if (t == typeof(PlayerModel) && this.Data.Players != null) { all = this.Data.Players.Cast<Object>().ToList(); } else if (t == typeof(KillModel) && this.Data.Kills != null) { all = this.Data.Kills.Cast<Object>().ToList(); } else if (t == typeof(MoveModel) && this.Data.Moves != null) { all = this.Data.Moves.Cast<Object>().ToList(); } else if (t == typeof(SpawnModel) && this.Data.Spawns != null) { all = this.Data.Spawns.Cast<Object>().ToList(); } else if (t == typeof(KickModel) && this.Data.Kicks != null) { all = this.Data.Kicks.Cast<Object>().ToList(); } else if (t == typeof(BanModel) && this.Data.Bans != null) { all = this.Data.Bans.Cast<Object>().ToList(); } else if (t == typeof(Settings) && this.Data.Settings != null) { all = this.Data.Settings.Cast<Object>().ToList(); } else if (t == typeof(MapModel) && this.Data.Maps != null) { all = this.Data.Maps.Cast<Object>().ToList(); } else if (t == typeof(ICommandResult) && this.Data.CommandResults != null) { all = this.Data.CommandResults.Cast<Object>().ToList(); } else if (t == typeof(IPacket) && this.Data.CommandResults != null) { all = this.Data.Packets.Cast<Object>().ToList(); } else if (t == typeof(IDatabaseObject) && this.Data.Queries != null) { all = this.Data.Queries.Cast<Object>().ToList(); } return all; } /// <summary> /// Converts a value to a specific type. Essentially a wrapper for Convert.ChangeType but /// checks for other common classes to convert to. /// </summary> /// <param name="value">The value to be changed</param> /// <param name="conversionType">The type to be changed to</param> /// <returns></returns> public Object ChangeType(Object value, Type conversionType) { Object changed = null; if (conversionType == typeof (Guid)) { changed = Guid.Parse((String)value); } else if (conversionType == typeof(DateTime)) { changed = DateTime.Parse((String)value); } else { changed = System.Convert.ChangeType(value, conversionType); } return changed; } public bool HasOne<T>(bool convert = true) { return this.HasOne(typeof(T), convert); } public bool HasOne(Type t, bool convert = true) { bool hasOne = false; if (CommandParameter.KnownTypes.Contains(t) == true && this.FetchAllByType(t) != null) { hasOne = true; } else if (convert == true) { if (t.IsEnum == true && this.HasOne<String>() == true && CommandParameter.ConvertToEnum(t, this.First<String>()) != null) { hasOne = true; } else if (this.HasOne<String>(false) == true) { try { hasOne = this.ChangeType(this.First<String>(false), t) != null; } catch { hasOne = false; } } } return hasOne; } public bool HasMany<T>(bool convert = true) { return this.HasMany(typeof(T), convert); } public bool HasMany(Type t, bool convert = true) { bool hasMany = false; if (CommandParameter.KnownTypes.Contains(t) == true) { List<Object> collection = this.FetchAllByType(t); hasMany = collection != null && collection.Count > 1; } else if (convert == true) { // If we're looking for an enum if (t.IsEnum == true) { List<String> strings = this.All<String>(); hasMany = strings.Select(s => CommandParameter.ConvertToEnum(t, s)).Count(e => e != null) == strings.Count; } // Else can we convert a list of strings to their type? else { List<String> strings = this.All<String>(); try { hasMany = strings.Select(s => this.ChangeType(s, t)).Count(e => e != null) == strings.Count; } catch { hasMany = false; } } } return hasMany; } public T First<T>(bool convert = true) { Object value = this.First(typeof(T), convert); return value != null ? (T)value : default(T); } public Object First(Type t, bool convert = true) { Object result = null; if (CommandParameter.KnownTypes.Contains(t) == true) { List<Object> collection = this.FetchAllByType(t); if (collection.Count > 0) { result = collection.FirstOrDefault(); } } else if (convert == true) { // If we're looking for an enum if (t.IsEnum == true) { // Convert the value, which will be null if no conversion exists. result = CommandParameter.ConvertToEnum(t, this.First<String>()); } // Else can we convert a list of strings to their type? else { try { result = this.ChangeType(this.First<String>(), t); } catch { result = null; } } } return result; } public Object All(Type t, bool convert = true) { Object result = null; if (CommandParameter.KnownTypes.Contains(t) == true) { result = this.FetchAllByType(t); } else if (convert == true) { // if we're looking for an enum if (t.IsEnum == true) { // Convert the value, which will be null if no conversion exists. result = this.All<String>() .Select(s => CommandParameter.ConvertToEnum(t, s)) .Where(e => e != null) .ToList(); } // Else can we convert a list of strings to their type? else { try { result = this.All<String>().Select(s => this.ChangeType(s, t)).Where(e => e != null).ToList(); } catch { result = null; } } } return result; } public List<T> All<T>() { List<T> result = new List<T>(); if (CommandParameter.KnownTypes.Contains(typeof(T)) == true) { List<Object> collection = this.FetchAllByType(typeof(T)); if (collection != null) { result = collection.Cast<T>().ToList(); } } return result; } /// <summary> /// Parses an enum either directly by assuming the value is a string or by assuming it's a primitive type. /// </summary> /// <param name="type">The type of enum we need</param> /// <param name="value">The value as an object that we need to convert to the enum</param> /// <returns>The converted value to enum</returns> private static Object ConvertToEnum(Type type, Object value) { Object enumValue = null; if (type.IsEnum == true && value != null) { string stringValue = value as string; if (stringValue != null) { if (Enum.IsDefined(type, stringValue) == true) { enumValue = Enum.Parse(type, stringValue); } } } return enumValue; } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Moq.Expressions.Visitors; using Moq.Properties; namespace Moq { /// <summary> /// Base class for mocks and static helper class with methods that apply to mocked objects, /// such as <see cref="Get"/> to retrieve a <see cref="Mock{T}"/> from an object instance. /// </summary> public abstract partial class Mock : IFluentInterface { internal static readonly MethodInfo GetMethod = typeof(Mock).GetMethod(nameof(Get), BindingFlags.Public | BindingFlags.Static); /// <summary> /// Initializes a new instance of the <see cref="Mock"/> class. /// </summary> protected Mock() { } /// <summary> /// Retrieves the mock object for the given object instance. /// </summary> /// <param name="mocked">The instance of the mocked object.</param> /// <typeparam name="T"> /// Type of the mock to retrieve. /// Can be omitted as it's inferred from the object instance passed in as the <paramref name="mocked"/> instance. /// </typeparam> /// <returns>The mock associated with the mocked object.</returns> /// <exception cref="ArgumentException">The received <paramref name="mocked"/> instance was not created by Moq.</exception> /// <example group="advanced"> /// The following example shows how to add a new setup to an object instance /// which is not the original <see cref="Mock{T}"/> but rather the object associated with it: /// <code> /// // Typed instance, not the mock, is retrieved from some test API. /// HttpContextBase context = GetMockContext(); /// /// // context.Request is the typed object from the "real" API /// // so in order to add a setup to it, we need to get /// // the mock that "owns" it /// Mock&lt;HttpRequestBase&gt; request = Mock.Get(context.Request); /// /// request.Setup(req => req.AppRelativeCurrentExecutionFilePath) /// .Returns(tempUrl); /// </code> /// </example> public static Mock<T> Get<T>(T mocked) where T : class { if (mocked is IMocked<T> mockedOfT) { // This would be the fastest check. return mockedOfT.Mock; } if (mocked is Delegate aDelegate && aDelegate.Target is IMocked<T> mockedDelegateImpl) { return mockedDelegateImpl.Mock; } if (mocked is IMocked mockedPlain) { // We may have received a T of an implemented // interface in the mock. var mock = mockedPlain.Mock; if (mock.ImplementsInterface(typeof(T))) { return mock.As<T>(); } // Alternatively, we may have been asked // for a type that is assignable to the // one for the mock. // This is not valid as generic types // do not support covariance on // the generic parameters. var imockedType = mocked.GetType().GetInterfaces().Single(i => i.Name.Equals("IMocked`1", StringComparison.Ordinal)); var mockedType = imockedType.GetGenericArguments()[0]; var types = string.Join( ", ", new[] {mockedType} // Ignore internally defined IMocked<T> .Concat(mock.InheritedInterfaces) .Concat(mock.AdditionalInterfaces) .Select(t => t.Name) .ToArray()); throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.InvalidMockGetType, typeof(T).Name, types)); } throw new ArgumentException(Resources.ObjectInstanceNotMock, "mocked"); } /// <summary> /// Verifies that all verifiable expectations have been met. /// </summary> /// <exception cref="MockException">Not all verifiable expectations were met.</exception> public static void Verify(params Mock[] mocks) { foreach (var mock in mocks) { mock.Verify(); } } /// <summary> /// Verifies all expectations regardless of whether they have been flagged as verifiable. /// </summary> /// <exception cref="MockException">At least one expectation was not met.</exception> public static void VerifyAll(params Mock[] mocks) { foreach (var mock in mocks) { mock.VerifyAll(); } } /// <summary> /// Gets the interfaces additionally implemented by the mock object. /// </summary> /// <remarks> /// This list may be modified by calls to <see cref="As{TInterface}"/> up until the first call to <see cref="Object"/>. /// </remarks> internal abstract List<Type> AdditionalInterfaces { get; } /// <summary> /// Behavior of the mock, according to the value set in the constructor. /// </summary> public abstract MockBehavior Behavior { get; } /// <summary> /// Whether the base member virtual implementation will be called for mocked classes if no setup is matched. /// Defaults to <see langword="false"/>. /// </summary> public abstract bool CallBase { get; set; } internal abstract object[] ConstructorArguments { get; } /// <summary> /// Specifies the behavior to use when returning default values for unexpected invocations on loose mocks. /// </summary> public DefaultValue DefaultValue { get { return this.DefaultValueProvider.Kind; } set { this.DefaultValueProvider = value switch { DefaultValue.Empty => DefaultValueProvider.Empty, DefaultValue.Mock => DefaultValueProvider.Mock, _ => throw new ArgumentOutOfRangeException(nameof(value)), }; } } internal abstract EventHandlerCollection EventHandlers { get; } /// <summary> /// Gets the mocked object instance. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Object", Justification = "Exposes the mocked object instance, so it's appropriate.")] [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The public Object property is the only one visible to Moq consumers. The protected member is for internal use only.")] public object Object => this.OnGetObject(); /// <summary> /// Gets the interfaces directly inherited from the mocked type (<see cref="MockedType"/>). /// </summary> internal abstract Type[] InheritedInterfaces { get; } internal abstract bool IsObjectInitialized { get; } /// <summary> /// Gets list of invocations which have been performed on this mock. /// </summary> public IInvocationList Invocations => MutableInvocations; internal abstract InvocationCollection MutableInvocations { get; } /// <summary> /// Returns the mocked object value. /// </summary> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is actually the protected virtual implementation of the property Object.")] protected abstract object OnGetObject(); /// <summary> /// Retrieves the type of the mocked object, its generic type argument. /// This is used in the auto-mocking of hierarchy access. /// </summary> internal abstract Type MockedType { get; } /// <summary> /// Gets or sets the <see cref="DefaultValueProvider"/> instance that will be used /// e. g. to produce default return values for unexpected invocations. /// </summary> public abstract DefaultValueProvider DefaultValueProvider { get; set; } /// <summary> /// The <see cref="Moq.DefaultValueProvider"/> used to initialize automatically stubbed properties. /// It is equal to the value of <see cref="Moq.Mock.DefaultValueProvider"/> at the time when /// <see cref="SetupAllProperties"/> was last called. /// </summary> internal abstract DefaultValueProvider AutoSetupPropertiesDefaultValueProvider { get; set; } internal abstract SetupCollection MutableSetups { get; } /// <summary> /// Gets the setups that have been configured on this mock, /// in chronological order (that is, oldest setup first, most recent setup last). /// </summary> public ISetupList Setups => this.MutableSetups; /// <summary> /// A set of switches that influence how this mock will operate. /// You can opt in or out of certain features via this property. /// </summary> public abstract Switches Switches { get; set; } #region Verify /// <summary> /// Verifies that all verifiable expectations have been met. /// </summary> /// <exception cref="MockException">Not all verifiable expectations were met.</exception> /// <example group="verification"> /// This example sets up an expectation and marks it as verifiable. /// After the mock is used, a <c>Verify()</c> call is issued on the mock /// to ensure the method in the setup was invoked: /// <code> /// var mock = new Mock&lt;IWarehouse&gt;(); /// this.Setup(x =&gt; x.HasInventory(TALISKER, 50)) /// .Returns(true) /// .Verifiable(); /// /// ... /// /// // Will throw if the test code did not call HasInventory. /// this.Verify(); /// </code> /// </example> public void Verify() { this.Verify(setup => !setup.IsOverridden && !setup.IsConditional && setup.IsVerifiable); } /// <summary> /// Verifies all expectations regardless of whether they have been flagged as verifiable. /// </summary> /// <exception cref="MockException">At least one expectation was not met.</exception> /// <example> /// This example sets up an expectation without marking it as verifiable. /// After the mock is used, a <see cref="VerifyAll"/> call is issued on the mock /// to ensure that all expectations are met: /// <code> /// var mock = new Mock&lt;IWarehouse&gt;(); /// this.Setup(x =&gt; x.HasInventory(TALISKER, 50)) /// .Returns(true); /// /// ... /// /// // Will throw if the test code did not call HasInventory, /// // even though that expectation was not marked as verifiable. /// mock.VerifyAll(); /// </code> /// </example> public void VerifyAll() { this.Verify(setup => !setup.IsOverridden && !setup.IsConditional); } private void Verify(Func<ISetup, bool> predicate) { var verifiedMocks = new HashSet<Mock>(); if (!this.TryVerify(predicate, verifiedMocks, out var error) && error.IsVerificationError) { throw error; } } internal bool TryVerify(Func<ISetup, bool> predicate, HashSet<Mock> verifiedMocks, out MockException error) { if (verifiedMocks.Add(this) == false) { // This mock has already been verified; don't verify it again. // (We can end up here e.g. when there are loops in the inner mock object graph.) error = null; return true; } foreach (Invocation invocation in this.MutableInvocations) { invocation.MarkAsVerifiedIfMatchedBy(predicate); } var errors = new List<MockException>(); foreach (var setup in this.MutableSetups.ToArray(predicate)) { if (predicate(setup) && !setup.TryVerify(recursive: true, predicate, verifiedMocks, out var e) && e.IsVerificationError) { errors.Add(e); } } if (errors.Count > 0) { error = MockException.Combined( errors, preamble: string.Format(CultureInfo.CurrentCulture, Resources.VerificationErrorsOfMock, this)); return false; } else { error = null; return true; } } internal static void Verify(Mock mock, LambdaExpression expression, Times times, string failMessage) { Guard.NotNull(times, nameof(times)); var invocationCount = Mock.GetMatchingInvocationCount(mock, expression, out var invocationsToBeMarkedAsVerified); if (times.Validate(invocationCount)) { foreach (var (invocation, part) in invocationsToBeMarkedAsVerified) { part.SetupEvaluatedSuccessfully(invocation); invocation.MarkAsVerified(); } } else { throw MockException.NoMatchingCalls(mock, expression, failMessage, times, invocationCount); } } internal static void VerifyGet(Mock mock, LambdaExpression expression, Times times, string failMessage) { Guard.NotNull(expression, nameof(expression)); if (!expression.IsPropertyIndexer()) // guard because `.ToPropertyInfo()` doesn't (yet) work for indexers { var property = expression.ToPropertyInfo(); Guard.CanRead(property); } Mock.Verify(mock, expression, times, failMessage); } internal static void VerifySet(Mock mock, LambdaExpression expression, Times times, string failMessage) { Guard.NotNull(expression, nameof(expression)); Guard.IsAssignmentToPropertyOrIndexer(expression, nameof(expression)); Mock.Verify(mock, expression, times, failMessage); } internal static void VerifyAdd(Mock mock, LambdaExpression expression, Times times, string failMessage) { Guard.NotNull(expression, nameof(expression)); Guard.IsEventAdd(expression, nameof(expression)); Mock.Verify(mock, expression, times, failMessage); } internal static void VerifyRemove(Mock mock, LambdaExpression expression, Times times, string failMessage) { Guard.NotNull(expression, nameof(expression)); Guard.IsEventRemove(expression, nameof(expression)); Mock.Verify(mock, expression, times, failMessage); } internal static void VerifyNoOtherCalls(Mock mock) { Mock.VerifyNoOtherCalls(mock, verifiedMocks: new HashSet<Mock>()); } private static void VerifyNoOtherCalls(Mock mock, HashSet<Mock> verifiedMocks) { if (!verifiedMocks.Add(mock)) return; var unverifiedInvocations = mock.MutableInvocations.ToArray(invocation => !invocation.IsVerified); var innerMockSetups = mock.MutableSetups.GetInnerMockSetups(); if (unverifiedInvocations.Any()) { // There are some invocations that shouldn't require explicit verification by the user. // The intent behind a `Verify` call for a call expression like `m.A.B.C.X` is probably // to verify `X`. If that succeeds, it's reasonable to expect that `m.A`, `m.A.B`, and // `m.A.B.C` have implicitly been verified as well. Below, invocations such as those to // the left of `X` are referred to as "transitive" (for lack of a better word). if (innerMockSetups.Any()) { for (int i = 0, n = unverifiedInvocations.Length; i < n; ++i) { // In order for an invocation to be "transitive", its return value has to be a // sub-object (inner mock); and that sub-object has to have received at least // one call: var wasTransitiveInvocation = innerMockSetups.TryFind(unverifiedInvocations[i]) is Setup inner && inner.InnerMock.MutableInvocations.Any(); if (wasTransitiveInvocation) { unverifiedInvocations[i] = null; } } } // "Transitive" invocations have been nulled out. Let's see what's left: var remainingUnverifiedInvocations = unverifiedInvocations.Where(i => i != null); if (remainingUnverifiedInvocations.Any()) { throw MockException.UnverifiedInvocations(mock, remainingUnverifiedInvocations); } } // Perform verification for all automatically created sub-objects (that is, those // created by "transitive" invocations): foreach (var inner in innerMockSetups) { VerifyNoOtherCalls(inner.InnerMock, verifiedMocks); } } private static int GetMatchingInvocationCount( Mock mock, LambdaExpression expression, out List<Pair<Invocation, InvocationShape>> invocationsToBeMarkedAsVerified) { Debug.Assert(mock != null); Debug.Assert(expression != null); invocationsToBeMarkedAsVerified = new List<Pair<Invocation, InvocationShape>>(); return Mock.GetMatchingInvocationCount( mock, new ImmutablePopOnlyStack<InvocationShape>(expression.Split()), new HashSet<Mock>(), invocationsToBeMarkedAsVerified); } private static int GetMatchingInvocationCount( Mock mock, in ImmutablePopOnlyStack<InvocationShape> parts, HashSet<Mock> visitedInnerMocks, List<Pair<Invocation, InvocationShape>> invocationsToBeMarkedAsVerified) { Debug.Assert(mock != null); Debug.Assert(!parts.Empty); Debug.Assert(visitedInnerMocks != null); // Several different invocations might return the same inner `mock`. // Keep track of the mocks whose invocations have already been counted: if (visitedInnerMocks.Contains(mock)) { return 0; } visitedInnerMocks.Add(mock); var part = parts.Pop(out var remainingParts); var count = 0; foreach (var matchingInvocation in mock.MutableInvocations.ToArray().Where(part.IsMatch)) { invocationsToBeMarkedAsVerified.Add(new Pair<Invocation, InvocationShape>(matchingInvocation, part)); if (remainingParts.Empty) { // We are not processing an intermediate part of a fluent expression. // Therefore, every matching invocation counts as one: ++count; } else { // We are processing an intermediate part of a fluent expression. // Therefore, all matching invocations are assumed to have a return value; // otherwise, they wouldn't be "chainable": Debug.Assert(matchingInvocation.Method.ReturnType != typeof(void)); // Intermediate parts of a fluent expression do not contribute to the // total count themselves. The matching invocation count of the rightmost // expression gets "forwarded" towards the left: if (Unwrap.ResultIfCompletedTask(matchingInvocation.ReturnValue) is IMocked mocked) { count += Mock.GetMatchingInvocationCount(mocked.Mock, remainingParts, visitedInnerMocks, invocationsToBeMarkedAsVerified); } } } return count; } #endregion #region Setup internal static MethodCall Setup(Mock mock, LambdaExpression expression, Condition condition) { Guard.NotNull(expression, nameof(expression)); return Mock.SetupRecursive(mock, expression, setupLast: (targetMock, originalExpression, part) => { var setup = new MethodCall(originalExpression, targetMock, condition, expectation: part); targetMock.MutableSetups.Add(setup); return setup; }); } internal static MethodCall SetupGet(Mock mock, LambdaExpression expression, Condition condition) { Guard.NotNull(expression, nameof(expression)); if (!expression.IsPropertyIndexer()) // guard because `.ToPropertyInfo()` doesn't (yet) work for indexers { var property = expression.ToPropertyInfo(); Guard.CanRead(property); } return Mock.Setup(mock, expression, condition); } internal static MethodCall SetupSet(Mock mock, LambdaExpression expression, Condition condition) { Guard.NotNull(expression, nameof(expression)); Guard.IsAssignmentToPropertyOrIndexer(expression, nameof(expression)); return Mock.Setup(mock, expression, condition); } internal static MethodCall SetupAdd(Mock mock, LambdaExpression expression, Condition condition) { Guard.NotNull(expression, nameof(expression)); Guard.IsEventAdd(expression, nameof(expression)); return Mock.Setup(mock, expression, condition); } internal static MethodCall SetupRemove(Mock mock, LambdaExpression expression, Condition condition) { Guard.NotNull(expression, nameof(expression)); Guard.IsEventRemove(expression, nameof(expression)); return Mock.Setup(mock, expression, condition); } internal static SequenceSetup SetupSequence(Mock mock, LambdaExpression expression) { Guard.NotNull(expression, nameof(expression)); return Mock.SetupRecursive(mock, expression, setupLast: (targetMock, originalExpression, part) => { var setup = new SequenceSetup(originalExpression, targetMock, expectation: part); targetMock.MutableSetups.Add(setup); return setup; }); } private static TSetup SetupRecursive<TSetup>(Mock mock, LambdaExpression expression, Func<Mock, Expression, InvocationShape, TSetup> setupLast) where TSetup : ISetup { Debug.Assert(mock != null); Debug.Assert(expression != null); Debug.Assert(setupLast != null); var parts = expression.Split(); return Mock.SetupRecursive(mock, originalExpression: expression, parts, setupLast); } private static TSetup SetupRecursive<TSetup>(Mock mock, LambdaExpression originalExpression, Stack<InvocationShape> parts, Func<Mock, Expression, InvocationShape, TSetup> setupLast) where TSetup : ISetup { var part = parts.Pop(); var (expr, method, arguments) = part; if (parts.Count == 0) { return setupLast(mock, originalExpression, part); } else { Mock innerMock; if (mock.MutableSetups.GetInnerMockSetups().TryFind(part) is Setup setup) { innerMock = setup.InnerMock; } else { var returnValue = mock.GetDefaultValue(method, out innerMock, useAlternateProvider: DefaultValueProvider.Mock); if (innerMock == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.UnsupportedExpression, expr.ToStringFixed() + " in " + originalExpression.ToStringFixed() + ":\n" + Resources.TypeNotMockable)); } setup = new InnerMockSetup(originalExpression, mock, expectation: part, returnValue); mock.MutableSetups.Add((Setup)setup); } Debug.Assert(innerMock != null); return Mock.SetupRecursive(innerMock, originalExpression, parts, setupLast); } } internal static void SetupAllProperties(Mock mock) { SetupAllProperties(mock, mock.DefaultValueProvider); } internal static void SetupAllProperties(Mock mock, DefaultValueProvider defaultValueProvider) { mock.MutableSetups.RemoveAllPropertyAccessorSetups(); // Removing all the previous properties setups to keep the behaviour of overriding // existing setups in `SetupAllProperties`. mock.AutoSetupPropertiesDefaultValueProvider = defaultValueProvider; // `SetupAllProperties` no longer performs properties setup like in previous versions. // Instead it just enables a switch to setup properties on-demand at the moment of first access. // In order for `SetupAllProperties`'s new mode of operation to be indistinguishable // from how it worked previously, it's important to capture the default value provider at this precise // moment, since it might be changed later (before queries to properties). } #endregion #region Raise internal static void RaiseEvent<T>(Mock mock, Action<T> action, object[] arguments) { Guard.NotNull(action, nameof(action)); var expression = ExpressionReconstructor.Instance.ReconstructExpression(action, mock.ConstructorArguments); var parts = expression.Split(); Mock.RaiseEvent(mock, expression, parts, arguments); } internal static void RaiseEvent(Mock mock, LambdaExpression expression, Stack<InvocationShape> parts, object[] arguments) { const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly; var part = parts.Pop(); var method = part.Method; if (parts.Count == 0) { EventInfo @event; if (method.IsEventAddAccessor()) { var implementingMethod = method.GetImplementingMethod(mock.Object.GetType()); @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetAddMethod(true) == implementingMethod); if (@event == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.SetupNotEventAdd, part.Expression)); } } else if (method.IsEventRemoveAccessor()) { var implementingMethod = method.GetImplementingMethod(mock.Object.GetType()); @event = implementingMethod.DeclaringType.GetEvents(bindingFlags).SingleOrDefault(e => e.GetRemoveMethod(true) == implementingMethod); if (@event == null) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.SetupNotEventRemove, part.Expression)); } } else { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.UnsupportedExpression, expression)); } if (mock.EventHandlers.TryGet(@event, out var handlers)) { handlers.InvokePreserveStack(arguments); } } else if (mock.MutableSetups.GetInnerMockSetups().TryFind(part) is Setup innerMockSetup) { Mock.RaiseEvent(innerMockSetup.InnerMock, expression, parts, arguments); } } #endregion #region As<TInterface> /// <summary> /// Adds an interface implementation to the mock, allowing setups to be specified for it. /// </summary> /// <remarks> /// This method can only be called before the first use of the mock <see cref="Object"/> property, /// at which point the runtime type has already been generated and no more interfaces can be added to it. /// <para> /// Also, <typeparamref name="TInterface"/> must be an interface and not a class, /// which must be specified when creating the mock instead. /// </para> /// </remarks> /// <typeparam name="TInterface">Type of interface to cast the mock to.</typeparam> /// <exception cref="ArgumentException">The <typeparamref name="TInterface"/> specified is not an interface.</exception> /// <exception cref="InvalidOperationException"> /// The mock type has already been generated by accessing the <see cref="Object"/> property. /// </exception> [SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "As", Justification = "We want the method called exactly as the keyword because that's what it does, it adds an implemented interface so that you can cast it later.")] public abstract Mock<TInterface> As<TInterface>() where TInterface : class; internal bool ImplementsInterface(Type interfaceType) { return this.InheritedInterfaces.Contains(interfaceType) || this.AdditionalInterfaces.Contains(interfaceType); } #endregion #region Default Values internal abstract Dictionary<Type, object> ConfiguredDefaultValues { get; } /// <summary> /// Defines the default return value for all mocked methods or properties with return type <typeparamref name= "TReturn" />. /// </summary> /// <typeparam name="TReturn">The return type for which to define a default value.</typeparam> /// <param name="value">The default return value.</param> /// <remarks> /// Default return value is respected only when there is no matching setup for a method call. /// </remarks> public void SetReturnsDefault<TReturn>(TReturn value) { this.ConfiguredDefaultValues[typeof(TReturn)] = value; } internal object GetDefaultValue(MethodInfo method, out Mock candidateInnerMock, DefaultValueProvider useAlternateProvider = null) { Debug.Assert(method != null); Debug.Assert(method.ReturnType != null); Debug.Assert(method.ReturnType != typeof(void)); if (this.ConfiguredDefaultValues.TryGetValue(method.ReturnType, out object configuredDefaultValue)) { candidateInnerMock = null; return configuredDefaultValue; } var result = (useAlternateProvider ?? this.DefaultValueProvider).GetDefaultReturnValue(method, this); var unwrappedResult = Unwrap.ResultIfCompletedTask(result); candidateInnerMock = (unwrappedResult as IMocked)?.Mock; return result; } #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.Globalization; using System.IO; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.Xml; namespace System.ServiceModel.Channels { public abstract class MessageHeader : MessageHeaderInfo { private const bool DefaultRelayValue = false; private const bool DefaultMustUnderstandValue = false; private const string DefaultActorValue = ""; public override string Actor { get { return ""; } } public override bool IsReferenceParameter { get { return false; } } public override bool MustUnderstand { get { return DefaultMustUnderstandValue; } } public override bool Relay { get { return DefaultRelayValue; } } public virtual bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageVersion)); } return true; } public override string ToString() { XmlWriterSettings xmlSettings = new XmlWriterSettings() { Indent = true }; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { using (XmlWriter textWriter = XmlWriter.Create(stringWriter, xmlSettings)) { using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(textWriter)) { if (IsMessageVersionSupported(MessageVersion.Soap12WSAddressing10)) { WriteHeader(writer, MessageVersion.Soap12WSAddressing10); } else if (IsMessageVersionSupported(MessageVersion.Soap12WSAddressingAugust2004)) { WriteHeader(writer, MessageVersion.Soap12WSAddressingAugust2004); } else if (IsMessageVersionSupported(MessageVersion.Soap11WSAddressing10)) { WriteHeader(writer, MessageVersion.Soap11WSAddressing10); } else if (IsMessageVersionSupported(MessageVersion.Soap11WSAddressingAugust2004)) { WriteHeader(writer, MessageVersion.Soap11WSAddressingAugust2004); } else if (IsMessageVersionSupported(MessageVersion.Soap12)) { WriteHeader(writer, MessageVersion.Soap12); } else if (IsMessageVersionSupported(MessageVersion.Soap11)) { WriteHeader(writer, MessageVersion.Soap11); } else { WriteHeader(writer, MessageVersion.None); } writer.Flush(); return stringWriter.ToString(); } } } } public void WriteHeader(XmlWriter writer, MessageVersion messageVersion) { WriteHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer), messageVersion); } public void WriteHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(writer))); } if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(messageVersion))); } OnWriteStartHeader(writer, messageVersion); OnWriteHeaderContents(writer, messageVersion); writer.WriteEndElement(); } public void WriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(writer))); } if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(messageVersion))); } OnWriteStartHeader(writer, messageVersion); } protected virtual void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(Name, Namespace); WriteHeaderAttributes(writer, messageVersion); } public void WriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(writer))); } if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(messageVersion))); } OnWriteHeaderContents(writer, messageVersion); } protected abstract void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion); protected void WriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion) { string actor = Actor; if (actor.Length > 0) { writer.WriteAttributeString(messageVersion.Envelope.DictionaryActor, messageVersion.Envelope.DictionaryNamespace, actor); } if (MustUnderstand) { writer.WriteAttributeString(XD.MessageDictionary.MustUnderstand, messageVersion.Envelope.DictionaryNamespace, "1"); } if (Relay && messageVersion.Envelope == EnvelopeVersion.Soap12) { writer.WriteAttributeString(XD.Message12Dictionary.Relay, XD.Message12Dictionary.Namespace, "1"); } } public static MessageHeader CreateHeader(string name, string ns, object value) { return CreateHeader(name, ns, value, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand) { return CreateHeader(name, ns, value, mustUnderstand, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor) { return CreateHeader(name, ns, value, mustUnderstand, actor, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, bool mustUnderstand, string actor, bool relay) { return new XmlObjectSerializerHeader(name, ns, value, null, mustUnderstand, actor, relay); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer) { return CreateHeader(name, ns, value, serializer, DefaultMustUnderstandValue, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand) { return CreateHeader(name, ns, value, serializer, mustUnderstand, DefaultActorValue, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor) { return CreateHeader(name, ns, value, serializer, mustUnderstand, actor, DefaultRelayValue); } public static MessageHeader CreateHeader(string name, string ns, object value, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) { if (serializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(serializer))); } return new XmlObjectSerializerHeader(name, ns, value, serializer, mustUnderstand, actor, relay); } internal static void GetHeaderAttributes(XmlDictionaryReader reader, MessageVersion version, out string actor, out bool mustUnderstand, out bool relay, out bool isReferenceParameter) { int attributeCount = reader.AttributeCount; if (attributeCount == 0) { mustUnderstand = false; actor = string.Empty; relay = false; isReferenceParameter = false; } else { string mustUnderstandString = reader.GetAttribute(XD.MessageDictionary.MustUnderstand, version.Envelope.DictionaryNamespace); if (mustUnderstandString != null && ToBoolean(mustUnderstandString)) { mustUnderstand = true; } else { mustUnderstand = false; } if (mustUnderstand && attributeCount == 1) { actor = string.Empty; relay = false; } else { actor = reader.GetAttribute(version.Envelope.DictionaryActor, version.Envelope.DictionaryNamespace); if (actor == null) { actor = ""; } if (version.Envelope == EnvelopeVersion.Soap12) { string relayString = reader.GetAttribute(XD.Message12Dictionary.Relay, version.Envelope.DictionaryNamespace); if (relayString != null && ToBoolean(relayString)) { relay = true; } else { relay = false; } } else { relay = false; } } isReferenceParameter = false; if (version.Addressing == AddressingVersion.WSAddressing10) { string refParam = reader.GetAttribute(XD.AddressingDictionary.IsReferenceParameter, version.Addressing.DictionaryNamespace); if (refParam != null) { isReferenceParameter = ToBoolean(refParam); } } } } private static bool ToBoolean(string value) { if (value.Length == 1) { char ch = value[0]; if (ch == '1') { return true; } if (ch == '0') { return false; } } else { if (value == "true") { return true; } else if (value == "false") { return false; } } try { return XmlConvert.ToBoolean(value); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, null)); } } } internal abstract class DictionaryHeader : MessageHeader { public override string Name { get { return DictionaryName.Value; } } public override string Namespace { get { return DictionaryNamespace.Value; } } public abstract XmlDictionaryString DictionaryName { get; } public abstract XmlDictionaryString DictionaryNamespace { get; } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { writer.WriteStartElement(DictionaryName, DictionaryNamespace); WriteHeaderAttributes(writer, messageVersion); } } internal class XmlObjectSerializerHeader : MessageHeader { private XmlObjectSerializer _serializer; private bool _mustUnderstand; private bool _relay; private bool _isOneTwoSupported; private bool _isOneOneSupported; private bool _isNoneSupported; private object _objectToSerialize; private string _name; private string _ns; private string _actor; private object _syncRoot = new object(); private XmlObjectSerializerHeader(XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) { _mustUnderstand = mustUnderstand; _relay = relay; _serializer = serializer; _actor = actor ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(actor)); if (actor == EnvelopeVersion.Soap12.UltimateDestinationActor) { _isOneOneSupported = false; _isOneTwoSupported = true; } else if (actor == EnvelopeVersion.Soap12.NextDestinationActorValue) { _isOneOneSupported = false; _isOneTwoSupported = true; } else if (actor == EnvelopeVersion.Soap11.NextDestinationActorValue) { _isOneOneSupported = true; _isOneTwoSupported = false; } else { _isOneOneSupported = true; _isOneTwoSupported = true; _isNoneSupported = true; } } public XmlObjectSerializerHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer, bool mustUnderstand, string actor, bool relay) : this(serializer, mustUnderstand, actor, relay) { if (null == name) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name))); } if (name.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.SFXHeaderNameCannotBeNullOrEmpty, "name")); } if (ns == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(ns)); } if (ns.Length > 0) { NamingHelper.CheckUriParameter(ns, "ns"); } _objectToSerialize = objectToSerialize; _name = name; _ns = ns; } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageVersion)); } if (messageVersion.Envelope == EnvelopeVersion.Soap12) { return _isOneTwoSupported; } else if (messageVersion.Envelope == EnvelopeVersion.Soap11) { return _isOneOneSupported; } else if (messageVersion.Envelope == EnvelopeVersion.None) { return _isNoneSupported; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, messageVersion.Envelope.ToString()))); } } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public override string Actor { get { return _actor; } } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { lock (_syncRoot) { if (_serializer == null) { _serializer = DataContractSerializerDefaults.CreateSerializer( (_objectToSerialize == null ? typeof(object) : _objectToSerialize.GetType()), Name, Namespace, int.MaxValue/*maxItems*/); } _serializer.WriteObjectContent(writer, _objectToSerialize); } } } internal abstract class ReadableMessageHeader : MessageHeader { public abstract XmlDictionaryReader GetHeaderReader(); protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (!IsMessageVersionSupported(messageVersion)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MessageHeaderVersionNotSupported, GetType().FullName, messageVersion.ToString()), "version")); } XmlDictionaryReader reader = GetHeaderReader(); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); reader.Dispose(); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { XmlDictionaryReader reader = GetHeaderReader(); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) { writer.WriteNode(reader, false); } reader.ReadEndElement(); reader.Dispose(); } } internal interface IMessageHeaderWithSharedNamespace { XmlDictionaryString SharedNamespace { get; } XmlDictionaryString SharedPrefix { get; } } internal class BufferedHeader : ReadableMessageHeader { private MessageVersion _version; private XmlBuffer _buffer; private int _bufferIndex; private string _actor; private bool _relay; private bool _mustUnderstand; private string _name; private string _ns; private bool _streamed; private bool _isRefParam; public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, string name, string ns, bool mustUnderstand, string actor, bool relay, bool isRefParam) { _version = version; _buffer = buffer; _bufferIndex = bufferIndex; _name = name; _ns = ns; _mustUnderstand = mustUnderstand; _actor = actor; _relay = relay; _isRefParam = isRefParam; } public BufferedHeader(MessageVersion version, XmlBuffer buffer, int bufferIndex, MessageHeaderInfo headerInfo) { _version = version; _buffer = buffer; _bufferIndex = bufferIndex; _actor = headerInfo.Actor; _relay = headerInfo.Relay; _name = headerInfo.Name; _ns = headerInfo.Namespace; _isRefParam = headerInfo.IsReferenceParameter; _mustUnderstand = headerInfo.MustUnderstand; } public BufferedHeader(MessageVersion version, XmlBuffer buffer, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes) { _streamed = true; _buffer = buffer; _version = version; GetHeaderAttributes(reader, version, out _actor, out _mustUnderstand, out _relay, out _isRefParam); _name = reader.LocalName; _ns = reader.NamespaceURI; Fx.Assert(_name != null, ""); Fx.Assert(_ns != null, ""); _bufferIndex = buffer.SectionCount; XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas); // Write an enclosing Envelope tag writer.WriteStartElement(MessageStrings.Envelope); if (envelopeAttributes != null) { XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer); } // Write and enclosing Header tag writer.WriteStartElement(MessageStrings.Header); if (headerAttributes != null) { XmlAttributeHolder.WriteAttributes(headerAttributes, writer); } writer.WriteNode(reader, false); writer.WriteEndElement(); writer.WriteEndElement(); buffer.CloseSection(); } public override string Actor { get { return _actor; } } public override bool IsReferenceParameter { get { return _isRefParam; } } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override bool MustUnderstand { get { return _mustUnderstand; } } public override bool Relay { get { return _relay; } } public override bool IsMessageVersionSupported(MessageVersion messageVersion) { if (messageVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(messageVersion))); } return messageVersion == _version; } public override XmlDictionaryReader GetHeaderReader() { XmlDictionaryReader reader = _buffer.GetReader(_bufferIndex); // See if we need to move past the enclosing envelope/header if (_streamed) { reader.MoveToContent(); reader.Read(); // Envelope reader.Read(); // Header reader.MoveToContent(); } return reader; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Gallio.Common.Reflection; using MbUnit.Framework; using MbUnit.TestResources; using MbUnit.TestResources.Fixtures; using Gallio.Model; using Gallio.Model.Filters; using Gallio.Tests; using Rhino.Mocks; namespace Gallio.Tests.Model.Filters { [TestFixture] [TestsOn(typeof(FilterParser<ITestDescriptor>))] [Author("Julian Hidalgo")] public class FilterParserTest : BaseTestWithMocks { private ITestDescriptor fixture1 = null; private ITestDescriptor fixture2 = null; private ITestDescriptor fixture3 = null; private ITestDescriptor fixture4 = null; private string fixture1TypeName = null; private string fixture2TypeName = null; private string fixture3TypeName = null; [SetUp] public override void SetUp() { fixture1 = Mocks.StrictMock<ITestDescriptor>(); fixture2 = Mocks.StrictMock<ITestDescriptor>(); fixture3 = Mocks.StrictMock<ITestDescriptor>(); fixture4 = Mocks.StrictMock<ITestDescriptor>(); ICodeElementInfo codeElement1 = Reflector.Wrap(typeof(SimpleTest)); SetupResult.For(fixture1.CodeElement).Return(codeElement1); fixture1TypeName = codeElement1.Name; ICodeElementInfo codeElement2 = Reflector.Wrap(typeof(ParameterizedTest)); SetupResult.For(fixture2.CodeElement).Return(codeElement2); fixture2TypeName = codeElement2.Name; ICodeElementInfo codeElement3 = Reflector.Wrap(typeof(FixtureInheritanceSample)); SetupResult.For(fixture3.CodeElement).Return(codeElement3); fixture3TypeName = codeElement3.Name; ICodeElementInfo codeElement4 = Reflector.Wrap(typeof(DerivedFixture)); SetupResult.For(fixture4.CodeElement).Return(codeElement4); Mocks.ReplayAll(); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void InstantiateWithNullFactory() { new FilterParser<ITestDescriptor>(null); } [Test] [Row("Exact", false)] [Row("", true)] public void ExactType(string filterType, bool shouldMatch) { string filter = filterType + "Type:" + fixture3TypeName; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsTrue(parsedFilter.IsMatch(fixture3)); Assert.AreEqual(parsedFilter.IsMatch(fixture4), shouldMatch); Assert.AreEqual(parsedFilter.ToString(), "Type(Equality('" + fixture3TypeName + "'), " + (filterType == "Exact" ? "False" : "True") + ")"); } [TearDown] public override void TearDown() { Mocks.VerifyAll(); } [Test] [Row(null, ExpectedException = typeof(FilterParseException))] [Row("", ExpectedException = typeof(FilterParseException))] [Row(" ", ExpectedException = typeof(FilterParseException))] [Row("\t", ExpectedException = typeof(FilterParseException))] [Row("\n \n", ExpectedException = typeof(FilterParseException))] public void AnyFilterIsReturnedForEmptyFilterExpressions(string filter) { FilterUtils.ParseTestFilter(filter); } [Test] public void AnyFilterIsReturnedForStar() { string filter = "*"; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Any()"); Assert.AreSame(parsedFilter.GetType(), typeof(AnyFilter<ITestDescriptor>)); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsTrue(parsedFilter.IsMatch(fixture2)); Assert.IsTrue(parsedFilter.IsMatch(fixture3)); } [Test] [Row("* and * or * and *", "(* and *) or (* and *)", true)] [Row("* or * and * or *", "* or (* and *) or *", true)] [Row("not * or not * and *", "(not *) or ((not *) and *)", false)] public void FilterWithStars(string filter1, string filter2, bool matches) { Filter<ITestDescriptor> parsedFilter1 = FilterUtils.ParseTestFilter(filter1); Assert.IsNotNull(parsedFilter1); Filter<ITestDescriptor> parsedFilter2 = FilterUtils.ParseTestFilter(filter2); Assert.IsNotNull(parsedFilter2); Assert.AreEqual(parsedFilter1.ToString(), parsedFilter2.ToString()); Assert.AreEqual(parsedFilter1.IsMatch(fixture1), matches); Assert.AreEqual(parsedFilter1.IsMatch(fixture2), matches); Assert.AreEqual(parsedFilter1.IsMatch(fixture3), matches); Assert.AreEqual(parsedFilter2.IsMatch(fixture1), matches); Assert.AreEqual(parsedFilter2.IsMatch(fixture2), matches); Assert.AreEqual(parsedFilter2.IsMatch(fixture3), matches); } [Test] [Row("SimpleTest")] [Row("MbUnit.TestResources.SimpleTest")] public void FilterWithOneValue(string type) { string filter = "Type:" + type; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Type(Equality('" + type + "'), True)"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("'SimpleTest'")] [Row("'MbUnit.TestResources.SimpleTest'")] [Row("\"SimpleTest\"")] [Row("\"MbUnit.TestResources.SimpleTest\"")] public void FilterWithQuotedValue(string type) { string filter = "Type:" + type; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Type(Equality('" + type.Substring(1, type.Length - 2) + "'), True)"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("/SimpleTest/", false)] [Row("/MbUnit.TestResources.SimpleTest/", false)] [Row("/simpletest/", true)] [Row("/MBUNIT.TESTRESOURCES.SIMPLETEST/", true)] public void FilterWithRegexValue(string type, bool caseInsensitive) { string filter = "Type:" + type + (caseInsensitive ? "i" : ""); Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Type(Regex('" + type.Substring(1, type.Length - 2) + "', " + (caseInsensitive ? "IgnoreCase, " : "") + "CultureInvariant), True)"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("SimpleTest", "ParameterizedTest")] [Row("MbUnit.TestResources.SimpleTest", "ParameterizedTest")] public void FilterWithTwoValues(string type1, string type2) { string filter = "Type:" + type1 + "," + type2; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Type(Or({ Equality('" + type1 + "'), Equality('" + type2 + "') }), True)"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsTrue(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("SimpleTest", "ParameterizedTest")] [Row("MbUnit.TestResources.SimpleTest", "ParameterizedTest")] public void OrFilter(string type1, string type2) { string filter = "Type:" + type1 + " or Type:" + type2; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "Or({ Type(Equality('" + type1 + "'), True), Type(Equality('" + type2 + "'), True) })"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsTrue(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("SimpleTest", "ParameterizedTest")] [Row("MbUnit.TestResources.SimpleTest", "ParameterizedTest")] public void AndFilter(string type1, string type2) { string filter = "Type:" + type1 + " and Type:" + type2; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "And({ Type(Equality('" + type1 + "'), True), Type(Equality('" + type2 + "'), True) })"); Assert.IsFalse(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("SimpleTest", "ParameterizedTest")] [Row("MbUnit.TestResources.SimpleTest", "ParameterizedTest")] public void NotFilter(string type1, string type2) { string filter = "Type:" + type1 + " and not Type:" + type2; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "And({ Type(Equality('" + type1 + "'), True), Not(Type(Equality('" + type2 + "'), True)) })"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] [Row("Type:\"Fixture1\"")] [Row("Type:\"Fixtur\\\\e1\"")] [Row("Type:'Fixture1'")] [Row("'Type':Fixture1")] [Row("Type:\"Fixture1\",Fixture2")] [Row("Type:\"Fixture1\",\"Fixture2\"")] [Row("Type:\"Fixture1\",'Fixture2'")] [Row("Type:'Fixture1','Fixture2'")] [Row("\"Type\":Fixture1")] [Row("Type:~\"Fixture1\"")] [Row("Type:~'Fixture1'")] [Row("(Type:Fixture1 or Type:Fixture2)")] [Row("Type:foo''")] [Row(@"Type:foo\\")] [Row("Type:foo\'blah")] [Row("(not not Author: Julian)")] public void ValidFiltersTests(string filter) { // Just making sure they are parsed Assert.IsNotNull(FilterUtils.ParseTestFilter(filter)); } [Test] [Row("Type:/RegExp/", "Type(Regex('RegExp', CultureInvariant), True)")] [Row("Type:/RegExp/i", "Type(Regex('RegExp', IgnoreCase, CultureInvariant), True)")] [Row("Type://", "Type(Regex('', CultureInvariant), True)")] [Row("Type://i", "Type(Regex('', IgnoreCase, CultureInvariant), True)")] [Row(@"Abc: /123 456 \/ 789/", @"Metadata('Abc', Regex('123 456 / 789', CultureInvariant))")] [Row(@"Abc: /123 456 \/ 789/i", @"Metadata('Abc', Regex('123 456 / 789', IgnoreCase, CultureInvariant))")] public void RegularExpressions(string filter, string parsedFilterString) { Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), parsedFilterString); } [Test] [Row("", "", Description = "Empty filter set.")] [Row("*", "*")] [Row("include *", "*")] [Row("exclude *", "exclude *")] [Row("include * exclude *", "* exclude *")] [Row("include * exclude Type: foo and Type: bar", "* exclude (Type: foo and Type: bar)")] [Row("Type: foo and Type: bar", "(Type: foo and Type: bar)")] public void FilterSets(string filterSetExpr, string parsedFilterSetString) { FilterSet<ITestDescriptor> parsedFilterSet = FilterUtils.ParseTestFilterSet(filterSetExpr); Assert.IsNotNull(parsedFilterSet); Assert.AreEqual(parsedFilterSetString, parsedFilterSet.ToFilterSetExpr()); } [Test] [Row("foo''", ExpectedException = typeof(FilterParseException))] [Row(@"foo\", ExpectedException = typeof(FilterParseException))] [Row(@"foo\\", ExpectedException = typeof(FilterParseException))] [Row("foo\'blah", ExpectedException = typeof(FilterParseException))] [Row(@"\", ExpectedException = typeof(FilterParseException))] [Row(@"'", ExpectedException = typeof(FilterParseException))] [Row("\"", ExpectedException = typeof(FilterParseException))] [Row("/", ExpectedException = typeof(FilterParseException))] [Row("~'Fixture1'", ExpectedException = typeof(FilterParseException))] [Row("Type:\"", ExpectedException = typeof(FilterParseException))] [Row(@"Type:'", ExpectedException = typeof(FilterParseException))] [Row(@"Type:/", ExpectedException = typeof(FilterParseException))] [Row(@"Type:foo\", ExpectedException = typeof(FilterParseException))] [Row(@"Type:\", ExpectedException = typeof(FilterParseException))] [Row(@"Type:'\", ExpectedException = typeof(FilterParseException))] [Row("Type:\"\\", ExpectedException = typeof(FilterParseException))] [Row("(Author:me", ExpectedException = typeof(FilterParseException))] [Row("(Author:", ExpectedException = typeof(FilterParseException))] [Row("(Author::", ExpectedException = typeof(FilterParseException))] [Row("include", ExpectedException = typeof(FilterParseException))] [Row("include exclude", ExpectedException = typeof(FilterParseException))] [Row("include * exclude", ExpectedException = typeof(FilterParseException))] public void InvalidFilter(string filter) { FilterUtils.ParseTestFilter(filter); } [Test] public void ComplexFilter1() { string filter = "((Type: " + fixture1TypeName + ") or (Type: " + fixture2TypeName + ")) and not Type:" + fixture3TypeName; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "And({ Or({ Type(Equality('" + fixture1TypeName + "'), True), Type(Equality('" + fixture2TypeName + "'), True) }), Not(Type(Equality('" + fixture3TypeName + "'), True)) })"); Assert.IsTrue(parsedFilter.IsMatch(fixture1)); Assert.IsTrue(parsedFilter.IsMatch(fixture2)); Assert.IsFalse(parsedFilter.IsMatch(fixture3)); } [Test] public void ComplexFilter2() { string filter = "not ((Type: " + fixture1TypeName + ") or (Type: " + fixture2TypeName + ")) and Type:" + fixture3TypeName + ""; Filter<ITestDescriptor> parsedFilter = FilterUtils.ParseTestFilter(filter); Assert.IsNotNull(parsedFilter); Assert.AreEqual(parsedFilter.ToString(), "And({ Not(Or({ Type(Equality('" + fixture1TypeName + "'), True), Type(Equality('" + fixture2TypeName + "'), True) })), Type(Equality('" + fixture3TypeName + "'), True) })"); Assert.IsFalse(parsedFilter.IsMatch(fixture1)); Assert.IsFalse(parsedFilter.IsMatch(fixture2)); Assert.IsTrue(parsedFilter.IsMatch(fixture3)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Streams; using Orleans.Configuration; namespace Orleans.Providers { /// <summary> /// Adapter factory for in memory stream provider. /// This factory acts as the adapter and the adapter factory. The events are stored in an in-memory grain that /// behaves as an event queue, this provider adapter is primarily used for testing /// </summary> public class MemoryAdapterFactory<TSerializer> : IQueueAdapterFactory, IQueueAdapter, IQueueAdapterCache where TSerializer : class, IMemoryMessageBodySerializer { private readonly StreamCacheEvictionOptions cacheOptions; private readonly StreamStatisticOptions statisticOptions; private readonly HashRingStreamQueueMapperOptions queueMapperOptions; private readonly IGrainFactory grainFactory; private readonly ITelemetryProducer telemetryProducer; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private readonly TSerializer serializer; private IStreamQueueMapper streamQueueMapper; private ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain> queueGrains; private IObjectPool<FixedSizeBuffer> bufferPool; private BlockPoolMonitorDimensions blockPoolMonitorDimensions; private IStreamFailureHandler streamFailureHandler; private TimePurgePredicate purgePredicate; /// <summary> /// Name of the adapter. Primarily for logging purposes /// </summary> public string Name { get; } /// <summary> /// Determines whether this is a rewindable stream adapter - supports subscribing from previous point in time. /// </summary> /// <returns>True if this is a rewindable stream adapter, false otherwise.</returns> public bool IsRewindable => true; /// <summary> /// Direction of this queue adapter: Read, Write or ReadWrite. /// </summary> /// <returns>The direction in which this adapter provides data.</returns> public StreamProviderDirection Direction => StreamProviderDirection.ReadWrite; /// <summary> /// Creates a failure handler for a partition. /// </summary> protected Func<string, Task<IStreamFailureHandler>> StreamFailureHandlerFactory { get; set; } /// <summary> /// Create a cache monitor to report cache related metrics /// Return a ICacheMonitor /// </summary> protected Func<CacheMonitorDimensions, ITelemetryProducer, ICacheMonitor> CacheMonitorFactory; /// <summary> /// Create a block pool monitor to monitor block pool related metrics /// Return a IBlockPoolMonitor /// </summary> protected Func<BlockPoolMonitorDimensions, ITelemetryProducer, IBlockPoolMonitor> BlockPoolMonitorFactory; /// <summary> /// Create a monitor to monitor QueueAdapterReceiver related metrics /// Return a IQueueAdapterReceiverMonitor /// </summary> protected Func<ReceiverMonitorDimensions, ITelemetryProducer, IQueueAdapterReceiverMonitor> ReceiverMonitorFactory; public MemoryAdapterFactory(string providerName, StreamCacheEvictionOptions cacheOptions, StreamStatisticOptions statisticOptions, HashRingStreamQueueMapperOptions queueMapperOptions, IServiceProvider serviceProvider, IGrainFactory grainFactory, ITelemetryProducer telemetryProducer, ILoggerFactory loggerFactory) { this.Name = providerName; this.queueMapperOptions = queueMapperOptions ?? throw new ArgumentNullException(nameof(queueMapperOptions)); this.cacheOptions = cacheOptions ?? throw new ArgumentNullException(nameof(cacheOptions)); this.statisticOptions = statisticOptions ?? throw new ArgumentException(nameof(statisticOptions)); this.grainFactory = grainFactory ?? throw new ArgumentNullException(nameof(grainFactory)); this.telemetryProducer = telemetryProducer ?? throw new ArgumentNullException(nameof(telemetryProducer)); this.loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); this.logger = loggerFactory.CreateLogger<ILogger<MemoryAdapterFactory<TSerializer>>>(); this.serializer = MemoryMessageBodySerializerFactory<TSerializer>.GetOrCreateSerializer(serviceProvider); } /// <summary> /// Factory initialization. /// </summary> public void Init() { this.queueGrains = new ConcurrentDictionary<QueueId, IMemoryStreamQueueGrain>(); if (CacheMonitorFactory == null) this.CacheMonitorFactory = (dimensions, telemetryProducer) => new DefaultCacheMonitor(dimensions, telemetryProducer); if (this.BlockPoolMonitorFactory == null) this.BlockPoolMonitorFactory = (dimensions, telemetryProducer) => new DefaultBlockPoolMonitor(dimensions, telemetryProducer); if (this.ReceiverMonitorFactory == null) this.ReceiverMonitorFactory = (dimensions, telemetryProducer) => new DefaultQueueAdapterReceiverMonitor(dimensions, telemetryProducer); this.purgePredicate = new TimePurgePredicate(this.cacheOptions.DataMinTimeInCache, this.cacheOptions.DataMaxAgeInCache); this.streamQueueMapper = new HashRingBasedStreamQueueMapper(this.queueMapperOptions, this.Name); } private void CreateBufferPoolIfNotCreatedYet() { if (this.bufferPool == null) { // 1 meg block size pool this.blockPoolMonitorDimensions = new BlockPoolMonitorDimensions($"BlockPool-{Guid.NewGuid()}"); var oneMb = 1 << 20; var objectPoolMonitor = new ObjectPoolMonitorBridge(this.BlockPoolMonitorFactory(blockPoolMonitorDimensions, this.telemetryProducer), oneMb); this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneMb), objectPoolMonitor, this.statisticOptions.StatisticMonitorWriteInterval); } } /// <summary> /// Create queue adapter. /// </summary> /// <returns></returns> public Task<IQueueAdapter> CreateAdapter() { return Task.FromResult<IQueueAdapter>(this); } /// <summary> /// Create queue message cache adapter /// </summary> /// <returns></returns> public IQueueAdapterCache GetQueueAdapterCache() { return this; } /// <summary> /// Create queue mapper /// </summary> /// <returns></returns> public IStreamQueueMapper GetStreamQueueMapper() { return streamQueueMapper; } /// <summary> /// Creates a queue receiver for the specified queueId /// </summary> /// <param name="queueId"></param> /// <returns></returns> public IQueueAdapterReceiver CreateReceiver(QueueId queueId) { var dimensions = new ReceiverMonitorDimensions(queueId.ToString()); var receiverLogger = this.loggerFactory.CreateLogger($"{typeof(MemoryAdapterReceiver<TSerializer>).FullName}.{this.Name}.{queueId}"); var receiverMonitor = this.ReceiverMonitorFactory(dimensions, this.telemetryProducer); IQueueAdapterReceiver receiver = new MemoryAdapterReceiver<TSerializer>(GetQueueGrain(queueId), receiverLogger, this.serializer, receiverMonitor); return receiver; } /// <summary> /// Writes a set of events to the queue as a single batch associated with the provided streamId. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="streamGuid"></param> /// <param name="streamNamespace"></param> /// <param name="events"></param> /// <param name="token"></param> /// <param name="requestContext"></param> /// <returns></returns> public async Task QueueMessageBatchAsync<T>(Guid streamGuid, string streamNamespace, IEnumerable<T> events, StreamSequenceToken token, Dictionary<string, object> requestContext) { try { var queueId = streamQueueMapper.GetQueueForStream(streamGuid, streamNamespace); ArraySegment<byte> bodyBytes = serializer.Serialize(new MemoryMessageBody(events.Cast<object>(), requestContext)); var messageData = MemoryMessageData.Create(streamGuid, streamNamespace, bodyBytes); IMemoryStreamQueueGrain queueGrain = GetQueueGrain(queueId); await queueGrain.Enqueue(messageData); } catch (Exception exc) { logger.Error((int)ProviderErrorCode.MemoryStreamProviderBase_QueueMessageBatchAsync, "Exception thrown in MemoryAdapterFactory.QueueMessageBatchAsync.", exc); throw; } } /// <summary> /// Create a cache for a given queue id /// </summary> /// <param name="queueId"></param> public IQueueCache CreateQueueCache(QueueId queueId) { //move block pool creation from init method to here, to avoid unnecessary block pool creation when stream provider is initialized in client side. CreateBufferPoolIfNotCreatedYet(); var logger = this.loggerFactory.CreateLogger($"{typeof(MemoryPooledCache<TSerializer>).FullName}.{this.Name}.{queueId}"); var monitor = this.CacheMonitorFactory(new CacheMonitorDimensions(queueId.ToString(), this.blockPoolMonitorDimensions.BlockPoolId), this.telemetryProducer); return new MemoryPooledCache<TSerializer>(bufferPool, purgePredicate, logger, this.serializer, monitor, this.statisticOptions.StatisticMonitorWriteInterval); } /// <summary> /// Acquire delivery failure handler for a queue /// </summary> /// <param name="queueId"></param> /// <returns></returns> public Task<IStreamFailureHandler> GetDeliveryFailureHandler(QueueId queueId) { return Task.FromResult(streamFailureHandler ?? (streamFailureHandler = new NoOpStreamDeliveryFailureHandler())); } /// <summary> /// Generate a deterministic Guid from a queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private Guid GenerateDeterministicGuid(QueueId queueId) { // provider name hash code int providerNameGuidHash = (int)JenkinsHash.ComputeHash(this.Name); // get queueId hash code uint queueIdHash = queueId.GetUniformHashCode(); byte[] queIdHashByes = BitConverter.GetBytes(queueIdHash); short s1 = BitConverter.ToInt16(queIdHashByes, 0); short s2 = BitConverter.ToInt16(queIdHashByes, 2); // build guid tailing 8 bytes from providerNameGuidHash and queIdHashByes. var tail = new List<byte>(); tail.AddRange(BitConverter.GetBytes(providerNameGuidHash)); tail.AddRange(queIdHashByes); // make guid. // - First int is provider name hash // - Two shorts from queue Id hash // - 8 byte tail from provider name hash and queue Id hash. return new Guid(providerNameGuidHash, s1, s2, tail.ToArray()); } /// <summary> /// Get a MemoryStreamQueueGrain instance by queue Id. /// </summary> /// <param name="queueId"></param> /// <returns></returns> private IMemoryStreamQueueGrain GetQueueGrain(QueueId queueId) { return queueGrains.GetOrAdd(queueId, grainFactory.GetGrain<IMemoryStreamQueueGrain>(GenerateDeterministicGuid(queueId))); } public static MemoryAdapterFactory<TSerializer> Create(IServiceProvider services, string name) { var cachePurgeOptions = services.GetOptionsByName<StreamCacheEvictionOptions>(name); var statisticOptions = services.GetOptionsByName<StreamStatisticOptions>(name); var queueMapperOptions = services.GetOptionsByName<HashRingStreamQueueMapperOptions>(name); var factory = ActivatorUtilities.CreateInstance<MemoryAdapterFactory<TSerializer>>(services, name, cachePurgeOptions, statisticOptions, queueMapperOptions); factory.Init(); return factory; } } }
/* * Unity VSCode Support * * Seamless support for Microsoft Visual Studio Code in Unity * * Version: * 2.6 * * Authors: * Matthew Davey <matthew.davey@dotbunny.com> */ // REQUIRES: VSCode 0.8.0 - Settings directory moved to .vscode // TODO: Currently VSCode will not debug mono on Windows -- need a solution. namespace dotBunny.Unity { using System; using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; [InitializeOnLoad] public static class VSCode { /// <summary> /// Current Version Number /// </summary> public const float Version = 2.6f; /// <summary> /// Current Version Code /// </summary> public const string VersionCode = "-RELEASE"; /// <summary> /// Download URL for Unity Debbuger /// </summary> public const string UnityDebuggerURL = "https://raw.githubusercontent.com/dotBunny/VSCode-Test/master/Downloads/unity-debug-101.vsix"; #region Properties /// <summary> /// Path to VSCode executable public static string CodePath { get { #if UNITY_EDITOR_OSX var newPath = "/Applications/Visual Studio Code.app"; #elif UNITY_EDITOR_WIN var newPath = ProgramFilesx86() + Path.DirectorySeparatorChar + "Microsoft VS Code" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "code.cmd"; #else var newPath = "/usr/local/bin/code"; #endif return EditorPrefs.GetString("VSCode_CodePath", newPath); } set { EditorPrefs.SetString("VSCode_CodePath", value); } } static string ProgramFilesx86() { if( 8 == IntPtr.Size || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432")))) { return Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } return Environment.GetEnvironmentVariable("ProgramFiles"); } /// <summary> /// Should debug information be displayed in the Unity terminal? /// </summary> public static bool Debug { get { return EditorPrefs.GetBool("VSCode_Debug", false); } set { EditorPrefs.SetBool("VSCode_Debug", value); } } /// <summary> /// Is the Visual Studio Code Integration Enabled? /// </summary> /// <remarks> /// We do not want to automatically turn it on, for in larger projects not everyone is using VSCode /// </remarks> public static bool Enabled { get { return EditorPrefs.GetBool("VSCode_Enabled", false); } set { // When turning the plugin on, we should remove all the previous project files if (!Enabled && value) { ClearProjectFiles(); } EditorPrefs.SetBool("VSCode_Enabled", value); } } public static bool UseUnityDebugger { get { return EditorPrefs.GetBool("VSCode_UseUnityDebugger", false); } set { if ( value != UseUnityDebugger ) { // Set value EditorPrefs.SetBool("VSCode_UseUnityDebugger", value); // Do not write the launch JSON file because the debugger uses its own if ( value ) { WriteLaunchFile = false; } // Update launch file UpdateLaunchFile(); } } } /// <summary> /// Should the launch.json file be written? /// </summary> /// <remarks> /// Useful to disable if someone has their own custom one rigged up /// </remarks> public static bool WriteLaunchFile { get { return EditorPrefs.GetBool("VSCode_WriteLaunchFile", true); } set { EditorPrefs.SetBool("VSCode_WriteLaunchFile", value); } } /// <summary> /// Should the plugin automatically update itself. /// </summary> static bool AutomaticUpdates { get { return EditorPrefs.GetBool("VSCode_AutomaticUpdates", false); } set { EditorPrefs.SetBool("VSCode_AutomaticUpdates", value); } } static float GitHubVersion { get { return EditorPrefs.GetFloat("VSCode_GitHubVersion", Version); } set { EditorPrefs.SetFloat("VSCode_GitHubVersion", value); } } /// <summary> /// When was the last time that the plugin was updated? /// </summary> static DateTime LastUpdate { get { // Feature creation date. DateTime lastTime = new DateTime(2015, 10, 8); if (EditorPrefs.HasKey("VSCode_LastUpdate")) { DateTime.TryParse(EditorPrefs.GetString("VSCode_LastUpdate"), out lastTime); } return lastTime; } set { EditorPrefs.SetString("VSCode_LastUpdate", value.ToString()); } } /// <summary> /// Quick reference to the VSCode launch settings file /// </summary> static string LaunchPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "launch.json"; } } /// <summary> /// The full path to the project /// </summary> static string ProjectPath { get { return System.IO.Path.GetDirectoryName(UnityEngine.Application.dataPath); } } /// <summary> /// Should the script editor be reverted when quiting Unity. /// </summary> /// <remarks> /// Useful for environments where you do not use VSCode for everything. /// </remarks> static bool RevertExternalScriptEditorOnExit { get { return EditorPrefs.GetBool("VSCode_RevertScriptEditorOnExit", true); } set { EditorPrefs.SetBool("VSCode_RevertScriptEditorOnExit", value); } } /// <summary> /// Quick reference to the VSCode settings folder /// </summary> static string SettingsFolder { get { return ProjectPath + System.IO.Path.DirectorySeparatorChar + ".vscode"; } } static string SettingsPath { get { return SettingsFolder + System.IO.Path.DirectorySeparatorChar + "settings.json"; } } static int UpdateTime { get { return EditorPrefs.GetInt("VSCode_UpdateTime", 7); } set { EditorPrefs.SetInt("VSCode_UpdateTime", value); } } #endregion /// <summary> /// Integration Constructor /// </summary> static VSCode() { if (Enabled) { UpdateUnityPreferences(true); UpdateLaunchFile(); // Add Update Check DateTime targetDate = LastUpdate.AddDays(UpdateTime); if (DateTime.Now >= targetDate && AutomaticUpdates) { CheckForUpdate(); } } // Event for when script is reloaded System.AppDomain.CurrentDomain.DomainUnload += System_AppDomain_CurrentDomain_DomainUnload; } static void System_AppDomain_CurrentDomain_DomainUnload(object sender, System.EventArgs e) { if (Enabled && RevertExternalScriptEditorOnExit) { UpdateUnityPreferences(false); } } #region Public Members /// <summary> /// Force Unity To Write Project File /// </summary> /// <remarks> /// Reflection! /// </remarks> public static void SyncSolution() { System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor"); System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); SyncSolution.Invoke(null, null); } /// <summary> /// Update the solution files so that they work with VS Code /// </summary> public static void UpdateSolution() { // No need to process if we are not enabled if (!VSCode.Enabled) { return; } if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Updating Solution & Project Files"); } var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); foreach (var filePath in solutionFiles) { string content = File.ReadAllText(filePath); content = ScrubSolutionContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } foreach (var filePath in projectFiles) { string content = File.ReadAllText(filePath); content = ScrubProjectContent(content); File.WriteAllText(filePath, content); ScrubFile(filePath); } } #endregion #region Private Members /// <summary> /// Call VSCode with arguements /// </summary> static void CallVSCode(string args) { System.Diagnostics.Process proc = new System.Diagnostics.Process(); #if UNITY_EDITOR_OSX proc.StartInfo.FileName = "open"; proc.StartInfo.Arguments = " -n -b \"com.microsoft.VSCode\" --args " + args; proc.StartInfo.UseShellExecute = false; #elif UNITY_EDITOR_WIN proc.StartInfo.FileName = CodePath; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; #else //TODO: Allow for manual path to code? proc.StartInfo.FileName = CodePath; proc.StartInfo.Arguments = args; proc.StartInfo.UseShellExecute = false; #endif proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); } /// <summary> /// Check for Updates with GitHub /// </summary> static void CheckForUpdate() { var fileContent = string.Empty; EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f); // Because were not a runtime framework, lets just use the simplest way of doing this try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs"); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Set the last update time LastUpdate = DateTime.Now; // Fix for oddity in downlo if (fileContent.Substring(0, 2) != "/*") { int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase); // Jump over junk characters fileContent = fileContent.Substring(startPosition); } string[] fileExploded = fileContent.Split('\n'); if (fileExploded.Length > 7) { float github = Version; if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github)) { GitHubVersion = github; } if (github > Version) { var GUIDs = AssetDatabase.FindAssets("t:Script VSCode"); var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/Assets".Length) + System.IO.Path.DirectorySeparatorChar + AssetDatabase.GUIDToAssetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar); if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No")) { // Always make sure the file is writable System.IO.FileInfo fileInfo = new System.IO.FileInfo(path); fileInfo.IsReadOnly = false; // Write update file File.WriteAllText(path, fileContent); // Force update on text file AssetDatabase.ImportAsset(AssetDatabase.GUIDToAssetPath(GUIDs[0]), ImportAssetOptions.ForceUpdate); } } } } /// <summary> /// Clear out any existing project files and lingering stuff that might cause problems /// </summary> static void ClearProjectFiles() { var currentDirectory = Directory.GetCurrentDirectory(); var solutionFiles = Directory.GetFiles(currentDirectory, "*.sln"); var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj"); var unityProjectFiles = Directory.GetFiles(currentDirectory, "*.unityproj"); foreach (string solutionFile in solutionFiles) { File.Delete(solutionFile); } foreach (string projectFile in projectFiles) { File.Delete(projectFile); } foreach (string unityProjectFile in unityProjectFiles) { File.Delete(unityProjectFile); } // Replace with our clean files (only in Unity 5) #if !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7 SyncSolution(); #endif } /// <summary> /// Force Unity Preferences Window To Read From Settings /// </summary> static void FixUnityPreferences() { // I want that window, please and thank you System.Type T = System.Type.GetType("UnityEditor.PreferencesWindow,UnityEditor"); if (EditorWindow.focusedWindow == null) return; // Only run this when the editor window is visible (cause its what screwed us up) if (EditorWindow.focusedWindow.GetType() == T) { var window = EditorWindow.GetWindow(T, true, "Unity Preferences"); if (window == null) { if (Debug) { UnityEngine.Debug.Log("[VSCode] No Preferences Window Found (really?)"); } return; } var invokerType = window.GetType(); var invokerMethod = invokerType.GetMethod("ReadPreferences", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (invokerMethod != null) { invokerMethod.Invoke(window, null); } else if (Debug) { UnityEngine.Debug.Log("[VSCode] No Reflection Method Found For Preferences"); } } // // Get internal integration class // System.Type iT = System.Type.GetType("UnityEditor.VisualStudioIntegration.UnityVSSupport,UnityEditor.VisualStudioIntegration"); // var iinvokerMethod = iT.GetMethod("ScriptEditorChanged", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); // var temp = EditorPrefs.GetString("kScriptsDefaultApp"); // iinvokerMethod.Invoke(null,new object[] { temp } ); } /// <summary> /// Determine what port Unity is listening for on Windows /// </summary> static int GetDebugPort() { #if UNITY_EDITOR_WIN System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "netstat"; process.StartInfo.Arguments = "-a -n -o -p TCP"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { string[] tokens = Regex.Split(line, "\\s+"); if (tokens.Length > 4) { int test = -1; int.TryParse(tokens[5], out test); if (test > 1023) { try { var p = System.Diagnostics.Process.GetProcessById(test); if (p.ProcessName == "Unity") { return test; } } catch { } } } } #else System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "lsof"; process.StartInfo.Arguments = "-c /^Unity$/ -i 4tcp -a"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); // Not thread safe (yet!) string output = process.StandardOutput.ReadToEnd(); string[] lines = output.Split('\n'); process.WaitForExit(); foreach (string line in lines) { int port = -1; if (line.StartsWith("Unity")) { string[] portions = line.Split(new string[] { "TCP *:" }, System.StringSplitOptions.None); if (portions.Length >= 2) { Regex digitsOnly = new Regex(@"[^\d]"); string cleanPort = digitsOnly.Replace(portions[1], ""); if (int.TryParse(cleanPort, out port)) { if (port > -1) { return port; } } } } } #endif return -1; } static void InstallUnityDebugger() { EditorUtility.DisplayProgressBar("VSCode", "Downloading Unity Debugger ...", 0.1f); byte[] fileContent; try { using (var webClient = new System.Net.WebClient()) { fileContent = webClient.DownloadData(UnityDebuggerURL); } } catch (Exception e) { if (Debug) { UnityEngine.Debug.Log("[VSCode] " + e.Message); } // Don't go any further if there is an error return; } finally { EditorUtility.ClearProgressBar(); } // Do we have a file to install? if ( fileContent != null ) { string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".vsix"; File.WriteAllBytes(fileName, fileContent); CallVSCode(fileName); } } // HACK: This is in until Unity can figure out why MD keeps opening even though a different program is selected. [MenuItem("Assets/Open C# Project In Code", false, 1000)] static void MenuOpenProject() { // Force the project files to be sync SyncSolution(); // Load Project CallVSCode("\"" + ProjectPath + "\" -r"); } [MenuItem("Assets/Open C# Project In Code", true, 1000)] static bool ValidateMenuOpenProject() { return Enabled; } /// <summary> /// VS Code Integration Preferences Item /// </summary> /// <remarks> /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off /// </remarks> [PreferenceItem("VSCode")] static void VSCodePreferencesItem() { if (EditorApplication.isCompiling) { EditorGUILayout.HelpBox("Please wait for Unity to finish compiling. \nIf the window doesn't refresh, simply click on the window or move it around to cause a repaint to happen.", MessageType.Warning); return; } EditorGUILayout.BeginVertical(); EditorGUILayout.HelpBox("Support development of this plugin, follow @reapazor and @dotbunny on Twitter.", MessageType.Info); EditorGUI.BeginChangeCheck(); Enabled = EditorGUILayout.Toggle(new GUIContent("Enable Integration", "Should the integration work its magic for you?"), Enabled); #if UNITY_5_3_OR_NEWER CodePath = EditorGUILayout.DelayedTextField(new GUIContent("VS Code Path", "Full path to the Micosoft Visual Studio code executable."), CodePath); #else CodePath = EditorGUILayout.TextField(new GUIContent("VS Code Path", "Full path to the Micosoft Visual Studio code executable."), CodePath); #endif UseUnityDebugger = EditorGUILayout.Toggle(new GUIContent("Use Unity Debugger", "Should the integration integrate with Unity's VSCode Extension (must be installed)."), UseUnityDebugger); EditorGUILayout.Space(); RevertExternalScriptEditorOnExit = EditorGUILayout.Toggle(new GUIContent("Revert Script Editor On Unload", "Should the external script editor setting be reverted to its previous setting on project unload? This is useful if you do not use Code with all your projects."),RevertExternalScriptEditorOnExit); Debug = EditorGUILayout.Toggle(new GUIContent("Output Messages To Console", "Should informational messages be sent to Unity's Console?"), Debug); WriteLaunchFile = EditorGUILayout.Toggle(new GUIContent("Always Write Launch File", "Always write the launch.json settings when entering play mode?"), WriteLaunchFile); EditorGUILayout.Space(); AutomaticUpdates = EditorGUILayout.Toggle(new GUIContent("Automatic Updates", "Should the plugin automatically update itself?"), AutomaticUpdates); UpdateTime = EditorGUILayout.IntSlider(new GUIContent("Update Timer (Days)", "After how many days should updates be checked for?"), UpdateTime, 1, 31); EditorGUILayout.Space(); EditorGUILayout.Space(); if (EditorGUI.EndChangeCheck()) { UpdateUnityPreferences(Enabled); //UnityEditor.PreferencesWindow.Read // TODO: Force Unity To Reload Preferences // This seems to be a hick up / issue if (VSCode.Debug) { if (Enabled) { UnityEngine.Debug.Log("[VSCode] Integration Enabled"); } else { UnityEngine.Debug.Log("[VSCode] Integration Disabled"); } } } if (GUILayout.Button(new GUIContent("Force Update", "Check for updates to the plugin, right NOW!"))) { CheckForUpdate(); EditorGUILayout.EndVertical(); return; } if (GUILayout.Button(new GUIContent("Write Workspace Settings", "Output a default set of workspace settings for VSCode to use, ignoring many different types of files."))) { WriteWorkspaceSettings(); EditorGUILayout.EndVertical(); return; } EditorGUILayout.Space(); if (UseUnityDebugger) { EditorGUILayout.HelpBox("In order for the \"Use Unity Debuggger\" option to function above, you need to have installed the Unity Debugger Extension for Visual Studio Code. You can do this by simply clicking the button below and it will take care of the rest.", MessageType.Warning); if (GUILayout.Button(new GUIContent("Install Unity Debugger", "Install the Unity Debugger Extension into Code"))) { InstallUnityDebugger(); EditorGUILayout.EndVertical(); return; } } GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label( new GUIContent( string.Format("{0:0.00}", Version) + VersionCode, "GitHub's Version @ " + string.Format("{0:0.00}", GitHubVersion))); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } /// <summary> /// Asset Open Callback (from Unity) /// </summary> /// <remarks> /// Called when Unity is about to open an asset. /// </remarks> [UnityEditor.Callbacks.OnOpenAssetAttribute()] static bool OnOpenedAsset(int instanceID, int line) { // bail out if we are not using VSCode if (!Enabled) { return false; } // current path without the asset folder string appPath = ProjectPath; // determine asset that has been double clicked in the project view UnityEngine.Object selected = EditorUtility.InstanceIDToObject(instanceID); if (selected.GetType().ToString() == "UnityEditor.MonoScript" || selected.GetType().ToString() == "UnityEngine.Shader") { string completeFilepath = appPath + Path.DirectorySeparatorChar + AssetDatabase.GetAssetPath(selected); string args = null; if (line == -1) { args = "\"" + ProjectPath + "\" \"" + completeFilepath + "\" -r"; } else { args = "\"" + ProjectPath + "\" -g \"" + completeFilepath + ":" + line.ToString() + "\" -r"; } // call 'open' CallVSCode(args); return true; } // Didnt find a code file? let Unity figure it out return false; } /// <summary> /// Executed when the Editor's playmode changes allowing for capture of required data /// </summary> static void OnPlaymodeStateChanged() { if (UnityEngine.Application.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode) { UpdateLaunchFile(); } } /// <summary> /// Detect when scripts are reloaded and relink playmode detection /// </summary> [UnityEditor.Callbacks.DidReloadScripts()] static void OnScriptReload() { EditorApplication.playmodeStateChanged -= OnPlaymodeStateChanged; EditorApplication.playmodeStateChanged += OnPlaymodeStateChanged; } /// <summary> /// Remove extra/erroneous lines from a file. static void ScrubFile(string path) { string[] lines = File.ReadAllLines(path); System.Collections.Generic.List<string> newLines = new System.Collections.Generic.List<string>(); for (int i = 0; i < lines.Length; i++) { // Check Empty if (string.IsNullOrEmpty(lines[i].Trim()) || lines[i].Trim() == "\t" || lines[i].Trim() == "\t\t") { } else { newLines.Add(lines[i]); } } File.WriteAllLines(path, newLines.ToArray()); } /// <summary> /// Remove extra/erroneous data from project file (content). /// </summary> static string ScrubProjectContent(string content) { if (content.Length == 0) return ""; // Note: it causes OmniSharp faults on Windows, such as "not seeing UnityEngine.UI". 3.5 target works fine #if !UNITY_EDITOR_WIN // Make sure our reference framework is 2.0, still the base for Unity if (content.IndexOf("<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>") != -1) { content = Regex.Replace(content, "<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>", "<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>"); } #endif string targetPath = "";// "<TargetPath>Temp" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "</TargetPath>"; //OutputPath string langVersion = "<LangVersion>default</LangVersion>"; bool found = true; int location = 0; string addedOptions = ""; int startLocation = -1; int endLocation = -1; int endLength = 0; while (found) { startLocation = -1; endLocation = -1; endLength = 0; addedOptions = ""; startLocation = content.IndexOf("<PropertyGroup", location); if (startLocation != -1) { endLocation = content.IndexOf("</PropertyGroup>", startLocation); endLength = (endLocation - startLocation); if (endLocation == -1) { found = false; continue; } else { found = true; location = endLocation; } if (content.Substring(startLocation, endLength).IndexOf("<TargetPath>") == -1) { addedOptions += "\n\r\t" + targetPath + "\n\r"; } if (content.Substring(startLocation, endLength).IndexOf("<LangVersion>") == -1) { addedOptions += "\n\r\t" + langVersion + "\n\r"; } if (!string.IsNullOrEmpty(addedOptions)) { content = content.Substring(0, endLocation) + addedOptions + content.Substring(endLocation); } } else { found = false; } } return content; } /// <summary> /// Remove extra/erroneous data from solution file (content). /// </summary> static string ScrubSolutionContent(string content) { // Replace Solution Version content = content.Replace( "Microsoft Visual Studio Solution File, Format Version 11.00\r\n# Visual Studio 2008\r\n", "\r\nMicrosoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio 2012"); // Remove Solution Properties (Unity Junk) int startIndex = content.IndexOf("GlobalSection(SolutionProperties) = preSolution"); if (startIndex != -1) { int endIndex = content.IndexOf("EndGlobalSection", startIndex); content = content.Substring(0, startIndex) + content.Substring(endIndex + 16); } return content; } /// <summary> /// Update Visual Studio Code Launch file /// </summary> static void UpdateLaunchFile() { if ( !VSCode.Enabled ) return; else if ( VSCode.UseUnityDebugger ) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\": \"0.2.0\",\n\t\"configurations\": [\n\t\t{\n\t\t\t\"name\": \"Unity Editor\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Windows Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"OSX Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Linux Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"iOS Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Android Player\",\n\t\t\t\"type\": \"unity\",\n\t\t\t\"request\": \"launch\"\n\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); } else if (VSCode.WriteLaunchFile) { int port = GetDebugPort(); if (port > -1) { if (!Directory.Exists(VSCode.SettingsFolder)) System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); // Write out proper formatted JSON (hence no more SimpleJSON here) string fileContent = "{\n\t\"version\":\"0.2.0\",\n\t\"configurations\":[ \n\t\t{\n\t\t\t\"name\":\"Unity\",\n\t\t\t\"type\":\"mono\",\n\t\t\t\"request\":\"attach\",\n\t\t\t\"address\":\"localhost\",\n\t\t\t\"port\":" + port + "\n\t\t}\n\t]\n}"; File.WriteAllText(VSCode.LaunchPath, fileContent); if (VSCode.Debug) { UnityEngine.Debug.Log("[VSCode] Debug Port Found (" + port + ")"); } } else { if (VSCode.Debug) { UnityEngine.Debug.LogWarning("[VSCode] Unable to determine debug port."); } } } } /// <summary> /// Update Unity Editor Preferences static void UpdateUnityPreferences(bool enabled) { if (enabled) { // App if (EditorPrefs.GetString("kScriptsDefaultApp") != CodePath) { EditorPrefs.SetString("VSCode_PreviousApp", EditorPrefs.GetString("kScriptsDefaultApp")); } EditorPrefs.SetString("kScriptsDefaultApp", CodePath); // Arguments if (EditorPrefs.GetString("kScriptEditorArgs") != "-r -g \"$(File):$(Line)\"") { EditorPrefs.SetString("VSCode_PreviousArgs", EditorPrefs.GetString("kScriptEditorArgs")); } EditorPrefs.SetString("kScriptEditorArgs", "-r -g \"$(File):$(Line)\""); EditorPrefs.SetString("kScriptEditorArgs" + CodePath, "-r -g \"$(File):$(Line)\""); // MonoDevelop Solution if (EditorPrefs.GetBool("kMonoDevelopSolutionProperties", false)) { EditorPrefs.SetBool("VSCode_PreviousMD", true); } EditorPrefs.SetBool("kMonoDevelopSolutionProperties", false); // Support Unity Proj (JS) if (EditorPrefs.GetBool("kExternalEditorSupportsUnityProj", false)) { EditorPrefs.SetBool("VSCode_PreviousUnityProj", true); } EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", false); if (!EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", false)) { EditorPrefs.SetBool("VSCode_PreviousAttach", false); } EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true); } else { // Restore previous app if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousApp"))) { EditorPrefs.SetString("kScriptsDefaultApp", EditorPrefs.GetString("VSCode_PreviousApp")); } // Restore previous args if (!string.IsNullOrEmpty(EditorPrefs.GetString("VSCode_PreviousArgs"))) { EditorPrefs.SetString("kScriptEditorArgs", EditorPrefs.GetString("VSCode_PreviousArgs")); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousMD", false)) { EditorPrefs.SetBool("kMonoDevelopSolutionProperties", true); } // Restore MD setting if (EditorPrefs.GetBool("VSCode_PreviousUnityProj", false)) { EditorPrefs.SetBool("kExternalEditorSupportsUnityProj", true); } // Always leave editor attaching on, I know, it solves the problem of needing to restart for this // to actually work EditorPrefs.SetBool("AllowAttachedDebuggingOfEditor", true); } FixUnityPreferences(); } /// <summary> /// Write Default Workspace Settings /// </summary> static void WriteWorkspaceSettings() { if (Debug) { UnityEngine.Debug.Log("[VSCode] Workspace Settings Written"); } if (!Directory.Exists(VSCode.SettingsFolder)) { System.IO.Directory.CreateDirectory(VSCode.SettingsFolder); } string exclusions = "{\n" + "\t\"files.exclude\":\n" + "\t{\n" + // Hidden Files "\t\t\"**/.DS_Store\":true,\n" + "\t\t\"**/.git\":true,\n" + "\t\t\"**/.gitignore\":true,\n" + "\t\t\"**/.gitattributes\":true,\n" + "\t\t\"**/.gitmodules\":true,\n" + "\t\t\"**/.svn\":true,\n" + // Project Files "\t\t\"**/*.booproj\":true,\n" + "\t\t\"**/*.pidb\":true,\n" + "\t\t\"**/*.suo\":true,\n" + "\t\t\"**/*.user\":true,\n" + "\t\t\"**/*.userprefs\":true,\n" + "\t\t\"**/*.unityproj\":true,\n" + "\t\t\"**/*.dll\":true,\n" + "\t\t\"**/*.exe\":true,\n" + // Media Files "\t\t\"**/*.pdf\":true,\n" + // Audio "\t\t\"**/*.mid\":true,\n" + "\t\t\"**/*.midi\":true,\n" + "\t\t\"**/*.wav\":true,\n" + // Textures "\t\t\"**/*.gif\":true,\n" + "\t\t\"**/*.ico\":true,\n" + "\t\t\"**/*.jpg\":true,\n" + "\t\t\"**/*.jpeg\":true,\n" + "\t\t\"**/*.png\":true,\n" + "\t\t\"**/*.psd\":true,\n" + "\t\t\"**/*.tga\":true,\n" + "\t\t\"**/*.tif\":true,\n" + "\t\t\"**/*.tiff\":true,\n" + // Models "\t\t\"**/*.3ds\":true,\n" + "\t\t\"**/*.3DS\":true,\n" + "\t\t\"**/*.fbx\":true,\n" + "\t\t\"**/*.FBX\":true,\n" + "\t\t\"**/*.lxo\":true,\n" + "\t\t\"**/*.LXO\":true,\n" + "\t\t\"**/*.ma\":true,\n" + "\t\t\"**/*.MA\":true,\n" + "\t\t\"**/*.obj\":true,\n" + "\t\t\"**/*.OBJ\":true,\n" + // Unity File Types "\t\t\"**/*.asset\":true,\n" + "\t\t\"**/*.cubemap\":true,\n" + "\t\t\"**/*.flare\":true,\n" + "\t\t\"**/*.mat\":true,\n" + "\t\t\"**/*.meta\":true,\n" + "\t\t\"**/*.prefab\":true,\n" + "\t\t\"**/*.unity\":true,\n" + // Folders "\t\t\"build/\":true,\n" + "\t\t\"Build/\":true,\n" + "\t\t\"Library/\":true,\n" + "\t\t\"library/\":true,\n" + "\t\t\"obj/\":true,\n" + "\t\t\"Obj/\":true,\n" + "\t\t\"ProjectSettings/\":true,\r" + "\t\t\"temp/\":true,\n" + "\t\t\"Temp/\":true\n" + "\t}\n" + "}"; // Dont like the replace but it fixes the issue with the JSON File.WriteAllText(VSCode.SettingsPath, exclusions); } #endregion } /// <summary> /// VSCode Asset AssetPostprocessor /// <para>This will ensure any time that the project files are generated the VSCode versions will be made</para> /// </summary> /// <remarks>Undocumented Event</remarks> public class VSCodeAssetPostprocessor : AssetPostprocessor { /// <summary> /// On documented, project generation event callback /// </summary> private static void OnGeneratedCSProjectFiles() { // Force execution of VSCode update VSCode.UpdateSolution(); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.ServiceProcess; using System.Management; using System.Timers; using System.Text; using Microsoft.Win32; namespace WebsitePanel.VmConfig { public partial class VmConfigService : ServiceBase { internal const string RegistryInputKey = "SOFTWARE\\Microsoft\\Virtual Machine\\External"; internal const string RegistryOutputKey = "SOFTWARE\\Microsoft\\Virtual Machine\\Guest"; internal const string TaskPrefix = "WSP-"; internal const string CurrentTaskName = "WSP-CurrentTask"; internal const string RAM_SUMMARY_KEY = "VM-RAM-Summary"; internal const string HDD_SUMMARY_KEY = "VM-HDD-Summary"; private Dictionary<string, string> provisioningModules; private Timer idleTimer; private Timer pollTimer; private Timer summaryTimer; private bool rebootRequired = false; private System.Threading.Thread mainThread; public VmConfigService() { InitializeComponent(); } protected override void OnStart(string[] args) { //start main procedure in separate thread mainThread = new System.Threading.Thread(new System.Threading.ThreadStart(Start)); mainThread.Start(); } private void Start() { //log ServiceLog.WriteApplicationStart(); // delay (for sync with KVP exchange service) DelayOnStart(); //init InitializeProvisioningModules(); InitializeTimers(); // start timer StartSummaryTimer(); //run tasks ProcessTasks(); } protected override void OnStop() { if (this.mainThread.IsAlive) { this.mainThread.Abort(); } this.mainThread.Join(); ServiceLog.WriteApplicationStop(); } private void DelayOnStart() { int startupDelay = 0; if (Int32.TryParse(ConfigurationManager.AppSettings["Service.StartupDelay"], out startupDelay) && startupDelay > 0) { ServiceLog.WriteStart("Delay on service start-up"); System.Threading.Thread.Sleep(startupDelay); ServiceLog.WriteEnd("Delay on service start-up"); } } private void DeleteOldResults() { // get the list of input tasks string[] strTasks = RegistryUtils.GetRegistryKeyValueNames(RegistryInputKey); List<string> tasks = new List<string>(); foreach (string strTask in strTasks) { if (!string.IsNullOrEmpty(strTask) && strTask.StartsWith(TaskPrefix) && strTask != CurrentTaskName) { //save only WebsitePanel tasks tasks.Add(strTask); } } // get the list of task results int deletedResults = 0; string[] strResults = RegistryUtils.GetRegistryKeyValueNames(RegistryOutputKey); foreach (string strResult in strResults) { if (!string.IsNullOrEmpty(strResult) && strResult.StartsWith(TaskPrefix) && strResult != CurrentTaskName) { // check if task result exists in the input tasks if (!tasks.Contains(strResult)) { DeleteRegistryKeyValue(RegistryOutputKey, strResult); ServiceLog.WriteInfo(string.Format("Deleted activity result: {0}", strResult)); deletedResults++; } } } if(deletedResults > 0) ServiceLog.WriteEnd(string.Format("{0} result(s) deleted", deletedResults)); } private void InitializeProvisioningModules() { ServiceLog.WriteStart("Loading provisioning modules..."); provisioningModules = new Dictionary<string, string>(); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ModuleSettingsSection section = config.Sections["moduleSettings"] as ModuleSettingsSection; if ( section != null) { foreach (string key in section.Modules.AllKeys) { provisioningModules.Add(key, section.Modules[key].Value); } } else ServiceLog.WriteError("Modules configuration section not found"); ServiceLog.WriteEnd(string.Format("{0} module(s) loaded", provisioningModules.Count)); } private void InitializeTimers() { // idle timer idleTimer = new Timer(); idleTimer.AutoReset = false; double idleInterval; if (!Double.TryParse(ConfigurationManager.AppSettings["Service.ExitIdleInterval"], out idleInterval)) { ServiceLog.WriteError("Invalid configuration parameter: Service.ExitIdleInterval"); idleInterval = 600000; } idleTimer.Interval = idleInterval; idleTimer.Enabled = false; idleTimer.Elapsed += new ElapsedEventHandler(OnIdleTimerElapsed); // poll timer pollTimer = new Timer(); pollTimer.AutoReset = false; double pollInterval; if (!Double.TryParse(ConfigurationManager.AppSettings["Service.RegistryPollInterval"], out pollInterval)) { ServiceLog.WriteError("Invalid configuration parameter: Service.RegistryPollInterval"); pollInterval = 60000; } pollTimer.Interval = pollInterval; pollTimer.Enabled = false; pollTimer.Elapsed += new ElapsedEventHandler(OnPollTimerElapsed); // system symmary timer summaryTimer = new Timer(); double summaryInterval; if (!Double.TryParse(ConfigurationManager.AppSettings["Service.SystemSummaryInterval"], out summaryInterval)) { ServiceLog.WriteError("Invalid configuration parameter: Service.SystemSummaryInterval"); summaryInterval = 15000; } summaryTimer.Interval = summaryInterval; summaryTimer.Enabled = false; summaryTimer.Elapsed += new ElapsedEventHandler(OnSummaryTimerElapsed); } private void OnIdleTimerElapsed(object sender, ElapsedEventArgs e) { base.Stop(); } private void OnPollTimerElapsed(object sender, ElapsedEventArgs e) { ProcessTasks(); } private void OnSummaryTimerElapsed(object sender, ElapsedEventArgs e) { GetSystemSummary(); } private void GetSystemSummary() { const UInt64 Size1KB = 0x400; const UInt64 Size1GB = 0x40000000; // check free/total RAM WmiUtils wmi = new WmiUtils("root\\cimv2"); ManagementObjectCollection objOses = wmi.ExecuteQuery("SELECT * FROM Win32_OperatingSystem"); foreach (ManagementObject objOs in objOses) { UInt64 freeRam = Convert.ToUInt64(objOs["FreePhysicalMemory"]) / Size1KB; UInt64 totalRam = Convert.ToUInt64(objOs["TotalVisibleMemorySize"]) / Size1KB; // write to the registry RegistryUtils.SetRegistryKeyStringValue(RegistryOutputKey, RAM_SUMMARY_KEY, String.Format("{0}:{1}", freeRam, totalRam)); objOs.Dispose(); } // check local HDD logical drives ManagementObjectCollection objDisks = wmi.ExecuteQuery("SELECT * FROM Win32_LogicalDisk WHERE DriveType = 3"); StringBuilder sb = new StringBuilder(); bool first = true; foreach (ManagementObject objDisk in objDisks) { if(!first) sb.Append(";"); sb.Append(objDisk["DeviceID"]); sb.Append(Convert.ToInt32(Convert.ToDouble(objDisk["FreeSpace"]) / (double)Size1GB)).Append(":"); sb.Append(Convert.ToInt32(Convert.ToDouble(objDisk["Size"]) / (double)Size1GB)); first = false; objDisk.Dispose(); } // write HDD info RegistryUtils.SetRegistryKeyStringValue(RegistryOutputKey, HDD_SUMMARY_KEY, sb.ToString()); // dispose resources objOses.Dispose(); objDisks.Dispose(); } private void ProcessTasks() { // delete old results DeleteOldResults(); //process all tasks while (true) { //load completed tasks results string[] strResults = RegistryUtils.GetRegistryKeyValueNames(RegistryOutputKey); List<string> results = new List<string>(); foreach (string strResult in strResults) { if (!string.IsNullOrEmpty(strResult) && strResult.StartsWith(TaskPrefix) && strResult != CurrentTaskName) { //save only WebsitePanel tasks results.Add(strResult); } } // sorted list of tasks - will be sorted by the TaskID (time in ticks) SortedList<long, string> tasks = new SortedList<long, string>(); //load task definitions from input registry key string[] strTasks = RegistryUtils.GetRegistryKeyValueNames(RegistryInputKey); foreach (string strTask in strTasks) { if (results.Contains(strTask)) continue; // skip completed tasks if (!string.IsNullOrEmpty(strTask) && strTask.StartsWith(TaskPrefix)) { // extract Task ID parameter int idx = strTask.LastIndexOf('-'); if(idx == -1) continue; string strTaskId = strTask.Substring(idx + 1); long taskId = 0; try { taskId = Int64.Parse(strTaskId); } catch { continue; // wrong task format } //save only WebsitePanel tasks if(!tasks.ContainsKey(taskId)) tasks.Add(taskId, strTask); } } if (tasks.Count == 0) { if (rebootRequired) { ServiceLog.WriteInfo("Reboot required"); RebootSystem(); return; } //start timers StartPollTimer(); //starts task processing after poll interval StartIdleTimer(); //stops service if idle //no tasks - exit! return; } else { //stop idle timer as we need to process tasks StopIdleTimer(); } ExecutionContext context = null; foreach (long tid in tasks.Keys) { //find first correct task string taskDefinition = tasks[tid]; string taskParameters = RegistryUtils.GetRegistryKeyStringValue(RegistryInputKey, taskDefinition); if (taskDefinition.LastIndexOf("-") == -1 || taskDefinition.LastIndexOf('-') == taskDefinition.Length - 1) { ServiceLog.WriteError(string.Format("Task was deleted from queue as its definition is invalid : {0}", taskDefinition)); DeleteRegistryKeyValue(RegistryInputKey, taskDefinition); //go to next task continue; } string taskName = taskDefinition.Substring(0, taskDefinition.LastIndexOf("-")).Substring(TaskPrefix.Length); string taskId = taskDefinition.Substring(taskDefinition.LastIndexOf('-') + 1); if (!provisioningModules.ContainsKey(taskName)) { ServiceLog.WriteError(string.Format("Task was deleted from queue as its definition was not found : {0}", taskName)); DeleteRegistryKeyValue(RegistryInputKey, taskDefinition); //go to next task continue; } //prepare execution context for correct task context = new ExecutionContext(); context.ActivityID = taskId; context.ActivityName = taskName; ParseParameters(context.Parameters, taskParameters); context.ActivityDefinition = taskDefinition; break; } if (context != null) { string type = provisioningModules[context.ActivityName]; ExecutionResult res = null; DateTime start = DateTime.Now; try { //load module and run task ServiceLog.WriteStart(string.Format("Starting '{0}' module...", context.ActivityName)); context.Progress = 0; res = ModuleLoader.Run(type, ref context); context.Progress = 100; ServiceLog.WriteEnd(string.Format("'{0}' module finished.", context.ActivityName)); } catch (Exception ex) { ServiceLog.WriteError("Unhandled exception:", ex); res = new ExecutionResult(); res.ResultCode = -1; res.ErrorMessage = string.Format("Unhandled exception : {0}", ex); } DateTime end = DateTime.Now; SaveExecutionResult(context.ActivityDefinition, res, start, end); //DeleteRegistryKeyValue(RegistryInputKey, context.ActivityDefinition); if (res.RebootRequired) rebootRequired = true; } } } private void ParseParameters(Dictionary<string, string> dictionary, string parameters) { if (dictionary == null) throw new ArgumentNullException("dictionary"); if (string.IsNullOrEmpty(parameters)) return; string[] pairs = parameters.Split('|'); foreach (string pair in pairs) { string[] parts = pair.Split(new char[] { '=' }, 2); if (parts.Length != 2) continue; if (!dictionary.ContainsKey(parts[0])) dictionary.Add(parts[0], parts[1]); } } private void DeleteRegistryKeyValue(string key, string valueName) { try { RegistryUtils.DeleteRegistryKeyValue(key, valueName); } catch (Exception ex) { ServiceLog.WriteError("Registry error:", ex); } } private void SaveExecutionResult(string name, ExecutionResult res, DateTime started, DateTime ended) { StringBuilder builder = new StringBuilder(); builder.AppendFormat("ResultCode={0}|", res.ResultCode); builder.AppendFormat("RebootRequired={0}|", res.RebootRequired); builder.AppendFormat("ErrorMessage={0}|", res.ErrorMessage); builder.AppendFormat("Value={0}|", res.Value); builder.AppendFormat("Started={0}|", started.ToString("yyyyMMddHHmmss")); builder.AppendFormat("Ended={0}", started.ToString("yyyyMMddHHmmss")); RegistryUtils.SetRegistryKeyStringValue(RegistryOutputKey, name, builder.ToString()); } private void StopIdleTimer() { idleTimer.Stop(); } private void StartIdleTimer() { if ( idleTimer.Interval > 1 ) idleTimer.Start(); } private void StartPollTimer() { if ( pollTimer.Interval > 1 ) pollTimer.Start(); } private void StartSummaryTimer() { if (summaryTimer.Interval > 1) summaryTimer.Start(); } private void RebootSystem() { try { ServiceLog.WriteStart("RebootSystem"); WmiUtils wmi = new WmiUtils("root\\cimv2"); ManagementObjectCollection objOses = wmi.ExecuteQuery("SELECT * FROM Win32_OperatingSystem"); foreach (ManagementObject objOs in objOses) { objOs.Scope.Options.EnablePrivileges = true; objOs.InvokeMethod("Reboot", null); } ServiceLog.WriteEnd("RebootSystem"); } catch (Exception ex) { ServiceLog.WriteError("Reboot System error:", ex); } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.Diagnostics; using System.Globalization; using System.ComponentModel; #if GDI using System.Drawing; #endif #if WPF using WpfColor = System.Windows.Media.Color; #endif #if UWP using UwpColor = Windows.UI.Color; #endif // ReSharper disable RedundantNameQualifier namespace PdfSharp.Drawing { ///<summary> /// Represents a RGB, CMYK, or gray scale color. /// </summary> [DebuggerDisplay("clr=(A={A}, R={R}, G={G}, B={B} C={C}, M={M}, Y={Y}, K={K})")] public struct XColor { XColor(uint argb) { _cs = XColorSpace.Rgb; _a = (byte)((argb >> 24) & 0xff) / 255f; _r = (byte)((argb >> 16) & 0xff); _g = (byte)((argb >> 8) & 0xff); _b = (byte)(argb & 0xff); _c = 0; _m = 0; _y = 0; _k = 0; _gs = 0; RgbChanged(); //_cs.GetType(); // Suppress warning } XColor(byte alpha, byte red, byte green, byte blue) { _cs = XColorSpace.Rgb; _a = alpha / 255f; _r = red; _g = green; _b = blue; _c = 0; _m = 0; _y = 0; _k = 0; _gs = 0; RgbChanged(); //_cs.GetType(); // Suppress warning } XColor(double alpha, double cyan, double magenta, double yellow, double black) { _cs = XColorSpace.Cmyk; _a = (float)(alpha > 1 ? 1 : (alpha < 0 ? 0 : alpha)); _c = (float)(cyan > 1 ? 1 : (cyan < 0 ? 0 : cyan)); _m = (float)(magenta > 1 ? 1 : (magenta < 0 ? 0 : magenta)); _y = (float)(yellow > 1 ? 1 : (yellow < 0 ? 0 : yellow)); _k = (float)(black > 1 ? 1 : (black < 0 ? 0 : black)); _r = 0; _g = 0; _b = 0; _gs = 0f; CmykChanged(); } XColor(double cyan, double magenta, double yellow, double black) : this(1.0, cyan, magenta, yellow, black) { } XColor(double gray) { _cs = XColorSpace.GrayScale; if (gray < 0) _gs = 0; else if (gray > 1) _gs = 1; _gs = (float)gray; _a = 1; _r = 0; _g = 0; _b = 0; _c = 0; _m = 0; _y = 0; _k = 0; GrayChanged(); } #if GDI XColor(System.Drawing.Color color) : this(color.A, color.R, color.G, color.B) { } #endif #if WPF XColor(WpfColor color) : this(color.A, color.R, color.G, color.B) { } #endif #if GDI XColor(KnownColor knownColor) : this(System.Drawing.Color.FromKnownColor(knownColor)) { } #endif #if UWP XColor(UwpColor color) : this(color.A, color.R, color.G, color.B) { } #endif internal XColor(XKnownColor knownColor) : this(XKnownColorTable.KnownColorToArgb(knownColor)) { } /// <summary> /// Creates an XColor structure from a 32-bit ARGB value. /// </summary> public static XColor FromArgb(int argb) { return new XColor((byte)(argb >> 24), (byte)(argb >> 16), (byte)(argb >> 8), (byte)(argb)); } /// <summary> /// Creates an XColor structure from a 32-bit ARGB value. /// </summary> public static XColor FromArgb(uint argb) { return new XColor((byte)(argb >> 24), (byte)(argb >> 16), (byte)(argb >> 8), (byte)(argb)); } // from System.Drawing.Color //public static XColor FromArgb(int alpha, Color baseColor); //public static XColor FromArgb(int red, int green, int blue); //public static XColor FromArgb(int alpha, int red, int green, int blue); //public static XColor FromKnownColor(KnownColor color); //public static XColor FromName(string name); /// <summary> /// Creates an XColor structure from the specified 8-bit color values (red, green, and blue). /// The alpha value is implicitly 255 (fully opaque). /// </summary> public static XColor FromArgb(int red, int green, int blue) { CheckByte(red, "red"); CheckByte(green, "green"); CheckByte(blue, "blue"); return new XColor(255, (byte)red, (byte)green, (byte)blue); } /// <summary> /// Creates an XColor structure from the four ARGB component (alpha, red, green, and blue) values. /// </summary> public static XColor FromArgb(int alpha, int red, int green, int blue) { CheckByte(alpha, "alpha"); CheckByte(red, "red"); CheckByte(green, "green"); CheckByte(blue, "blue"); return new XColor((byte)alpha, (byte)red, (byte)green, (byte)blue); } #if GDI /// <summary> /// Creates an XColor structure from the specified System.Drawing.Color. /// </summary> public static XColor FromArgb(System.Drawing.Color color) { return new XColor(color); } #endif #if WPF /// <summary> /// Creates an XColor structure from the specified System.Drawing.Color. /// </summary> public static XColor FromArgb(WpfColor color) { return new XColor(color); } #endif #if UWP /// <summary> /// Creates an XColor structure from the specified Windows.UI.Color. /// </summary> public static XColor FromArgb(UwpColor color) { return new XColor(color); } #endif /// <summary> /// Creates an XColor structure from the specified alpha value and color. /// </summary> public static XColor FromArgb(int alpha, XColor color) { color.A = ((byte)alpha) / 255.0; return color; } #if GDI /// <summary> /// Creates an XColor structure from the specified alpha value and color. /// </summary> public static XColor FromArgb(int alpha, System.Drawing.Color color) { // Cast required to use correct constructor. return new XColor((byte)alpha, color.R, color.G, color.B); } #endif #if WPF /// <summary> /// Creates an XColor structure from the specified alpha value and color. /// </summary> public static XColor FromArgb(int alpha, WpfColor color) { // Cast required to use correct constructor. return new XColor((byte)alpha, color.R, color.G, color.B); } #endif #if UWP /// <summary> /// Creates an XColor structure from the specified alpha value and color. /// </summary> public static XColor FromArgb(int alpha, UwpColor color) { // Cast required to use correct constructor. return new XColor((byte)alpha, color.R, color.G, color.B); } #endif /// <summary> /// Creates an XColor structure from the specified CMYK values. /// </summary> public static XColor FromCmyk(double cyan, double magenta, double yellow, double black) { return new XColor(cyan, magenta, yellow, black); } /// <summary> /// Creates an XColor structure from the specified CMYK values. /// </summary> public static XColor FromCmyk(double alpha, double cyan, double magenta, double yellow, double black) { return new XColor(alpha, cyan, magenta, yellow, black); } /// <summary> /// Creates an XColor structure from the specified gray value. /// </summary> public static XColor FromGrayScale(double grayScale) { return new XColor(grayScale); } /// <summary> /// Creates an XColor from the specified pre-defined color. /// </summary> public static XColor FromKnownColor(XKnownColor color) { return new XColor(color); } #if GDI /// <summary> /// Creates an XColor from the specified pre-defined color. /// </summary> public static XColor FromKnownColor(KnownColor color) { return new XColor(color); } #endif /// <summary> /// Creates an XColor from the specified name of a pre-defined color. /// </summary> public static XColor FromName(string name) { #if GDI // The implementation in System.Drawing.dll is interesting. It uses a ColorConverter // with hash tables, locking mechanisms etc. I'm not sure what problems that solves. // So I don't use the source, but the reflection. try { return new XColor((KnownColor)Enum.Parse(typeof(KnownColor), name, true)); } // ReSharper disable EmptyGeneralCatchClause catch { } // ReSharper restore EmptyGeneralCatchClause #endif return Empty; } /// <summary> /// Gets or sets the color space to be used for PDF generation. /// </summary> public XColorSpace ColorSpace { get { return _cs; } set { if (!Enum.IsDefined(typeof(XColorSpace), value)) throw new InvalidEnumArgumentException("value", (int)value, typeof(XColorSpace)); _cs = value; } } /// <summary> /// Indicates whether this XColor structure is uninitialized. /// </summary> public bool IsEmpty { get { return this == Empty; } } #if GDI #if UseGdiObjects /// <summary> /// Implicit conversion from Color to XColor /// </summary> public static implicit operator XColor(Color color) { return new XColor(color); } #endif ///<summary> /// Creates a System.Drawing.Color object from this color. /// </summary> public System.Drawing.Color ToGdiColor() { return System.Drawing.Color.FromArgb((int)(_a * 255), _r, _g, _b); } #endif #if WPF ///<summary> /// Creates a WpfColor object from this color. /// </summary> public WpfColor ToWpfColor() { return WpfColor.FromArgb((byte)(_a * 255), _r, _g, _b); } #endif #if UWP ///<summary> /// Creates a Windows.UI.Color object from this color. /// </summary> public UwpColor ToUwpColor() { return UwpColor.FromArgb((byte)(_a * 255), _r, _g, _b); } #endif /// <summary> /// Determines whether the specified object is a Color structure and is equivalent to this /// Color structure. /// </summary> public override bool Equals(object obj) { // ReSharper disable CompareOfFloatsByEqualityOperator if (obj is XColor) { XColor color = (XColor)obj; if (_r == color._r && _g == color._g && _b == color._b && _c == color._c && _m == color._m && _y == color._y && _k == color._k && _gs == color._gs) { return _a == color._a; } } return false; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Returns the hash code for this instance. /// </summary> public override int GetHashCode() { // ReSharper disable NonReadonlyFieldInGetHashCode return ((byte)(_a * 255)) ^ _r ^ _g ^ _b; // ReSharper restore NonReadonlyFieldInGetHashCode } /// <summary> /// Determines whether two colors are equal. /// </summary> public static bool operator ==(XColor left, XColor right) { // ReSharper disable CompareOfFloatsByEqualityOperator if (left._r == right._r && left._g == right._g && left._b == right._b && left._c == right._c && left._m == right._m && left._y == right._y && left._k == right._k && left._gs == right._gs) { return left._a == right._a; } return false; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Determines whether two colors are not equal. /// </summary> public static bool operator !=(XColor left, XColor right) { return !(left == right); } /// <summary> /// Gets a value indicating whether this color is a known color. /// </summary> public bool IsKnownColor { get { return XKnownColorTable.IsKnownColor(Argb); } } /// <summary> /// Gets the hue-saturation-brightness (HSB) hue value, in degrees, for this color. /// </summary> /// <returns>The hue, in degrees, of this color. The hue is measured in degrees, ranging from 0 through 360, in HSB color space.</returns> public double GetHue() { // ReSharper disable CompareOfFloatsByEqualityOperator if ((_r == _g) && (_g == _b)) return 0; double value1 = _r / 255.0; double value2 = _g / 255.0; double value3 = _b / 255.0; double value7 = 0; double value4 = value1; double value5 = value1; if (value2 > value4) value4 = value2; if (value3 > value4) value4 = value3; if (value2 < value5) value5 = value2; if (value3 < value5) value5 = value3; double value6 = value4 - value5; if (value1 == value4) value7 = (value2 - value3) / value6; else if (value2 == value4) value7 = 2f + ((value3 - value1) / value6); else if (value3 == value4) value7 = 4f + ((value1 - value2) / value6); value7 *= 60; if (value7 < 0) value7 += 360; return value7; // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Gets the hue-saturation-brightness (HSB) saturation value for this color. /// </summary> /// <returns>The saturation of this color. The saturation ranges from 0 through 1, where 0 is grayscale and 1 is the most saturated.</returns> public double GetSaturation() { // ReSharper disable CompareOfFloatsByEqualityOperator double value1 = _r / 255.0; double value2 = _g / 255.0; double value3 = _b / 255.0; double value7 = 0; double value4 = value1; double value5 = value1; if (value2 > value4) value4 = value2; if (value3 > value4) value4 = value3; if (value2 < value5) value5 = value2; if (value3 < value5) value5 = value3; if (value4 == value5) return value7; double value6 = (value4 + value5) / 2; if (value6 <= 0.5) return (value4 - value5) / (value4 + value5); return (value4 - value5) / ((2f - value4) - value5); // ReSharper restore CompareOfFloatsByEqualityOperator } /// <summary> /// Gets the hue-saturation-brightness (HSB) brightness value for this color. /// </summary> /// <returns>The brightness of this color. The brightness ranges from 0 through 1, where 0 represents black and 1 represents white.</returns> public double GetBrightness() { double value1 = _r / 255.0; double value2 = _g / 255.0; double value3 = _b / 255.0; double value4 = value1; double value5 = value1; if (value2 > value4) value4 = value2; if (value3 > value4) value4 = value3; if (value2 < value5) value5 = value2; if (value3 < value5) value5 = value3; return (value4 + value5) / 2; } ///<summary> /// One of the RGB values changed; recalculate other color representations. /// </summary> void RgbChanged() { // ReSharper disable LocalVariableHidesMember _cs = XColorSpace.Rgb; int c = 255 - _r; int m = 255 - _g; int y = 255 - _b; int k = Math.Min(c, Math.Min(m, y)); if (k == 255) _c = _m = _y = 0; else { float black = 255f - k; _c = (c - k) / black; _m = (m - k) / black; _y = (y - k) / black; } _k = _gs = k / 255f; // ReSharper restore LocalVariableHidesMember } ///<summary> /// One of the CMYK values changed; recalculate other color representations. /// </summary> void CmykChanged() { _cs = XColorSpace.Cmyk; float black = _k * 255; float factor = 255f - black; _r = (byte)(255 - Math.Min(255f, _c * factor + black)); _g = (byte)(255 - Math.Min(255f, _m * factor + black)); _b = (byte)(255 - Math.Min(255f, _y * factor + black)); _gs = (float)(1 - Math.Min(1.0, 0.3f * _c + 0.59f * _m + 0.11 * _y + _k)); } ///<summary> /// The gray scale value changed; recalculate other color representations. /// </summary> void GrayChanged() { _cs = XColorSpace.GrayScale; _r = (byte)(_gs * 255); _g = (byte)(_gs * 255); _b = (byte)(_gs * 255); _c = 0; _m = 0; _y = 0; _k = 1 - _gs; } // Properties /// <summary> /// Gets or sets the alpha value the specifies the transparency. /// The value is in the range from 1 (opaque) to 0 (completely transparent). /// </summary> public double A { get { return _a; } set { if (value < 0) _a = 0; else if (value > 1) _a = 1; else _a = (float)value; } } /// <summary> /// Gets or sets the red value. /// </summary> public byte R { get { return _r; } set { _r = value; RgbChanged(); } } /// <summary> /// Gets or sets the green value. /// </summary> public byte G { get { return _g; } set { _g = value; RgbChanged(); } } /// <summary> /// Gets or sets the blue value. /// </summary> public byte B { get { return _b; } set { _b = value; RgbChanged(); } } /// <summary> /// Gets the RGB part value of the color. Internal helper function. /// </summary> internal uint Rgb { get { return ((uint)_r << 16) | ((uint)_g << 8) | _b; } } /// <summary> /// Gets the ARGB part value of the color. Internal helper function. /// </summary> internal uint Argb { get { return ((uint)(_a * 255) << 24) | ((uint)_r << 16) | ((uint)_g << 8) | _b; } } /// <summary> /// Gets or sets the cyan value. /// </summary> public double C { get { return _c; } set { if (value < 0) _c = 0; else if (value > 1) _c = 1; else _c = (float)value; CmykChanged(); } } /// <summary> /// Gets or sets the magenta value. /// </summary> public double M { get { return _m; } set { if (value < 0) _m = 0; else if (value > 1) _m = 1; else _m = (float)value; CmykChanged(); } } /// <summary> /// Gets or sets the yellow value. /// </summary> public double Y { get { return _y; } set { if (value < 0) _y = 0; else if (value > 1) _y = 1; else _y = (float)value; CmykChanged(); } } /// <summary> /// Gets or sets the black (or key) value. /// </summary> public double K { get { return _k; } set { if (value < 0) _k = 0; else if (value > 1) _k = 1; else _k = (float)value; CmykChanged(); } } /// <summary> /// Gets or sets the gray scale value. /// </summary> // ReSharper disable InconsistentNaming public double GS // ReSharper restore InconsistentNaming { get { return _gs; } set { if (value < 0) _gs = 0; else if (value > 1) _gs = 1; else _gs = (float)value; GrayChanged(); } } /// <summary> /// Represents the null color. /// </summary> public static XColor Empty; ///<summary> /// Special property for XmlSerializer only. /// </summary> public string RgbCmykG { get { return String.Format(CultureInfo.InvariantCulture, "{0};{1};{2};{3};{4};{5};{6};{7};{8}", _r, _g, _b, _c, _m, _y, _k, _gs, _a); } set { string[] values = value.Split(';'); _r = byte.Parse(values[0], CultureInfo.InvariantCulture); _g = byte.Parse(values[1], CultureInfo.InvariantCulture); _b = byte.Parse(values[2], CultureInfo.InvariantCulture); _c = float.Parse(values[3], CultureInfo.InvariantCulture); _m = float.Parse(values[4], CultureInfo.InvariantCulture); _y = float.Parse(values[5], CultureInfo.InvariantCulture); _k = float.Parse(values[6], CultureInfo.InvariantCulture); _gs = float.Parse(values[7], CultureInfo.InvariantCulture); _a = float.Parse(values[8], CultureInfo.InvariantCulture); } } static void CheckByte(int val, string name) { if (val < 0 || val > 0xFF) throw new ArgumentException(PSSR.InvalidValue(val, name, 0, 255)); } XColorSpace _cs; float _a; // alpha byte _r; // \ byte _g; // |--- RGB byte _b; // / float _c; // \ float _m; // |--- CMYK float _y; // | float _k; // / float _gs; // >--- gray scale } }
// sendWord.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Collections.Generic; using System.Text; using Word = NetOffice.WordApi; //using Word = Microsoft.Office.Interop.Word; using System.Reflection; using System.IO; using System.Text.RegularExpressions; using System.Collections; using CoreUtilities; /* Features * ************* * DONE ************* * # = Bullets * * = bullets (can't get multi-level to work, and when they do, they'll only work if you have a style) * = Heading 1... Heading 4 = * '' Italic * ''' Bold * ||table|| * * * * ************ * TO DO ************ * */ namespace SendTextAway { class sendWord : sendBase { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ object oFalse = false; object oTrue = true; Word._Application oWord; Word._Document oDoc; Word.Selection oSelection; object oStyle = null; object oHeader1 = null; object oHeader2 = null; object oHeader3 = null; object oHeader4 = null; object oHeader5 = null; object oBullet = null; object oBulletNumber = null; object oTableStyle = null; object oTitle = null; /// <summary> /// before whatever initial operations are required to open the filestream /// or whatever (in the case of Word Auto, will require global variables) /// </summary> protected override int InitializeDocument(ControlFile _controlFile) { //create a word object instead of globals, ie., WOrd(ControlFIle) base.InitializeDocument(_controlFile); oWord = new Word.Application(); oWord.Visible = true; object template = controlFile.Template; oDoc = oWord.Documents.Add( template, oMissing, oMissing, oMissing); oSelection = oWord.Selection; // load defaults from tempalte try { oHeader1 = controlFile.Heading1; oHeader2 = controlFile.Heading2; // write getmethods? oHeader3 = controlFile.Heading3; oHeader4 = controlFile.Heading4; oHeader5 = controlFile.Heading5; oBullet = controlFile.Bullet; oTitle = controlFile.ChapterTitle; oStyle = controlFile.BodyText; oBulletNumber = controlFile.BulletNumber; oTableStyle = controlFile.TableStyle; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); return -1; } // test if style exists before being used bool bExists = false; foreach (Word.Style style in oDoc.Styles) { if (style.NameLocal == (oStyle).ToString()) { bExists = true; } } if (false == bExists) { NewMessage.Show(oStyle.ToString() + " did not exist"); } oSelection.Style = oStyle;// (March 2013 - this might be reasonable replacement // set defaults // oSelection.set_Style(ref oStyle); //this never seemed to happen 12/12/2010 (FIXED! The name was wrong, trying to come up with a better error check system Word.Style oSetStyle = (Word.Style)oSelection.Style; /* DId not work to test if (oSetStyle.NameLocal != (oStyle).ToString()) { NewMessage.Show(oStyle.ToString() + " did not exist"); }*/ return 1; } /// <summary> /// overwrite the tab character being written /// </summary> protected override void AddTab() { InlineWrite("\t"); } /// <summary> /// Builds a table row /// </summary> /// <param name="sText"></param> protected override void AddTable(string sText) { //March 2013 NetOffice.WordApi.Enums.WdDefaultTableBehavior.wdWord8TableBehavior; object objDefaultBehaviorWord8 = Word.Enums.WdDefaultTableBehavior.wdWord8TableBehavior; string[] Cols = sText.Split(new string[1] { "||" }, StringSplitOptions.RemoveEmptyEntries); Word.Table oTable; oTable = oDoc.Tables.Add(oSelection.Range, 1, Cols.Length, objDefaultBehaviorWord8, oMissing); oTable.Style = oTableStyle; // oTable.Range.ParagraphFormat.SpaceAfter = 10; // oSelection.SetRange(oTable.Range.End + 20, 1); //oTable.Borders = Word.WdBorderType.wdBorderBottom; for (int table = 0; table < Cols.Length; table++) { // oTable.Cell(oTable.Rows.Count, table + 1).Range.Text = Word.Range range = oTable.Cell(oTable.Rows.Count, table + 1).Range; oSelection.SetRange(range.Start, range.End); FormatRestOfText(Cols[table]); } // edit from the end // March 2013 Word.Range wrdRng = oDoc.Bookmarks[oEndOfDoc].Range; Word.Range wrdRng = oDoc.Bookmarks[oEndOfDoc].Range; oSelection.SetRange(wrdRng.Start, wrdRng.End); } /// <summary> /// /// </summary> /// <param name="sText"></param> protected override void AddNumberedBullets(string sText) { try { // Figured out how to have two chunks of text //if (oBulletNumber.ToString() != "bulletdefault") { string sTabPrefix = ""; string sOldText = sText; // add tabs sText = sText.TrimStart('#').Trim(); int nInsertionPoint = oSelection.Start; string sTextToAdd = sTabPrefix + sText;// +Environment.NewLine; oSelection.Style = oBulletNumber; // oSelection.set_Style(ref oBulletNumber); object defaultlist = Word.Enums.WdDefaultListBehavior.wdWord10ListBehavior; /*while (oSelection.Range.ListFormat.ListType != Microsoft.Office.Interop.Word.WdListType.wdListSimpleNumbering) { oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); }*/ //oSelection.Range.ListFormat.List. oSelection.Range.ListFormat.ApplyNumberDefault( defaultlist); oSelection.Range.ListFormat.ApplyNumberDefault( defaultlist); // oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); // oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); /* Word.ListFormat cleanFormat = null; if (cleanFormat == null) { cleanFormat = oSelection.Range.ListFormat; } oSelection.Range. = cleanFormat; */ int nCount = 0; bool done = false; //System.Windows.Forms.MessageBox.Show(oSelection.Range.ListFormat.ListValue.ToString()); oSelection.Range.ListFormat.ListLevelNumber = 1; while (done == false) { // test to see if are an empty string if (sOldText.Length > nCount + 1) { if (nCount > 0 && sOldText[nCount] == '#') { // tab blanked the text; /* Word.Range oldrange = oSelection.Range; oSelection.SetRange(nInsertionPoint, nInsertionPoint + sTextToAdd.Length); oSelection.Range.InsertAlignmentTab((int)Word.WdAlignmentTabAlignment.wdRight, (int)Word.WdAlignmentTabAlignment.wdLeft); oSelection.SetRange(oldrange.Start, oldrange.End); */ oSelection.Range.ListFormat.ListLevelNumber++; // ++crash // oSelection.Range.ListFormat.ListIndent(); not what we want //oSelection.TypeText("\t"); // closet but ick // oSelection.TypeText("\xB"); vertical tab did not work // oSelection.TypeText(); } else if (nCount > 0) { done = true; } } else { done = true; } nCount++; } // we restart a list if the ListValue is greater than ONE // and we have reset InAList = false // This means that we are at #2 of a list that thinks it is continuing // from another list seperated by text bool bRestartList = false; if (oSelection.Range.ListFormat.ListValue > 1 && InAList == false) { bRestartList = true; } // we sometimes reset the list due to 'issues' if ((oSelection.Range.ListFormat.ListLevelNumber == 1 && FixListScan(oSelection.Range.ListFormat.ListString) == true) || (bRestartList == true) ) { foreach (Word.Paragraph para in oSelection.Range.ListParagraphs) { // para.ResetAdvanceTo(); // para.SeparateList(); para.Reset(); // worked for simple list but not big doc //para.Reset(); } } // set that we are in a list // if (oSelection.Range.ListFormat.ListValue == 1) { InAList = true; } /* worked but Reset seems easier * object oDef = Word.WdDefaultListBehavior.wdWord10ListBehavior; object myTemplateIndex = 1; Word.ListTemplate myTemplate = oWord.ListGalleries[Microsoft.Office.Interop.Word.WdListGalleryType.wdNumberGallery].ListTemplates.get_Item(ref myTemplateIndex); oSelection.Range.ListFormat.ApplyListTemplate(myTemplate, ref oFalse, ref oFalse, ref oDef ); * */ // System.Windows.Forms.MessageBox.Show("bad list"); /* foreach (Word.Paragraph para in oSelection.Range.ListParagraphs) { // para.ResetAdvanceTo(); // para.SeparateList(); para.Reset(); // worked for simple list but not big doc para.Reset(); } */ // oSelection.Range.ListParagraphs[1].SeparateList(); //oSelection.Range.ListFormat.ApplyListTemplate(oSelection.Range.ListParagraphs[1]. // oSelection.Range.SetListLevel(1); // oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); // oSelection.set_Style(ref oBulletNumber); // oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); //oSelection.TypeText(sTextToAdd); FormatRestOfText(sTextToAdd);// + "(" + oSelection.Range.ListFormat.ListValue.ToString()); //indent for each # // turn off // oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); // oSelection.Range.ListFormat.ListLevelNumber = 1; oSelection.Range.ListFormat.ApplyNumberDefault( defaultlist); oSelection.Style =oStyle; } } catch (Exception ex) { UpdateErrors("Failure in AddNumberedBullets + " + sText + " " + ex.ToString()); } /* else { object defaultlist = Word.WdDefaultListBehavior.wdWord10ListBehavior; oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); oSelection.TypeText(sText + Environment.NewLine); // oSelection.Select(); did I need this oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); }*/ /* bool done = false; int nCount = 0; //indent for each # while (done == false) { if (sText[nCount] == '#') { oSelection.Range.ListFormat.ListIndent(); } else { done = true; } nCount++; } sText = sText.TrimStart('#').Trim(); object defaultlist = Word.WdDefaultListBehavior.wdWord10ListBehavior; oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist); oSelection.TypeText(sText + Environment.NewLine); oSelection.Range.ListFormat.ApplyNumberDefault(ref defaultlist);*/ } /// <summary> /// Align text until next alignment command is hit /// 0 - Center /// 1 - Left /// 2 - Right /// </summary> /// <param name="nAlignment"></param> protected override void AlignText(int nAlignment) { switch (nAlignment) { case 0: oSelection.ParagraphFormat.Alignment = Word.Enums.WdParagraphAlignment.wdAlignParagraphCenter; break; case 1: oSelection.ParagraphFormat.Alignment = Word.Enums.WdParagraphAlignment.wdAlignParagraphLeft; break; case 2: oSelection.ParagraphFormat.Alignment = Word.Enums.WdParagraphAlignment.wdAlignParagraphRight; break; } } /// <summary> /// /// </summary> /// <param name="sText"></param> protected override void AddBullets(string sText) { /* sText = sText.TrimStart('*').Trim(); object defaultlist = Word.WdDefaultListBehavior.wdWord10ListBehavior; oSelection.Range.ListFormat.ApplyBulletDefault(ref defaultlist); oSelection.Range.ListFormat.ListOutdent(); //oSelection.TypeText(FormatRestOfText(sText) + Environment.NewLine); // oSelection.Range.ListFormat.ListLevelNumber++; FormatRestOfText(sText); oSelection.Range.ListFormat.ApplyBulletDefault(ref defaultlist);*/ string sOldText = sText; // add tabs sText = sText.TrimStart('*').Trim(); int nInsertionPoint = oSelection.Start; string sTextToAdd = sText; oSelection.Style = oBullet; object defaultlist = Word.Enums.WdDefaultListBehavior.wdWord10ListBehavior; oSelection.Range.ListFormat.ApplyBulletDefault( defaultlist); oSelection.Range.ListFormat.ApplyBulletDefault( defaultlist); int nCount = 0; bool done = false; oSelection.Range.ListFormat.ListLevelNumber = 1; while (done == false) { // test to see if are an empty string if (sOldText.Length > nCount + 1) { if (nCount > 0 && sOldText[nCount] == '*') { oSelection.Range.ListFormat.ListLevelNumber++; } else if (nCount > 0) { done = true; } } else { done = true; } nCount++; } FormatRestOfText(sTextToAdd);// + "(" + oSelection.Range.ListFormat.ListValue.ToString()); oSelection.Range.ListFormat.ApplyBulletDefault( defaultlist); oSelection.Style = oStyle; } /// <summary> /// insert a page break, but only if we need it /// </summary> protected override void AddPageBreak() { Word.Enums.WdInformation info =Word.Enums.WdInformation.wdFirstCharacterLineNumber; int line = (int)oSelection.get_Information(info); int col =(int)oSelection.get_Information(Word.Enums.WdInformation.wdFirstCharacterColumnNumber); // if we are not on the first line and column of a page we insert a page break if ( !(line == 1 && col == 1) ) { object pageBreak = Word.Enums.WdBreakType.wdPageBreak; oSelection.InsertBreak( pageBreak); } } /// <summary> /// /// </summary> /// <param name="sText"></param> protected override string AddTitle(string sText) { sText = base.AddTitle(sText); if (chapter > 1) { AddPageBreak(); } oSelection.Style = oTitle; oSelection.TypeText(sText + Environment.NewLine); oSelection.Style = oStyle; return sText; } /// <summary> /// sID is already lowercase /// </summary> /// <param name="sID"></param> protected override void AddFootnote(string sID) { sID = sID.Trim(); if (FootnoteHash.ContainsKey(sID) == true) { string sSource = (string) FootnoteHash[sID]; sSource = sSource.Replace("<br>", Environment.NewLine); // process text lienfeed object sText = sSource; object id = (object)sID; // oSelection.Text = oSelection.Text + " "; oSelection.Select(); object start = oSelection.Range.End-2; object end = oSelection.Range.End-1;// oSelection.Range.End - 1; Word.Range mark = oDoc.Range( start, end); //oSelection.TypeText("(Note)"); oSelection.Footnotes.Add(mark, oMissing, sText); object amount = 1; oSelection.MoveLeft( oMissing, amount, oMissing); } else { NewMessage.Show(String.Format("{0} footnote not found!", sID)); } } /// <summary> /// /// </summary> /// <param name="sText"></param> /// <param name="nLevel">Heading level 1..4</param> protected override void AddHeader(string sText, int nLevel) { object oStyleToUse = null; switch (nLevel) { case 1: oStyleToUse = oHeader1; break; case 2: oStyleToUse = oHeader2; break; case 3: oStyleToUse = oHeader3; break; case 4: oStyleToUse = oHeader4; break; case 5: oStyleToUse = oHeader5; break; } oSelection.Style = oStyleToUse; oSelection.TypeText(sText + Environment.NewLine); oSelection.Style = oStyle; } /// <summary> /// Starts a multiline format change such as /// <example> /// here /// </example> /// </summary> /// <param name="sFormatType"></param> /// <returns></returns> protected override bool AddStartMultiLineFormat(string sFormatType) { // starting a format change object newFormat = sFormatType; oSelection.Style = newFormat; return true; } /// <summary> /// resets the formatting of a multi line format to normal format /// </summary> /// <returns></returns> protected override void AddEndMultiLineFormat() { oSelection.Style = oStyle; } protected override void ChatMode(int onoff) { switch (controlFile.ChatMode) { case 0: InlineUnderline(onoff); break; case 1: InlineItalic(onoff); break; case 2: InlineBold(onoff); break; } /* if (1 == onoff) { // object newFormat = "Emphasis"; // oSelection.set_Style(ref newFormat); InlineUnderline(1); } else { // back to default // oSelection.set_Style(ref oStyle); }*/ } protected override int LineCount() { // return oDoc.Sentences.Count; return oDoc.Paragraphs.Count; } /// <summary> /// searches for the object in text /// /// May 2012 /// Original intent was just to look for extra brackets in text as /// error detction mechanism /// </summary> /// <param name="searchMe"></param> protected override void SearchFor(object searchMe) { /* NEVER WORKED object item = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToLine; object whichItem = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst; object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceNone; object forward = false; //cause we are back of it? object matchAllWord = false; object missing = System.Reflection.Missing.Value; oSelection.Range.Document.GoTo(ref item, ref whichItem, ref missing, ref missing); oSelection.Range.Find.Execute(ref searchMe, ref missing, ref matchAllWord, ref missing, ref missing, ref missing, ref forward, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); */ } protected override void Cleanup() { /*12/12/2010 - disabled, lost text between page breaks if (controlFile.Linespace != -1) { // do cleanup // fix line spacing NewMessage.Show("Starting Double Space -- DO NOT TOUCH WORD FILE UNTIL DONE"); foreach (Microsoft.Office.Interop.Word.Paragraph paragraph in oDoc.Paragraphs) { paragraph.Format.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceExactly; paragraph.Format.LineSpacing = oWord.LinesToPoints(controlFile.Linespace); } NewMessage.Show("DOUBLE SPACE FINISHED"); }*/ //* trying to replace tabbed underlines with no underline... instead created a macro and a reminder to run it /* oSelection.Find.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle; oSelection.Find.Replacement.ClearFormatting(); oSelection.Find.Replacement.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone; oSelection.Find.Text = "^t"; oSelection.Find.Replacement.Text = "^t"; oSelection.Find. */ // may 2012 trying to count lines /* foreach (Microsoft.Office.Interop.Word.Paragraph paragraph in oDoc.Paragraphs) { // count paragraphs foreach ( }*/ base.Cleanup(); // update the table of contents if present if (oDoc.TablesOfContents.Count > 0) { oDoc.TablesOfContents[1].Update(); } } /// <summary> /// While processing linline formatting (bold, et cetera), this is used to write out a line of text /// </summary> /// <param name="sText"></param> protected override void InlineWrite(string sText) { base.InlineWrite(sText); oSelection.TypeText(sText); } protected override void InlineBold(int nValue) { oSelection.Font.Bold = nValue; } protected override void InlineItalic(int nValue) { oSelection.Font.Italic = nValue; } /* /// <summary> /// get current page number /// </summary> /// <param name="nValue"></param> protected override string PageNumber() { // return oSelection.Footnotes[0].ToString(); return oSelection.Footnotes.Count.ToString(); }*/ protected override void InlineStrikeThrough(int nValue) { oSelection.Font.StrikeThrough = nValue; } /// <summary> /// nvalue is ignored for underline /// </summary> /// <param name="nValue"></param> protected override void InlineSuper(int nValue) { oSelection.Font.Superscript = nValue; } /// <summary> /// nvalue is ignored for underline /// </summary> /// <param name="nValue"></param> protected override void InlineSub(int nValue) { oSelection.Font.Subscript = nValue; } /// <summary> /// Adds a bookmark at cursor point /// </summary> /// <param name="sBookmark"></param> protected override void AddBookmark(string sBookmark) { sBookmark = sBookmark.Trim(); object Range = oSelection.Range; oSelection.Bookmarks.Add(sBookmark, Range); } int formatCount = 0; // Nov 2012 will increment. If we are already underlining and then we have underlining inside of underlining // we do not STOP underlining until the block text is finished formatting. /// <summary> /// nvalue is ignored for underline /// </summary> /// <param name="nValue"></param> protected override void InlineUnderline(int nValue) { if (nValue == 1) { if (oSelection.Font.Underline == Word.Enums.WdUnderline.wdUnderlineSingle) { NewMessage.Show("We were asked to start underining during a segment of text wherein we were ALREADY underlining. We are ignoring this request. Check for any text issues."); formatCount++; } oSelection.Font.Underline = Word.Enums.WdUnderline.wdUnderlineSingle; } else if (nValue == 0) { if (0 == formatCount) { oSelection.Font.Underline = Word.Enums.WdUnderline.wdUnderlineNone; } else formatCount--; } } /// <summary> /// /// </summary> /// <param name="sPathToFile"></param> protected override void AddLink(string sPathToFile, string sTitle) { object oTextToShow = sTitle; object oLink = sPathToFile; oSelection.Hyperlinks.Add(oSelection.Range, oLink, oMissing, oMissing, oTextToShow, oMissing); // System.Windows.Forms.MessageBox.Show(sPathToFile); } /// <summary> /// adds a picture /// </summary> /// <param name="nValue"></param> protected override void AddPicture(string sPathToFile) { base.AddPicture(sPathToFile); object oWidth = 10; object oLeft = 1; object oTop = oSelection.Range.Start; object oHeight = 100; // System.Windows.Forms.MessageBox.Show(sPathToFile); //oDoc.Shapes.AddPicture(sPathToFile, ref oMissing, ref oMissing, ref oLeft, ref oTop, ref oWidth, ref oHeight, ref oMissing); oSelection.InlineShapes.AddPicture(sPathToFile, oMissing, oTrue, oMissing); } /// <summary> /// Adds a table of contents at location /// </summary> protected override void AddTableOfContents() { Object oUpperHeadingLevel = "1"; Object oLowerHeadingLevel = "3"; Object oTrue = true; Object oTOCTableID = "TableOfContents"; oDoc.TablesOfContents.Add(oSelection.Range, oTrue, oUpperHeadingLevel, oLowerHeadingLevel, oMissing, oTOCTableID, oTrue, oTrue, oMissing, oTrue, oTrue, oTrue); } /// <summary> /// just an example function /// </summary> public void example() { //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add( oMissing, oMissing, oMissing, oMissing); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add( oMissing); object styleHeading1 = "Heading 1"; oPara1.Style = styleHeading1; oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); //Insert a paragraph at the end of the document. Word.Paragraph oPara2; object oRng = oDoc.Bookmarks[ oEndOfDoc].Range; oPara2 = oDoc.Content.Paragraphs.Add( oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks[ oEndOfDoc].Range; oPara3 = oDoc.Content.Paragraphs.Add( oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //Insert a 3 x 5 table, fill it with data, and make the first row //bold and italic. Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks[ oEndOfDoc].Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, oMissing, oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for (r = 1; r <= 3; r++) for (c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //Add some text after the table. Word.Paragraph oPara4; oRng = oDoc.Bookmarks[ oEndOfDoc].Range; oPara4 = oDoc.Content.Paragraphs.Add( oRng); oPara4.Range.InsertParagraphBefore(); oPara4.Range.Text = "And here's another table:"; oPara4.Format.SpaceAfter = 24; oPara4.Range.InsertParagraphAfter(); //Insert a 5 x 2 table, fill it with data, and change the column widths. wrdRng = oDoc.Bookmarks[ oEndOfDoc].Range; oTable = oDoc.Tables.Add(wrdRng, 5, 2, oMissing, oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; for (r = 1; r <= 5; r++) for (c = 1; c <= 2; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2 oTable.Columns[2].Width = oWord.InchesToPoints(3); //Keep inserting text. When you get to 7 inches from top of the //document, insert a hard page break. object oPos; double dPos = oWord.InchesToPoints(7); oDoc.Bookmarks[ oEndOfDoc].Range.InsertParagraphAfter(); do { wrdRng = oDoc.Bookmarks[ oEndOfDoc].Range; wrdRng.ParagraphFormat.SpaceAfter = 6; wrdRng.InsertAfter("A line of text"); wrdRng.InsertParagraphAfter(); oPos = wrdRng.get_Information (Word.Enums.WdInformation.wdVerticalPositionRelativeToPage); } while (dPos >= Convert.ToDouble(oPos)); object oCollapseEnd = Word.Enums.WdCollapseDirection.wdCollapseEnd; object oPageBreak = Word.Enums.WdBreakType.wdPageBreak; wrdRng.Collapse( oCollapseEnd); wrdRng.InsertBreak( oPageBreak); wrdRng.Collapse( oCollapseEnd); wrdRng.InsertAfter("We're now on page 2. Here's my chart:"); wrdRng.InsertParagraphAfter(); //Insert a chart. // Word.InlineShape oShape; // object oClassType = "MSGraph.Chart.8"; // wrdRng = oDoc.Bookmarks[ oEndOfDoc].Range; // oShape = wrdRng.InlineShapes.AddOLEObject( oClassType, oMissing, // oMissing, oMissing, oMissing, // oMissing, oMissing, oMissing); //Demonstrate use of late bound oChart and oChartApp objects to //manipulate the chart object with MSGraph. // object oChart; // object oChartApp; // oChart = oShape.OLEFormat.Object; // oChartApp = oChart.GetType().InvokeMember("Application", // BindingFlags.GetProperty, null, oChart, null); // // //Change the chart type to Line. // object[] Parameters = new Object[1]; // Parameters[0] = 4; //xlLine = 4 // oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty, // null, oChart, Parameters); // // //Update the chart image and quit MSGraph. // oChartApp.GetType().InvokeMember("Update", // BindingFlags.InvokeMethod, null, oChartApp, null); // oChartApp.GetType().InvokeMember("Quit", // BindingFlags.InvokeMethod, null, oChartApp, null); // //... If desired, you can proceed from here using the Microsoft Graph // //Object model on the oChart and oChartApp objects to make additional // //changes to the chart. // // //Set the width of the chart. // oShape.Width = oWord.InchesToPoints(6.25f); // oShape.Height = oWord.InchesToPoints(3.57f); //Add text after the chart. wrdRng = oDoc.Bookmarks[ oEndOfDoc].Range; wrdRng.InsertParagraphAfter(); wrdRng.InsertAfter("THE END."); //Close this form. } /// <summary> /// This did not work /// </summary> /// <param name="source"></param> /// <param name="matchPattern"></param> /// <param name="findAllUnique"></param> /// <returns></returns> public static Match[] FindSubstrings(string source, string matchPattern, bool findAllUnique) { SortedList uniqueMatches = new SortedList(); Match[] retArray = null; Regex RE = new Regex(matchPattern, RegexOptions.Multiline); MatchCollection theMatches = RE.Matches(source); if (findAllUnique) { for (int counter = 0; counter < theMatches.Count; counter++) { if (!uniqueMatches.ContainsKey(theMatches[counter].Value)) { uniqueMatches.Add(theMatches[counter].Value, theMatches[counter]); } } retArray = new Match[uniqueMatches.Count]; uniqueMatches.Values.CopyTo(retArray, 0); } else { retArray = new Match[theMatches.Count]; theMatches.CopyTo(retArray, 0); } return (retArray); } public override string ToString () { return string.Format ("[sendWord]"); } protected override string HandleEmDash (string sText) { return sText.Replace ("--", "\x2014"); } protected override string ReplaceFancyCharacters (string sSource) { if (true == controlFile.FancyCharacters) { sSource = sSource.Replace(".\"", ".\x201D"); sSource = sSource.Replace("\".", "\x201D."); sSource = sSource.Replace("!\"", "!\x201D"); sSource = sSource.Replace("?\"", "?\x201D"); sSource = sSource.Replace("--\"", "--\x201D"); sSource = sSource.Replace("-\"", "-\x201D"); sSource = sSource.Replace("-- \"", "-- \x201D"); sSource = sSource.Replace(",\"", ",\x201D"); // remainder of quotes will be the opposite way sSource = sSource.Replace("\"", "\x201C"); // do standard repalcements (February 2010) if (sSource.IndexOf("...") > -1) { sSource = sSource.Replace("...", "\x2026"); } // to finish look here: http://www.unicode.org/charts/charindex.html } return sSource; } } }
namespace SupermarketsChain.Data.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using SupermarketsChain.Data.Contexts; using SupermarketsChain.Models; internal sealed class Configuration : DbMigrationsConfiguration<SupermarketsChainDbContext> { private readonly Random random = new Random(0); public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = true; } protected override void Seed(SupermarketsChainDbContext context) { var towns = this.SeedTowns(context); var supermarkets = this.SeedSupermarkets(context, towns); var vendors = this.SeedVendors(context); var measures = this.SeedMeasures(context); var products = this.SeedProducts(context, vendors, measures); this.SeedSales(context, products, supermarkets); } private void SeedSales(SupermarketsChainDbContext context, IList<Product> products, IList<Supermarket> supermarkets) { var sales = new List<Sale>(); for (int i = 0; i < 100; i++) { var unitPrice = this.random.Next(1000); var quantity = this.random.Next(1000); sales.Add(new Sale { Product = products[this.random.Next(products.Count)], Supermarket = supermarkets[this.random.Next(supermarkets.Count)], SoldDate = this.RandomDay(), PricePerUnit = unitPrice, Quantity = quantity, SaleCost = unitPrice * quantity }); } foreach (var sale in sales) { context.Sales.Add(sale); } context.SaveChanges(); } private IList<Measure> SeedMeasures(SupermarketsChainDbContext context) { var measures = new List<Measure> { new Measure { Name = "Liter" }, new Measure { Name = "Unit" }, new Measure { Name = "Kilograms" }, new Measure { Name = "Grams" } }; foreach (var measure in measures) { context.Measures.AddOrUpdate(measure); } context.SaveChanges(); return measures; } private IList<Product> SeedProducts(SupermarketsChainDbContext context, IList<Vendor> vendors, IList<Measure> measures) { var products = new List<Product> { new Product { Name = "Laptop", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Tablet", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Smartphone", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Glass", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Monitor", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Visual Studio", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Energy Drink", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Banana", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Potato", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Lan Cable", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Shirt", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Beer", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Vodka", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Wisky", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] }, new Product { Name = "Coffee", Vendor = vendors[this.random.Next(vendors.Count)], Measure = measures[this.random.Next(measures.Count)] } }; foreach (var product in products) { context.Products.AddOrUpdate(product); } context.SaveChanges(); return products; } private IList<Vendor> SeedVendors(SupermarketsChainDbContext context) { var vendors = new List<Vendor> { new Vendor { Name = "Bosh" }, new Vendor { Name = "Simens" }, new Vendor { Name = "Toshiba" }, new Vendor { Name = "FF" }, new Vendor { Name = "K-Classics" }, new Vendor { Name = "Clever" } }; foreach (var vendor in vendors) { context.Vendors.AddOrUpdate(vendor); } context.SaveChanges(); return vendors; } private IList<Supermarket> SeedSupermarkets(SupermarketsChainDbContext context, IList<Town> towns) { var supermarkets = new List<Supermarket> { new Supermarket { Name = "Billa", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Billa", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Fantastico", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "T-Market", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "MyShop", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Dar", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Kal", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Kaufland", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "MyShop", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Kaufland", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Lidl", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Plus", Town = towns[this.random.Next(towns.Count)] }, new Supermarket { Name = "Tempo", Town = towns[this.random.Next(towns.Count)] } }; foreach (var supermarket in supermarkets) { context.Supermarkets.AddOrUpdate(supermarket); } context.SaveChanges(); return supermarkets; } private IList<Town> SeedTowns(SupermarketsChainDbContext context) { var towns = new List<Town> { new Town { Name = "Sofia" }, new Town { Name = "Varna" }, new Town { Name = "Burgas" }, new Town { Name = "Plovdiv" }, new Town { Name = "Ruse" }, new Town { Name = "Pernik" } }; foreach (var town in towns) { context.Towns.AddOrUpdate(town); } context.SaveChanges(); return towns; } private DateTime RandomDay() { DateTime start = new DateTime(1995, 1, 1); int range = (DateTime.Today - start).Days; return start.AddDays(this.random.Next(range)); } } }
namespace SampleOptionQuoting { using System; using System.Collections.Generic; using System.Linq; using Ecng.Common; using StockSharp.Algo; using StockSharp.BusinessEntities; using StockSharp.Messages; class DummyProvider : CollectionSecurityProvider, IMarketDataProvider, IPositionProvider { public DummyProvider(IEnumerable<Security> securities, IEnumerable<Position> positions) : base(securities) { _positions = positions ?? throw new ArgumentNullException(nameof(positions)); } event Action<Security, IEnumerable<KeyValuePair<Level1Fields, object>>, DateTimeOffset, DateTimeOffset> IMarketDataProvider.ValuesChanged { add { } remove { } } MarketDepth IMarketDataProvider.GetMarketDepth(Security security) { return null; } object IMarketDataProvider.GetSecurityValue(Security security, Level1Fields field) { switch (field) { case Level1Fields.OpenInterest: return security.OpenInterest; case Level1Fields.ImpliedVolatility: return security.ImpliedVolatility; case Level1Fields.HistoricalVolatility: return security.HistoricalVolatility; case Level1Fields.Volume: return security.Volume; case Level1Fields.LastTradePrice: return security.LastTrade?.Price; case Level1Fields.LastTradeVolume: return security.LastTrade?.Volume; case Level1Fields.BestBidPrice: return security.BestBid?.Price; case Level1Fields.BestBidVolume: return security.BestBid?.Volume; case Level1Fields.BestAskPrice: return security.BestAsk?.Price; case Level1Fields.BestAskVolume: return security.BestAsk?.Volume; } return null; } IEnumerable<Level1Fields> IMarketDataProvider.GetLevel1Fields(Security security) { return new[] { Level1Fields.OpenInterest, Level1Fields.ImpliedVolatility, Level1Fields.HistoricalVolatility, Level1Fields.Volume, Level1Fields.LastTradePrice, Level1Fields.LastTradeVolume, Level1Fields.BestBidPrice, Level1Fields.BestAskPrice, Level1Fields.BestBidVolume, Level1Fields.BestAskVolume }; } event Action<Trade> IMarketDataProvider.NewTrade { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security> IMarketDataProvider.NewSecurity { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security> IMarketDataProvider.SecurityChanged { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<MarketDepth> IMarketDataProvider.NewMarketDepth { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<MarketDepth> IMarketDataProvider.MarketDepthChanged { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<MarketDepth> IMarketDataProvider.FilteredMarketDepthChanged { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<OrderLogItem> IMarketDataProvider.NewOrderLogItem { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<News> IMarketDataProvider.NewNews { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<News> IMarketDataProvider.NewsChanged { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<SecurityLookupMessage, IEnumerable<Security>, Exception> IMarketDataProvider.LookupSecuritiesResult { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<SecurityLookupMessage, IEnumerable<Security>, IEnumerable<Security>, Exception> IMarketDataProvider.LookupSecuritiesResult2 { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<BoardLookupMessage, IEnumerable<ExchangeBoard>, Exception> IMarketDataProvider.LookupBoardsResult { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<BoardLookupMessage, IEnumerable<ExchangeBoard>, IEnumerable<ExchangeBoard>, Exception> IMarketDataProvider.LookupBoardsResult2 { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<TimeFrameLookupMessage, IEnumerable<TimeSpan>, Exception> IMarketDataProvider.LookupTimeFramesResult { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<TimeFrameLookupMessage, IEnumerable<TimeSpan>, IEnumerable<TimeSpan>, Exception> IMarketDataProvider.LookupTimeFramesResult2 { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage> IMarketDataProvider.MarketDataSubscriptionSucceeded { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage, Exception> IMarketDataProvider.MarketDataSubscriptionFailed { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage, SubscriptionResponseMessage> IMarketDataProvider.MarketDataSubscriptionFailed2 { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage> IMarketDataProvider.MarketDataUnSubscriptionSucceeded { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage, Exception> IMarketDataProvider.MarketDataUnSubscriptionFailed { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage, SubscriptionResponseMessage> IMarketDataProvider.MarketDataUnSubscriptionFailed2 { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, SubscriptionFinishedMessage> IMarketDataProvider.MarketDataSubscriptionFinished { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage, Exception> IMarketDataProvider.MarketDataUnexpectedCancelled { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } event Action<Security, MarketDataMessage> IMarketDataProvider.MarketDataSubscriptionOnline { add => throw new NotSupportedException(); remove => throw new NotSupportedException(); } MarketDepth IMarketDataProvider.GetFilteredMarketDepth(Security security) { throw new NotSupportedException(); } private readonly IEnumerable<Position> _positions; IEnumerable<Position> IPositionProvider.Positions => _positions; IEnumerable<Portfolio> IPortfolioProvider.Portfolios => _positions.OfType<Portfolio>(); event Action<Position> IPositionProvider.NewPosition { add { } remove { } } event Action<Position> IPositionProvider.PositionChanged { add { } remove { } } event Action<Portfolio> IPortfolioProvider.NewPortfolio { add { } remove { } } event Action<Portfolio> IPortfolioProvider.PortfolioChanged { add { } remove { } } Position IPositionProvider.GetPosition(Portfolio portfolio, Security security, string strategyId, Sides? side, string clientCode, string depoName, TPlusLimits? limit) { return _positions.FirstOrDefault(p => p.Security == security && p.Portfolio == portfolio); } Portfolio IPortfolioProvider.LookupByPortfolioName(string name) { return _positions.OfType<Portfolio>().FirstOrDefault(p => p.Name.EqualsIgnoreCase(name)); } } }
/* 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.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.Xrm.Client; namespace Microsoft.Xrm.Portal.Web { /// <summary> /// Represents an assembly attribute that registers another assembly of statically served embedded resource files. /// </summary> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class EmbeddedResourceAssemblyAttribute : Attribute { /// <summary> /// Gets the name of the assembly containing the embedded resources. /// </summary> public Assembly Assembly { get; private set; } /// <summary> /// Gets the default namespace. /// </summary> public string Namespace { get; private set; } /// <summary> /// Gets the virtual directory path pattern to match against. /// </summary> public string VirtualPathMask { get; private set; } /// <summary> /// Gets the flag allowing the previous virtual path provider to take precedence. /// </summary> public bool AllowOverride { get; set; } /// <summary> /// Gets the flag allowing a default document transfer to occur. /// </summary> public bool AllowDefaultDocument { get; set; } /// <summary> /// Gets the set of resources contained in the assembly. /// </summary> public EmbeddedResourceNode Resources { get; private set; } /// <summary> /// Gets a lookup from resource name to resource node. /// </summary> public IDictionary<string, EmbeddedResourceNode> ResourceLookup { get; private set; } public EmbeddedResourceAssemblyAttribute(string virtualPathMask, string assembly, string theNamespace) { VirtualPathMask = virtualPathMask; Namespace = theNamespace; AllowOverride = true; AllowDefaultDocument = true; try { // load the related assembly and resource tree Assembly = Assembly.Load(assembly); ResourceLookup = new Dictionary<string, EmbeddedResourceNode>(StringComparer.InvariantCultureIgnoreCase); Resources = new EmbeddedResourceNode(string.Empty, true, false, "~", Namespace); // convert resource names to virtual paths var paths = GetVirtualPaths(Assembly.GetManifestResourceNames()); foreach (var path in paths) { AddResource(Resources, ResourceLookup, path.VirtualPath, path.ResourceName); } } catch (FileNotFoundException) { // Silently fail if the resource assembly isn't found. } } public EmbeddedResourceNode FindResource(string path) { if (ResourceLookup == null) return null; var resourceName = ConvertVirtualPathToResourceName(path); EmbeddedResourceNode node; if (ResourceLookup.TryGetValue(resourceName, out node)) { return node; } return null; } private static readonly string[] _directoryDelimiters = new[] { "/", @"\", "~" }; private static void AddResource(EmbeddedResourceNode resources, IDictionary<string, EmbeddedResourceNode> lookup, string path, string resourceName) { var parts = path.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries); AddResource(resources, lookup, parts, resourceName); } private static void AddResource(EmbeddedResourceNode node, IDictionary<string, EmbeddedResourceNode> lookup, IEnumerable<string> path, string resourceName) { if (path.Any()) { var name = path.First(); var child = node.Children.SingleOrDefault(n => n.Name == name); if (child == null) { var isFile = path.Count() == 1; var resource = isFile ? resourceName : GetResourceName(node, name); child = new EmbeddedResourceNode(name, !isFile, isFile, GetVirtualPath(node, name), resource); node.Children.Add(child); lookup.Add(resource, child); } AddResource(child, lookup, path.Skip(1), resourceName); } } private static string GetVirtualPath(EmbeddedResourceNode node, string name) { return "{0}/{1}".FormatWith(node.VirtualPath, name); } private static string GetResourceName(EmbeddedResourceNode node, string name) { return "{0}.{1}".FormatWith(node.VirtualPath, name); } private struct Pair { public string VirtualPath; public string ResourceName; } private IEnumerable<Pair> GetVirtualPaths(IEnumerable<string> resourceNames) { var files = Assembly.GetCustomAttributes(typeof(EmbeddedResourceFileAttribute), true).Cast<EmbeddedResourceFileAttribute>(); var lookup = new Dictionary<string, string>(); foreach (var file in files) { lookup[file.ResourceName] = file.VirtualPath; } foreach (var resourceName in resourceNames) { var virtualPath = lookup.ContainsKey(resourceName) ? lookup[resourceName] : ConvertResourceNameToVirtualPath(resourceName); yield return new Pair { VirtualPath = virtualPath, ResourceName = resourceName }; } } private string ConvertResourceNameToVirtualPath(string resourceName) { // generic algorithm for turning a resource name into a virtual path // replace every dot with a slash except for the last dot // chop off the leading default namespace var index1 = resourceName.LastIndexOf('.'); var index2 = index1 + 1; var head = Regex.Replace(resourceName.Substring(0, index1), "^" + Namespace, string.Empty, RegexOptions.IgnoreCase).Replace('.', '/'); var tail = resourceName.Substring(index2, resourceName.Length - index2); return "~/{0}.{1}".FormatWith(head, tail); } private string ConvertVirtualPathToResourceName(string virtualPath) { // converting an entire path // for all parts: prepend an '_' if the name starts with a numeric character // replace all '/' or '\\' with '.' // prepend the default namespace // besides a leading underscore, filenames remain unchanged var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries); if (parts.Any()) { var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p); var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName); var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_'); var tail = partsWithUnderscores.Last(); return "{0}.{1}".FormatWith(head, tail); } return null; } private static string ConvertDirectoryToResourceName(string directory) { // converting and individual directory // for all parts: prepend an '_' if the name starts with a numeric character // convert '-' to '_' var parts = directory.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Any()) { var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p); return string.Join(".", partsWithUnderscores.ToArray()).Replace('-', '_'); } 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 System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using System.Net; using System.Security.Principal; using System.Security; namespace System.DirectoryServices.AccountManagement { internal class Utils { // To stop the compiler from autogenerating a constructor for this class private Utils() { } // // byte utilities // /// <summary> /// Performs bytewise comparison of two byte[] arrays /// </summary> /// <param name="src">Array to compare</param> /// <param name="tgt">Array to compare against src</param> /// <returns>true if identical, false otherwise</returns> internal static bool AreBytesEqual(byte[] src, byte[] tgt) { if (src.Length != tgt.Length) return false; for (int i = 0; i < src.Length; i++) { if (src[i] != tgt[i]) return false; } return true; } internal static void ClearBit(ref int value, uint bitmask) { value = (int)(((uint)value) & ((uint)(~bitmask))); } internal static void SetBit(ref int value, uint bitmask) { value = (int)(((uint)value) | ((uint)bitmask)); } // {0xa2, 0x3f,...} --> "a23f..." internal static string ByteArrayToString(byte[] byteArray) { StringBuilder stringizedArray = new StringBuilder(); foreach (byte b in byteArray) { stringizedArray.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringizedArray.ToString(); } // Use this for ldap search filter string... internal static string SecurityIdentifierToLdapHexFilterString(SecurityIdentifier sid) { return (ADUtils.HexStringToLdapHexString(SecurityIdentifierToLdapHexBindingString(sid))); } // use this for binding string... internal static string SecurityIdentifierToLdapHexBindingString(SecurityIdentifier sid) { byte[] sidB = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidB, 0); StringBuilder stringizedBinarySid = new StringBuilder(); foreach (byte b in sidB) { stringizedBinarySid.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringizedBinarySid.ToString(); } internal static byte[] StringToByteArray(string s) { if (s.Length % 2 != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Utils", "StringToByteArray: string has bad length " + s.Length); return null; } byte[] bytes = new byte[s.Length / 2]; for (int i = 0; i < (s.Length) / 2; i++) { char firstChar = s[i * 2]; char secondChar = s[(i * 2) + 1]; if (((firstChar >= '0' && firstChar <= '9') || (firstChar >= 'A' && firstChar <= 'F') || (firstChar >= 'a' && firstChar <= 'f')) && ((secondChar >= '0' && secondChar <= '9') || (secondChar >= 'A' && secondChar <= 'F') || (secondChar >= 'a' && secondChar <= 'f'))) { byte b = byte.Parse(s.Substring(i * 2, 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture); bytes[i] = b; } else { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "Utils", "StringToByteArray: invalid string: " + s); return null; } } return bytes; } // // SID Utilities // internal static string ConvertSidToSDDL(byte[] sid) { string sddlSid = null; // To put the byte[] SID into SDDL, we use ConvertSidToStringSid. // Calling that requires we first copy the SID into native memory. IntPtr pSid = IntPtr.Zero; try { pSid = ConvertByteArrayToIntPtr(sid); if (UnsafeNativeMethods.ConvertSidToStringSid(pSid, ref sddlSid)) { return sddlSid; } else { int lastErrorCode = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConvertSidToSDDL: ConvertSidToStringSid failed, " + lastErrorCode); return null; } } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } // The caller must call Marshal.FreeHGlobal on the returned // value to free it. internal static IntPtr ConvertByteArrayToIntPtr(byte[] bytes) { IntPtr pBytes = IntPtr.Zero; pBytes = Marshal.AllocHGlobal(bytes.Length); try { Marshal.Copy(bytes, 0, pBytes, bytes.Length); } catch (Exception e) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "ConvertByteArrayToIntPtr: caught exception of type " + e.GetType().ToString() + " and message " + e.Message); Marshal.FreeHGlobal(pBytes); throw; } Debug.Assert(pBytes != IntPtr.Zero); return pBytes; } internal static byte[] ConvertNativeSidToByteArray(IntPtr pSid) { int sidLength = UnsafeNativeMethods.GetLengthSid(pSid); byte[] sid = new byte[sidLength]; Marshal.Copy(pSid, sid, 0, sidLength); return sid; } internal static SidType ClassifySID(byte[] sid) { IntPtr pSid = IntPtr.Zero; try { pSid = ConvertByteArrayToIntPtr(sid); return ClassifySID(pSid); } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } internal static SidType ClassifySID(IntPtr pSid) { Debug.Assert(UnsafeNativeMethods.IsValidSid(pSid)); // Get the issuing authority and the first RID IntPtr pIdentAuth = UnsafeNativeMethods.GetSidIdentifierAuthority(pSid); UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY identAuth = (UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY)Marshal.PtrToStructure(pIdentAuth, typeof(UnsafeNativeMethods.SID_IDENTIFIER_AUTHORITY)); IntPtr pRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, 0); int rid = Marshal.ReadInt32(pRid); // These bit signify that the sid was issued by ADAM. If so then it can't be a fake sid. if ((identAuth.b3 & 0xF0) == 0x10) return SidType.RealObject; // Is it S-1-5-...? if (!(identAuth.b1 == 0) && (identAuth.b2 == 0) && (identAuth.b3 == 0) && (identAuth.b4 == 0) && (identAuth.b5 == 0) && (identAuth.b6 == 5)) { // No, so it can't be an account or builtin SID. // Probably something like \Everyone or \LOCAL. return SidType.FakeObject; } switch (rid) { case 21: // Account SID return SidType.RealObject; case 32: // BUILTIN SID return SidType.RealObjectFakeDomain; default: return SidType.FakeObject; } } internal static int GetLastRidFromSid(IntPtr pSid) { IntPtr pRidCount = UnsafeNativeMethods.GetSidSubAuthorityCount(pSid); int ridCount = Marshal.ReadByte(pRidCount); IntPtr pLastRid = UnsafeNativeMethods.GetSidSubAuthority(pSid, ridCount - 1); int lastRid = Marshal.ReadInt32(pLastRid); return lastRid; } internal static int GetLastRidFromSid(byte[] sid) { IntPtr pSid = IntPtr.Zero; try { pSid = Utils.ConvertByteArrayToIntPtr(sid); int rid = GetLastRidFromSid(pSid); return rid; } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); } } // // // internal static bool IsSamUser() { // // Basic algorithm // // Get SID of current user (via OpenThreadToken/GetTokenInformation/CloseHandle for TokenUser) // // Is the user SID of the form S-1-5-21-... (does GetSidIdentityAuthority(u) == 5 and GetSidSubauthority(u, 0) == 21)? // If NO ---> is local user // If YES ---> // Get machine domain SID (via LsaOpenPolicy/LsaQueryInformationPolicy for PolicyAccountDomainInformation/LsaClose) // Does EqualDomainSid indicate the current user SID and the machine domain SID have the same domain? // If YES --> // IS the local machine a DC // If NO --> is local user // If YES --> is _not_ local user // If NO --> is _not_ local user // IntPtr pCopyOfUserSid = IntPtr.Zero; IntPtr pMachineDomainSid = IntPtr.Zero; try { // Get the user's SID pCopyOfUserSid = GetCurrentUserSid(); // Is it of S-1-5-21 form: Is the issuing authority NT_AUTHORITY and the RID NT_NOT_UNIQUE? SidType sidType = ClassifySID(pCopyOfUserSid); if (sidType == SidType.RealObject) { // It's a domain SID. Now, is the domain portion for the local machine, or something else? // Get the machine domain SID pMachineDomainSid = GetMachineDomainSid(); // Does the user SID have the same domain as the machine SID? bool sameDomain = false; bool success = UnsafeNativeMethods.EqualDomainSid(pCopyOfUserSid, pMachineDomainSid, ref sameDomain); // Since both pCopyOfUserSid and pMachineDomainSid should always be account SIDs Debug.Assert(success == true); // If user SID is the same domain as the machine domain, and the machine is not a DC then the user is a local (machine) user return sameDomain ? !IsMachineDC(null) : false; } else { // It's not a domain SID, must be local (e.g., NT AUTHORITY\foo, or BUILTIN\foo) return true; } } finally { if (pCopyOfUserSid != IntPtr.Zero) Marshal.FreeHGlobal(pCopyOfUserSid); if (pMachineDomainSid != IntPtr.Zero) Marshal.FreeHGlobal(pMachineDomainSid); } } internal static IntPtr GetCurrentUserSid() { IntPtr pTokenHandle = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; try { // // Get the current user's SID // int error = 0; // Get the current thread's token if (!UnsafeNativeMethods.OpenThreadToken( UnsafeNativeMethods.GetCurrentThread(), 0x8, // TOKEN_QUERY true, ref pTokenHandle )) { if ((error = Marshal.GetLastWin32Error()) == 1008) // ERROR_NO_TOKEN { Debug.Assert(pTokenHandle == IntPtr.Zero); // Current thread doesn't have a token, try the process if (!UnsafeNativeMethods.OpenProcessToken( UnsafeNativeMethods.GetCurrentProcess(), 0x8, // TOKEN_QUERY ref pTokenHandle )) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenProcessToken failed, gle=" + lastError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToOpenToken, lastError)); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenThreadToken failed, gle=" + error); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToOpenToken, error)); } } Debug.Assert(pTokenHandle != IntPtr.Zero); int neededBufferSize = 0; // Retrieve the user info from the current thread's token // First, determine how big a buffer we need. bool success = UnsafeNativeMethods.GetTokenInformation( pTokenHandle, 1, // TokenUser IntPtr.Zero, 0, ref neededBufferSize); int getTokenInfoError = 0; if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (1st try) failed, gle=" + getTokenInfoError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, getTokenInfoError)); } // Allocate the necessary buffer. Debug.Assert(neededBufferSize > 0); pBuffer = Marshal.AllocHGlobal(neededBufferSize); // Load the user info into the buffer success = UnsafeNativeMethods.GetTokenInformation( pTokenHandle, 1, // TokenUser pBuffer, neededBufferSize, ref neededBufferSize); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (2nd try) failed, neededBufferSize=" + neededBufferSize + ", gle=" + lastError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError)); } // Retrieve the user's SID from the user info UnsafeNativeMethods.TOKEN_USER tokenUser = (UnsafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_USER)); IntPtr pUserSid = tokenUser.sidAndAttributes.pSid; // this is a reference into the NATIVE memory (into pBuffer) Debug.Assert(UnsafeNativeMethods.IsValidSid(pUserSid)); // Now we make a copy of the SID to return int userSidLength = UnsafeNativeMethods.GetLengthSid(pUserSid); IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength); success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: CopySid failed, errorcode=" + lastError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError)); } return pCopyOfUserSid; } finally { if (pTokenHandle != IntPtr.Zero) UnsafeNativeMethods.CloseHandle(pTokenHandle); if (pBuffer != IntPtr.Zero) Marshal.FreeHGlobal(pBuffer); } } internal static IntPtr GetMachineDomainSid() { IntPtr pPolicyHandle = IntPtr.Zero; IntPtr pBuffer = IntPtr.Zero; IntPtr pOA = IntPtr.Zero; try { UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES oa = new UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES(); pOA = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(UnsafeNativeMethods.LSA_OBJECT_ATTRIBUTES))); Marshal.StructureToPtr(oa, pOA, false); int err = UnsafeNativeMethods.LsaOpenPolicy( IntPtr.Zero, pOA, 1, // POLICY_VIEW_LOCAL_INFORMATION ref pPolicyHandle); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaOpenPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err)); throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrievePolicy, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pPolicyHandle != IntPtr.Zero); err = UnsafeNativeMethods.LsaQueryInformationPolicy( pPolicyHandle, 5, // PolicyAccountDomainInformation ref pBuffer); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaQueryInformationPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err)); throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrievePolicy, SafeNativeMethods.LsaNtStatusToWinError(err))); } Debug.Assert(pBuffer != IntPtr.Zero); UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO info = (UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO) Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.POLICY_ACCOUNT_DOMAIN_INFO)); Debug.Assert(UnsafeNativeMethods.IsValidSid(info.domainSid)); // Now we make a copy of the SID to return int sidLength = UnsafeNativeMethods.GetLengthSid(info.domainSid); IntPtr pCopyOfSid = Marshal.AllocHGlobal(sidLength); bool success = UnsafeNativeMethods.CopySid(sidLength, pCopyOfSid, info.domainSid); if (!success) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: CopySid failed, errorcode=" + lastError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrievePolicy, lastError)); } return pCopyOfSid; } finally { if (pPolicyHandle != IntPtr.Zero) UnsafeNativeMethods.LsaClose(pPolicyHandle); if (pBuffer != IntPtr.Zero) UnsafeNativeMethods.LsaFreeMemory(pBuffer); if (pOA != IntPtr.Zero) Marshal.FreeHGlobal(pOA); } } // Returns name in the form "domain\user" internal static string GetNT4UserName() { using (WindowsIdentity currentIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()) { string s = currentIdentity.Name; GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "GetNT4UserName: name is " + s); return s; } } internal static string GetComputerFlatName() { //string s = System.Windows.Forms.SystemInformation.ComputerName; string s = Environment.MachineName; GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "GetComputerFlatName: name is " + s); return s; } // // Interop support // internal static UnsafeNativeMethods.DomainControllerInfo GetDcName(string computerName, string domainName, string siteName, int flags) { IntPtr domainControllerInfoPtr = IntPtr.Zero; try { int err = UnsafeNativeMethods.DsGetDcName(computerName, domainName, IntPtr.Zero, siteName, flags, out domainControllerInfoPtr); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetDcName: DsGetDcName failed, err=" + err); throw new PrincipalOperationException( string.Format( CultureInfo.CurrentCulture, SR.UnableToRetrieveDomainInfo, err)); } UnsafeNativeMethods.DomainControllerInfo domainControllerInfo = (UnsafeNativeMethods.DomainControllerInfo)Marshal.PtrToStructure(domainControllerInfoPtr, typeof(UnsafeNativeMethods.DomainControllerInfo)); return domainControllerInfo; } finally { if (domainControllerInfoPtr != IntPtr.Zero) UnsafeNativeMethods.NetApiBufferFree(domainControllerInfoPtr); } } internal static int LookupSid(string serverName, NetCred credentials, byte[] sid, out string name, out string domainName, out int accountUsage) { IntPtr pSid = IntPtr.Zero; int nameLength = 0; int domainNameLength = 0; StringBuilder sbName; StringBuilder sbDomainName; accountUsage = 0; name = null; domainName = null; IntPtr hUser = IntPtr.Zero; try { pSid = ConvertByteArrayToIntPtr(sid); Utils.BeginImpersonation(credentials, out hUser); // hUser could be null if no credentials were specified Debug.Assert(hUser != IntPtr.Zero || (credentials == null || (credentials.UserName == null && credentials.Password == null))); bool f = UnsafeNativeMethods.LookupAccountSid(serverName, pSid, null, ref nameLength, null, ref domainNameLength, ref accountUsage); int lastErr = Marshal.GetLastWin32Error(); if (lastErr != 122) // ERROR_INSUFFICIENT_BUFFER { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "LookupSid: LookupAccountSid (1st try) failed, gle=" + lastErr); return lastErr; } Debug.Assert(f == false); // should never succeed, with a 0 buffer size Debug.Assert(nameLength > 0); Debug.Assert(domainNameLength > 0); sbName = new StringBuilder(nameLength); sbDomainName = new StringBuilder(domainNameLength); f = UnsafeNativeMethods.LookupAccountSid(serverName, pSid, sbName, ref nameLength, sbDomainName, ref domainNameLength, ref accountUsage); if (f == false) { lastErr = Marshal.GetLastWin32Error(); Debug.Assert(lastErr != 0); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "LookupSid: LookupAccountSid (2nd try) failed, gle=" + lastErr); return lastErr; } name = sbName.ToString(); domainName = sbDomainName.ToString(); return 0; } finally { if (pSid != IntPtr.Zero) Marshal.FreeHGlobal(pSid); if (hUser != IntPtr.Zero) Utils.EndImpersonation(hUser); } } static internal Principal ConstructFakePrincipalFromSID( byte[] sid, PrincipalContext ctx, string serverName, NetCred credentials, string authorityName) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "Utils", "ConstructFakePrincipalFromSID: Build principal for SID={0}, server={1}, authority={2}", Utils.ByteArrayToString(sid), (serverName != null ? serverName : "NULL"), (authorityName != null ? authorityName : "NULL")); Debug.Assert(ClassifySID(sid) == SidType.FakeObject); // Get the name for it string nt4Name = ""; int accountUsage = 0; string name; string domainName; int err = Utils.LookupSid(serverName, credentials, sid, out name, out domainName, out accountUsage); if (err == 0) { // If it failed, we'll just live without a name //Debug.Assert(accountUsage == 5 /*WellKnownGroup*/); nt4Name = (!string.IsNullOrEmpty(domainName) ? domainName + "\\" : "") + name; } else { GlobalDebug.WriteLineIf( GlobalDebug.Warn, "Utils", "ConstructFakePrincipalFromSID: LookupSid failed (ignoring), serverName=" + serverName + ", err=" + err); } // Since LookupAccountSid indicates all of the NT AUTHORITY, etc., SIDs are WellKnownGroups, // we'll map them all to Group. // Create a Principal object to represent it GroupPrincipal g = GroupPrincipal.MakeGroup(ctx); g.fakePrincipal = true; g.unpersisted = false; // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalDisplayName, nt4Name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalName, name); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSamAccountName, name); // SID IdentityClaim SecurityIdentifier sidObj = new SecurityIdentifier(Utils.ConvertSidToSDDL(sid)); // Set the display name on the object g.LoadValueIntoProperty(PropertyNames.PrincipalSid, sidObj); g.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, true); return g; } // // Impersonation // internal static bool BeginImpersonation(NetCred credential, out IntPtr hUserToken) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "Entering BeginImpersonation"); hUserToken = IntPtr.Zero; IntPtr hToken = IntPtr.Zero; // default credential is specified, no need to do impersonation if (credential == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate"); return false; } // Retrive the parsed username which has had the domain removed because LogonUser // expects creds this way. string userName = credential.ParsedUserName; string password = credential.Password; string domainName = credential.Domain; // no need to do impersonation as username and password are both null if (userName == null && password == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: nothing to impersonate (2)"); return false; } GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "BeginImpersonation: trying to impersonate " + userName); int result = UnsafeNativeMethods.LogonUser( userName, domainName, password, 9, /* LOGON32_LOGON_NEW_CREDENTIALS */ 3, /* LOGON32_PROVIDER_WINNT50 */ ref hToken); // check the result if (result == 0) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: LogonUser failed, gle=" + lastError); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToImpersonateCredentials, lastError)); } result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken); if (result == 0) { int lastError = Marshal.GetLastWin32Error(); GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: ImpersonateLoggedOnUser failed, gle=" + lastError); // Close the token the was created above.... UnsafeNativeMethods.CloseHandle(hToken); throw new PrincipalOperationException( string.Format(CultureInfo.CurrentCulture, SR.UnableToImpersonateCredentials, lastError)); } hUserToken = hToken; return true; } internal static void EndImpersonation(IntPtr hUserToken) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "Utils", "Entering EndImpersonation"); UnsafeNativeMethods.RevertToSelf(); UnsafeNativeMethods.CloseHandle(hUserToken); } internal static bool IsMachineDC(string computerName) { IntPtr dsRoleInfoPtr = IntPtr.Zero; int err = -1; try { if (null == computerName) err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(null, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); else err = UnsafeNativeMethods.DsRoleGetPrimaryDomainInformation(computerName, UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.DsRolePrimaryDomainInfoBasic, out dsRoleInfoPtr); if (err != 0) { GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "IsMachineDC: DsRoleGetPrimaryDomainInformation failed, err=" + err); throw new PrincipalOperationException( string.Format( CultureInfo.CurrentCulture, SR.UnableToRetrieveDomainInfo, err)); } UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC dsRolePrimaryDomainInfo = (UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)Marshal.PtrToStructure(dsRoleInfoPtr, typeof(UnsafeNativeMethods.DSROLE_PRIMARY_DOMAIN_INFO_BASIC)); return (dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RoleBackupDomainController || dsRolePrimaryDomainInfo.MachineRole == UnsafeNativeMethods.DSROLE_MACHINE_ROLE.DsRole_RolePrimaryDomainController); } finally { if (dsRoleInfoPtr != IntPtr.Zero) UnsafeNativeMethods.DsRoleFreeMemory(dsRoleInfoPtr); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using Trionic5Tools; namespace Trionic5Controls { public enum InjectionType : int { Normal = 0, Knocking, Idle } public partial class frmInjectionTiming : DevExpress.XtraEditors.XtraForm { private InjectionType m_viewtype = InjectionType.Normal; private MapSensorType m_mapSensor = MapSensorType.MapSensor25; public MapSensorType MapSensor { get { return m_mapSensor; } set { m_mapSensor = value; } } private int batt_volt = 13; private int min_tid = 0; public int Min_tid { get { return min_tid; } set { min_tid = value; } } private int[] batt_korr_tab; public int[] Batt_korr_tab { get { return batt_korr_tab; } set { batt_korr_tab = value; } } private int[] temp_steg; public int[] Temp_steg { get { return temp_steg; } set { temp_steg = value; } } private int[] kyltemp_steg; public int[] Kyltemp_steg { get { return kyltemp_steg; } set { kyltemp_steg = value; } } private int[] kyltemp_tab; public int[] Kyltemp_tab { get { return kyltemp_tab; } set { kyltemp_tab = value; } } private int[] lufttemp_steg; public int[] Lufttemp_steg { get { return lufttemp_steg; } set { lufttemp_steg = value; } } private int[] luft_kompfak; public int[] Luft_kompfak { get { return luft_kompfak; } set { luft_kompfak = value; } } private int[] lufttemp_tab; public int[] Lufttemp_tab { get { return lufttemp_tab; } set { lufttemp_tab = value; } } private int[] fuel_map_x_axis; public int[] Fuel_map_x_axis { get { return fuel_map_x_axis; } set { fuel_map_x_axis = value; } } private int[] fuel_map_y_axis; public int[] Fuel_map_y_axis { get { return fuel_map_y_axis; } set { fuel_map_y_axis = value; } } private int[] fuel_knock_map_x_axis; public int[] Fuel_knock_map_x_axis { get { return fuel_knock_map_x_axis; } set { fuel_knock_map_x_axis = value; } } private int[] fuel_knock_map_y_axis; public int[] Fuel_knock_map_y_axis { get { return fuel_knock_map_y_axis; } set { fuel_knock_map_y_axis = value; } } private byte[] insp_mat; public byte[] Insp_mat { get { return insp_mat; } set { insp_mat = value; } } private byte[] fuel_knock_mat; public byte[] Fuel_knock_mat { get { return fuel_knock_mat; } set { fuel_knock_mat = value; } } private byte[] idle_fuel_map; public byte[] Idle_fuel_map { get { return idle_fuel_map; } set { idle_fuel_map = value; } } private int[] idle_fuel_y_axis; public int[] Idle_fuel_y_axis { get { return idle_fuel_y_axis; } set { idle_fuel_y_axis = value; } } private int[] idle_fuel_x_axis; public int[] Idle_fuel_x_axis { get { return idle_fuel_x_axis; } set { idle_fuel_x_axis = value; } } private int inj_konst = 21; public int Inj_konst { get { return inj_konst; } set { inj_konst = value; spinEdit1.EditValue = inj_konst; } } private int m_iat = 46; // 60 degrees public frmInjectionTiming() { InitializeComponent(); gridView1.IndicatorWidth = 40; } private int LookupCoolantTemperature(int axisvalue) { // find index in Kyltemp_steg int index = -1; int retval = -1; int smallestdiff = 256; int idx = 0; int secondvalue = -1; try { foreach (int i in Kyltemp_steg) { if (Math.Abs(i - axisvalue) < smallestdiff) { index = idx; smallestdiff = (int)Math.Abs(i - axisvalue); if (i < axisvalue) { secondvalue = (int)Kyltemp_steg.GetValue(idx + 1); } else { secondvalue = (int)Kyltemp_steg.GetValue(idx - 1); } } idx++; } if (index >= 0 && index < Kyltemp_tab.Length) { // get value from Kyltemp_tab retval = (int)Kyltemp_tab.GetValue(index); int firstvalue = (int)Kyltemp_steg.GetValue(index); int sval = -1000; int diff = (int)Math.Abs(secondvalue - firstvalue); int diff2 = axisvalue - firstvalue; double percentage = (double)diff2 / (double)diff; if (secondvalue > firstvalue) { // dan moeten we de volgende uit kyltemp_tab ook hebben sval = (int)Kyltemp_tab.GetValue(index + 1); percentage = (double)diff2 / (double)diff; } else { sval = (int)Kyltemp_tab.GetValue(index - 1); percentage = (double)diff2 / (double)diff; percentage = -percentage; } // hoeveel interpoleren? retval += (int)((double)percentage * (double)(sval - retval)); retval -= 40; } } catch (Exception E) { Console.WriteLine(E.Message); } Console.WriteLine("looked for : " + axisvalue.ToString() + " found idx in kyltemp_steg : " + index.ToString() + " value in kyltemp_tab: " + retval.ToString()); return retval; } private int LookupAirTemperature(int axisvalue) { // find index in Lufttemp_steg int index = -1; int retval = -1; int smallestdiff = 256; int idx = 0; int secondvalue = -1; try { foreach (int i in Lufttemp_steg) { if (Math.Abs(i - axisvalue) < smallestdiff) { index = idx; smallestdiff = (int)Math.Abs(i - axisvalue); try { if (i < axisvalue) { secondvalue = (int)Lufttemp_steg.GetValue(idx + 1); } else { secondvalue = (int)Lufttemp_steg.GetValue(idx - 1); } } catch (Exception sE) { Console.WriteLine(sE.Message); } } idx++; } if (index >= 0 && index < Lufttemp_tab.Length) { // get value from Lufttemp_tab retval = (int)Lufttemp_tab.GetValue(index); int firstvalue = (int)Lufttemp_steg.GetValue(index); int sval = -1000; int diff = (int)Math.Abs(secondvalue - firstvalue); int diff2 = axisvalue - firstvalue; double percentage = (double)diff2 / (double)diff; if (secondvalue >= 0) { if (secondvalue > firstvalue) { // dan moeten we de volgende uit Lufttemp_tab ook hebben sval = (int)Lufttemp_tab.GetValue(index + 1); percentage = (double)diff2 / (double)diff; } else { sval = (int)Lufttemp_tab.GetValue(index - 1); percentage = (double)diff2 / (double)diff; percentage = -percentage; } // hoeveel interpoleren? retval += (int)((double)percentage * (double)(sval - retval)); } retval -= 40; } } catch (Exception E) { Console.WriteLine(E.Message); } return retval; } public void CalculateInjectionTiming(InjectionType type) { gridView1.Columns.Clear(); switch (type) { case InjectionType.Normal: if (fuel_map_x_axis.Length > 0 && fuel_map_y_axis.Length > 0 && insp_mat.Length > 0) { // fill table DataTable dt = new DataTable(); object[] vals = new object[fuel_map_x_axis.Length]; int idx = 0; foreach (int pressure in fuel_map_x_axis) { dt.Columns.Add(pressure.ToString()); } int rpm_index = 0; for(int i = fuel_map_y_axis.Length -1; i >= 0; i --) //foreach (int rpm in fuel_map_y_axis) { int rpm = fuel_map_y_axis[i]; int mapindex = 0; foreach (int pressureit in fuel_map_x_axis) { int pressure = pressureit; if (m_mapSensor == MapSensorType.MapSensor30) { pressure *= 120; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor35) { pressure *= 140; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor40) { pressure *= 160; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor50) { pressure *= 200; pressure /= 100; } int Lufttemp_faktor = GetLuftTempFactor(m_iat); int P_manifold10 = pressure * 10; int Last = 0; int Medellast = 0; if ((((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512) < 255) { Last = ((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512; } else { Last = 255; } Medellast = Last; //Console.WriteLine(pressure.ToString() + " gives medellast: " + Medellast.ToString()); int cellvalue = (int)Handle_tables(rpm, (byte)Medellast, fuel_map_y_axis.Length, fuel_map_x_axis.Length, insp_mat, fuel_map_y_axis, fuel_map_x_axis); int injection_duration = CalculateInjectionTime(pressure, m_iat); float inj_dur_ms = injection_duration * (((float)cellvalue + 128) / 256); if (batt_volt >= 14) { batt_volt = 14; } else if (batt_volt < 5) { batt_volt = 4; } int Batt_korr = Batt_korr_tab[14 - batt_volt]; inj_dur_ms += Batt_korr; if (inj_dur_ms >= 32500) { inj_dur_ms = 32500; } if (inj_dur_ms <= min_tid) { inj_dur_ms = min_tid; } float Injection_timems10 = inj_dur_ms / 25; float temp = 6000000 / (float)rpm; //float dutycycle = ((Injection_timems10) / temp) * 100; inj_dur_ms /= 250; float dutycycle = (rpm * inj_dur_ms) / 1200; // for fun, take Fload_tab into account //Console.WriteLine("InjTiming Converting pressure: " + pressure.ToString() + " rpm: " + rpm.ToString() + " dc: " + dutycycle.ToString() + " ms: " + inj_dur_ms.ToString()); vals.SetValue(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2"), mapindex); //Console.WriteLine(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2") + " mapidx: " + mapindex.ToString()); mapindex++; } dt.Rows.Add(vals); rpm_index++; } gridControl1.DataSource = dt; } break; case InjectionType.Knocking: if (fuel_knock_map_x_axis.Length > 0 && fuel_knock_map_y_axis.Length > 0 && fuel_knock_mat.Length > 0) { // fill table DataTable dt = new DataTable(); object[] vals = new object[fuel_knock_map_x_axis.Length]; int idx = 0; foreach (int pressure in fuel_knock_map_x_axis) { dt.Columns.Add(pressure.ToString()); } int rpm_index = 0; for (int i = fuel_knock_map_y_axis.Length - 1; i >= 0; i--) //foreach (int rpm in fuel_map_y_axis) { int rpm = fuel_knock_map_y_axis[i]; int mapindex = 0; foreach (int pressureit in fuel_knock_map_x_axis) { int pressure = pressureit; if (m_mapSensor == MapSensorType.MapSensor30) { pressure *= 120; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor35) { pressure *= 140; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor40) { pressure *= 160; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor50) { pressure *= 200; pressure /= 100; } int Lufttemp_faktor = GetLuftTempFactor(m_iat); int P_manifold10 = pressure * 10; int Last = 0; int Medellast = 0; if ((((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512) < 255) { Last = ((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512; } else { Last = 255; } Medellast = Last; int cellvalue = (int)Handle_tables(rpm, (byte)Medellast, fuel_knock_map_y_axis.Length, fuel_knock_map_x_axis.Length, fuel_knock_mat, fuel_knock_map_y_axis, fuel_knock_map_x_axis); int injection_duration = CalculateInjectionTime(pressure, m_iat); float inj_dur_ms = injection_duration * (((float)cellvalue + 128) / 256); if (batt_volt >= 14) { batt_volt = 14; } else if (batt_volt < 5) { batt_volt = 4; } int Batt_korr = Batt_korr_tab[14 - batt_volt]; inj_dur_ms += Batt_korr; if (inj_dur_ms >= 32500) { inj_dur_ms = 32500; } if (inj_dur_ms <= min_tid) { inj_dur_ms = min_tid; } float Injection_timems10 = inj_dur_ms / 25; float temp = 6000000 / (float)rpm; //float dutycycle = ((float)(Injection_timems10) / temp) * 100; inj_dur_ms /= 250; float dutycycle = (rpm * inj_dur_ms) / 1200; vals.SetValue(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2"), mapindex); //Console.WriteLine(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2") + " mapidx: " + mapindex.ToString()); mapindex++; } dt.Rows.Add(vals); rpm_index++; } gridControl1.DataSource = dt; } break; case InjectionType.Idle: if (idle_fuel_x_axis.Length > 0 && idle_fuel_y_axis.Length > 0 && idle_fuel_map.Length > 0) { // fill table DataTable dt = new DataTable(); object[] vals = new object[idle_fuel_x_axis.Length]; int idx = 0; foreach (int pressure in idle_fuel_x_axis) { dt.Columns.Add(pressure.ToString()); } int rpm_index = 0; for (int i = idle_fuel_y_axis.Length - 1; i >= 0; i--) //foreach (int rpm in fuel_map_y_axis) { int rpm = idle_fuel_y_axis[i]; int mapindex = 0; foreach (int pressureit in idle_fuel_x_axis) { int pressure = pressureit; if (m_mapSensor == MapSensorType.MapSensor30) { pressure *= 120; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor35) { pressure *= 140; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor40) { pressure *= 160; pressure /= 100; } else if (m_mapSensor == MapSensorType.MapSensor50) { pressure *= 200; pressure /= 100; } int Lufttemp_faktor = GetLuftTempFactor(m_iat); int P_manifold10 = pressure * 10; int Last = 0; int Medellast = 0; if ((((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512) < 255) { Last = ((Lufttemp_faktor + 384) * (P_manifold10 / 10)) / 512; } else { Last = 255; } Medellast = Last; int cellvalue = (int)Handle_tables(rpm, (byte)Medellast, idle_fuel_y_axis.Length, idle_fuel_x_axis.Length, idle_fuel_map, idle_fuel_y_axis, idle_fuel_x_axis); int injection_duration = CalculateInjectionTime(pressure, m_iat); float inj_dur_ms = injection_duration * (((float)cellvalue + 128) / 256); if (batt_volt >= 14) { batt_volt = 14; } else if (batt_volt < 5) { batt_volt = 4; } int Batt_korr = Batt_korr_tab[14 - batt_volt]; inj_dur_ms += Batt_korr; if (inj_dur_ms >= 32500) { inj_dur_ms = 32500; } if (inj_dur_ms <= min_tid) { inj_dur_ms = min_tid; } float Injection_timems10 = inj_dur_ms / 25; float temp = 6000000 / (float)rpm; //float dutycycle = ((float)(Injection_timems10) / temp) * 100; inj_dur_ms /= 250; float dutycycle = (rpm * inj_dur_ms) / 1200; vals.SetValue(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2"), mapindex); //Console.WriteLine(inj_dur_ms.ToString("F2") + "/" + dutycycle.ToString("F2") + " mapidx: " + mapindex.ToString()); mapindex++; } dt.Rows.Add(vals); rpm_index++; } gridControl1.DataSource = dt; } break; } } private int CalculateInjectionTime(int pressure, int m_iat) { //pressure *= 10; // must be P_manifold10 int grund_tid = inj_konst * ((GetLuftTempFactor(m_iat) + 384) * pressure) / 512; return grund_tid; //(Insp_mat+128)/256 } private int GetLuftTempFactor(int m_iat) { //P_manifold_LTF = ((Lufttemp_faktor + 384) * P_manifold10) / 512; //return 100; int Lufttemp_faktor = Handle_temp_tables(m_iat, luft_kompfak,lufttemp_steg); return Lufttemp_faktor; //int Lufttemp_faktor = LookupAirTemperature(m_iat); //return Lufttemp_faktor; } private int Handle_temp_tables(int AD_value, int[] tab, int[] steg) { int steg_index = 0; int steg_value; int ret_value; /*find steg index*/ while (steg[steg_index] != 255) { if (steg[steg_index] >= AD_value) { break; } steg_index++; } if (steg_index == 0) { ret_value = tab[0]; } else { steg_index--; if (tab[steg_index + 1] > tab[steg_index]) { //check ret_value = tab[steg_index] + (((tab[steg_index + 1] - tab[steg_index]) * (AD_value - steg[steg_index])) / (steg[steg_index + 1] - steg[steg_index])); } else { ret_value = tab[steg_index] - (((tab[steg_index] - tab[steg_index + 1]) * (AD_value - steg[steg_index])) / (steg[steg_index + 1] - steg[steg_index])); } }/*Handle temp tables*/ return ret_value; } private byte Handle_tables(int y_value, byte x_value, int y_count, int x_count, byte[] matrix, int[] y_axis, int[] x_axis) { byte value; byte tmp1; byte tmp2; byte tmp3, vx, vy; byte x_indx; byte y_indx; int y_delta; byte x_delta; byte x_interpol; byte y_interpol; /*find y-index*/ y_indx = 0; while (y_indx <= y_count - 1) { if (y_axis[y_indx] > y_value) { break; } y_indx++; } /*find x-index*/ x_indx = 0; while (x_indx <= x_count - 1) { if (x_axis[x_indx] > x_value) { break; } x_indx++; } if (x_indx > 0) x_indx--; if (y_indx > 0) y_indx--; tmp1 = matrix[(y_indx * x_count) + x_indx]; if (y_indx < y_count - 1) { tmp2 = matrix[(y_indx + 1) * x_count + x_indx]; } else { tmp2 = tmp1; } if (x_indx < x_count - 1) { tmp3 = matrix[(y_indx * x_count) + (x_indx + 1)]; } else { tmp3 = tmp1; } //trionic style x&y if (x_indx < x_count-1 && y_indx < y_count-1) { vx = interpolate2((tmp3 - tmp1), (x_axis[x_indx + 1] - x_axis[x_indx]), (x_value - x_axis[x_indx]), tmp1); vy = interpolate2((tmp2 - tmp1), (y_axis[y_indx + 1] - y_axis[y_indx]), (y_value - y_axis[y_indx]), tmp1); } else { vx = interpolate2((tmp3 - tmp1), (x_axis[x_indx ] - x_axis[x_indx]), (x_value - x_axis[x_indx]), tmp1); vy = interpolate2((tmp2 - tmp1), (y_axis[y_indx ] - y_axis[y_indx]), (y_value - y_axis[y_indx]), tmp1); } //printf("vx=0x%x vy=0x%x\n",vx,vy); //todo: interpolate vx and vy value = (byte)((vy + vx) / 2); // value=interpolate2(,tmp1); return value; } private byte interpolate2(int tmp1, int tmp2, int tmp3, int tmp4) { byte retval = 0; try { if (tmp2 != 0) { retval = (byte)(((tmp1 * tmp3) / tmp2) + tmp4); } else { retval = (byte)tmp4; } } catch (Exception E) { Console.WriteLine(E.Message); } return retval; } private void simpleButton1_Click(object sender, EventArgs e) { this.Close(); } private void RecalculateValues(InjectionType type) { CalculateInjectionTiming(type); } private void comboBoxEdit1_SelectedIndexChanged_1(object sender, EventArgs e) { switch (comboBoxEdit1.SelectedIndex) { case 0: //-30 m_iat = 230; break; case 1: //-10 m_iat = 199; break; case 2: // 20 m_iat = 163; break; case 3: // 40 m_iat = 77; break; case 4: // 60 m_iat = 46; break; case 5: // 80 m_iat = 36; break; } RecalculateValues(m_viewtype); } private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e) { switch (comboBoxEdit2.SelectedIndex) { case 0: // normal m_viewtype = InjectionType.Normal; break; case 2: // knock m_viewtype = InjectionType.Knocking; break; case 1: // idle m_viewtype = InjectionType.Idle; break; } RecalculateValues(m_viewtype); } private void comboBoxEdit3_SelectedIndexChanged(object sender, EventArgs e) { try { batt_volt = Convert.ToInt32(comboBoxEdit3.Text); } catch (Exception E) { Console.WriteLine(E.Message); } comboBoxEdit3.Text = batt_volt.ToString(); RecalculateValues(m_viewtype); } private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) { try { string str = (string)e.CellValue; char[] sep = new char[1]; sep.SetValue('/', 0); string[] vals = str.Split(sep); double v = Convert.ToDouble(vals.GetValue(0)); int b = (int)v; e.DisplayText = v.ToString(); double dc = Convert.ToDouble(vals.GetValue(1)); if (comboBoxEdit4.SelectedIndex == 1) { e.DisplayText = dc.ToString(); } b *= 8; if (b < 0) b = -b; if (b > 255) b = 255; Color c = Color.FromArgb(b, Color.Red); int width = (int)(e.Bounds.Width * dc) / 100; //Color c = Color.FromArgb(r, 128, 128); SolidBrush sb = new SolidBrush(c); e.Graphics.FillRectangle(sb, e.Bounds /* new Rectangle(e.Bounds.X, e.Bounds.Y, width, e.Bounds.Height)*/); // draw DC in bottom of cell System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.Green, Color.Red, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, new Rectangle(e.Bounds.X, e.Bounds.Y + e.Bounds.Height - 3, width, 4)); } catch (Exception E) { Console.WriteLine(E.Message); } } private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { bool m_isUpsideDown = true; if (e.RowHandle >= 0) { try { switch (m_viewtype) { case InjectionType.Normal: if (fuel_map_y_axis.Length > 0) { if (fuel_map_y_axis.Length > e.RowHandle) { string yvalue = fuel_map_y_axis.GetValue((fuel_map_y_axis.Length - 1) - e.RowHandle).ToString(); if (!m_isUpsideDown) { // dan andere waarde nemen yvalue = fuel_map_y_axis.GetValue(e.RowHandle).ToString(); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); e.Graphics.DrawString(yvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 4, e.Bounds.Y + 1 + (e.Bounds.Height- 12) / 2)); e.Handled = true; } } break; case InjectionType.Knocking: if (fuel_knock_map_y_axis.Length > 0) { if (fuel_knock_map_y_axis.Length > e.RowHandle) { string yvalue = fuel_knock_map_y_axis.GetValue((fuel_knock_map_y_axis.Length - 1) - e.RowHandle).ToString(); if (!m_isUpsideDown) { // dan andere waarde nemen yvalue = fuel_knock_map_y_axis.GetValue(e.RowHandle).ToString(); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); e.Graphics.DrawString(yvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 4, e.Bounds.Y + 1 + (e.Bounds.Height - 12) / 2)); e.Handled = true; } } break; case InjectionType.Idle: if (idle_fuel_y_axis.Length > 0) { if (idle_fuel_y_axis.Length > e.RowHandle) { string yvalue = idle_fuel_y_axis.GetValue((idle_fuel_y_axis.Length - 1) - e.RowHandle).ToString(); if (!m_isUpsideDown) { // dan andere waarde nemen yvalue = idle_fuel_y_axis.GetValue(e.RowHandle).ToString(); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); e.Graphics.DrawString(yvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 4, e.Bounds.Y + 1 + (e.Bounds.Height - 12) / 2)); e.Handled = true; } } break; } } catch (Exception E) { Console.WriteLine(E.Message); } } } private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e) { try { switch (m_viewtype) { case InjectionType.Normal: if (fuel_map_x_axis.Length > e.Column.VisibleIndex) { string xvalue = fuel_map_x_axis.GetValue(e.Column.VisibleIndex).ToString(); try { float v = (float)Convert.ToDouble(xvalue); switch (m_mapSensor) { case MapSensorType.MapSensor30: v *= 1.2F; break; case MapSensorType.MapSensor35: v *= 1.4F; break; case MapSensorType.MapSensor40: v *= 1.6F; break; case MapSensorType.MapSensor50: v *= 2.0F; break; } v *= (float)0.01F; v -= 1; xvalue = v.ToString("F2"); } catch (Exception cE) { Console.WriteLine(cE.Message); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); //e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, r); e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 3, e.Bounds.Y + 1 + (e.Bounds.Height- 12) / 2)); e.Handled = true; } break; case InjectionType.Knocking: if (fuel_knock_map_x_axis.Length > e.Column.VisibleIndex) { string xvalue = fuel_knock_map_x_axis.GetValue(e.Column.VisibleIndex).ToString(); try { float v = (float)Convert.ToDouble(xvalue); switch (m_mapSensor) { case MapSensorType.MapSensor30: v *= 1.2F; break; case MapSensorType.MapSensor35: v *= 1.4F; break; case MapSensorType.MapSensor40: v *= 1.6F; break; case MapSensorType.MapSensor50: v *= 2.0F; break; } v *= (float)0.01F; v -= 1; xvalue = v.ToString("F2"); } catch (Exception cE) { Console.WriteLine(cE.Message); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); //e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, r); e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 3, e.Bounds.Y + 1 + (e.Bounds.Height - 12) / 2)); e.Handled = true; } break; case InjectionType.Idle: if (idle_fuel_x_axis.Length > e.Column.VisibleIndex) { string xvalue = idle_fuel_x_axis.GetValue(e.Column.VisibleIndex).ToString(); try { float v = (float)Convert.ToDouble(xvalue); switch (m_mapSensor) { case MapSensorType.MapSensor30: v *= 1.2F; break; case MapSensorType.MapSensor35: v *= 1.4F; break; case MapSensorType.MapSensor40: v *= 1.6F; break; case MapSensorType.MapSensor50: v *= 2.0F; break; } v *= (float)0.01F; v -= 1; xvalue = v.ToString("F2"); } catch (Exception cE) { Console.WriteLine(cE.Message); } Rectangle r = new Rectangle(e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2); e.Graphics.DrawRectangle(Pens.LightSteelBlue, r); System.Drawing.Drawing2D.LinearGradientBrush gb = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, e.Appearance.BackColor2, e.Appearance.BackColor2, System.Drawing.Drawing2D.LinearGradientMode.Horizontal); e.Graphics.FillRectangle(gb, e.Bounds); //e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, r); e.Graphics.DrawString(xvalue, this.Font, Brushes.MidnightBlue, new PointF(e.Bounds.X + 3, e.Bounds.Y + 1 + (e.Bounds.Height - 12) / 2)); e.Handled = true; } break; } } catch (Exception E) { Console.WriteLine(E.Message); } } private void spinEdit1_EditValueChanged(object sender, EventArgs e) { inj_konst = Convert.ToInt32(spinEdit1.EditValue); RecalculateValues(m_viewtype); } private void comboBoxEdit4_SelectedIndexChanged(object sender, EventArgs e) { RecalculateValues(m_viewtype); } } }
/* Game Data Script v1.0 Is attached to Persistant GameData Object And stores Statistics which * are needed across scenes also saves and loads vital data to a binary file. * written by Jonathan Ward modified 09/10/14 */ using UnityEngine; using System.Collections; using System; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public class GameData : MonoBehaviour { #region variables public static GameData instance; //Ship Prefabs public GameObject LunarPrefab; public GameObject TyrantPrefab; public GameObject GothicPrefab; public GameObject DauntlessPrefab; public GameObject MurderPrefab; public GameObject CarnagePrefab; public GameObject SlaughterPrefab; //player Prefabs public GameObject UserPlayerPrefab; public GameObject AIPlayerPrefab; //other batlle object prefabs public GameObject blastmakerPrefab; public GameObject SmallStandPrefab; public GameObject LargeStandPrefab; //prefabs to be removed public GameObject TilePrefab;// Tile prefab is used to make grid to check model scale. //Ship Names for Random Generation public string[] imperialShipNames = new string[]{"Godefroy Magnificat", "His Will", "Triumph", "Duke Helbrecht", "Divine Right", "Dominus Astra", "Indomitable Wrath", "Legatus Stygies", "Lord of Light", "Corax", "Green Lake", "Justus Dominus", "Bloodhawk", "Cardinal Boras", "Saint Augusta", "Pride of Fenris", "Victory", "Hammer of Scaro", "Guardian of Aquinas", "The Sword Infernus", "Warrior Knight", "Light of Ascension", "Kingmaker", "The Covenanter", "Vigilanti Eternas", "Thunderchild", "Hammer of Light", "Ex Cathedra", "Pax Imperium", "Imperious", "Marquis Lex", "Fist of Russ", "Cardinal Xian", "Cypra Probatii", "Flame of Purity", "Niobe", "Sword of Retribution", "Righteous Power", "Sebastian Thor", "Silent Fire", "Archon Kort", "Fortitude", "Lord Solar Macharius", "Rhadamanthine", "Hammer of Justice", "Depth of Fury", "Ferrum Aeterna", "Ultima Praetor", "Invincible", "Emperor's Wrath", "Pallas Imperious", "Preceptor", "Righteous Fury", "Spirit of Defiance", "Sword of Orion", "Lord Daros", "Retribution", "Agrippa", "Minotaur", "Iron Duke", "Justicar", "Indomitus Imperious", "Relentless", "Hammer of Thrace", "Goliath", "Imperial Wrath", "Zealous", "Dominion", "Incendrius", "Lord Sylvanus", "Blade of Drusus", "Cardinal Turin", "Vanguard", "Abdiel", "Uziel", "Baron Surtur", "Vigilant", "Havock", "Guardian", "Advocate", "Cerebus", "August", "Luxor", "Yermetov", "Divine Crusade", "Saint of Scintilla", "Forebearer", "Archangel", "Leonid", "Sword of Voss", "Sanctis Legate", "Ad Liberis", "Cape Wrath", "Harrower", "Valiant", "Strident Virtue", "Purgation"}; public string[] chaosShipNames = new string[]{"Merciless Death", "Fortress of Agony", "Damnations Fury", "Sword of Sacrilege", "Eternity of Pain", "Torment", "The Ninth Eye", "The Treacherous", "Vengeful Spirit", "Infidus Imperator", "Incarnadine", "Foebane", "Bloodied Sword", "Foe-Reaper", "Bringer of Despair", "Blood Royale", "Chaos Eternus", "Injustice", "Warmaker", "Malignus Maximus", "Contagion", "Horrific", "Darkblood", "Heartless Destroyer", "Initiate of Skalathrax", "Wanton Desecration", "Excessive", "Anarchic Vendetta", "Infidus Diabolus", "Covenant of Blood", "Piercing Nova", "Deathbane", "Unforgivable", "Doombringer", "Deathblade", "Steel Fang", "Monstrous", "Unholy Dominion", "Plagueclaw", "Despicable Ecstasy", "Deathskull", "Heathen Promise", "Killfrenzy", "Soulless", "Fearmongers", "Lost Souls", "Carrion Squadron", "Inculpators of Harok", "Relatiators", "Pugatos", "Unclean Ravagers", "Khorne's Disciples", "Fellclaws", "Damnators", "Exterminators"}; //Data For campaign public List<playerData> Players = new List<playerData>(); //Data for Battle public int currentLevel; public BattleData battleData = new BattleData(); //set to true when Loading an old battle public bool levelLoaded = false; #endregion #region Start //Make Persistant void Awake () { if (instance == null) { instance = this; DontDestroyOnLoad (gameObject); } else if (instance != this) { Destroy(gameObject); } } #endregion #region Save/Load Functions //Save Functiom Serialises Data public void Save(string filename){ BinaryFormatter bf = new BinaryFormatter (); FileStream file; CurrentData data; if (File.Exists (Application.persistentDataPath + "/" + filename + ".dat")) { file = File.Open (Application.persistentDataPath + "/" + filename + ".dat", FileMode.Open); data = (CurrentData)bf.Deserialize (file); } else { file = File.Create(Application.persistentDataPath + "/" + filename + ".dat"); data = new CurrentData (); } data.currentLevel = currentLevel; data.players = Players; bf.Serialize (file, data); file.Close (); } //load data retrives data but BattleManager Uses this Data to recreate level public void Load(string filename){ levelLoaded = true; if (File.Exists (Application.persistentDataPath + "/" + filename + ".dat")) { BinaryFormatter bf = new BinaryFormatter (); FileStream file = File.Open (Application.persistentDataPath + "/" + filename + ".dat", FileMode.Open); CurrentData data = (CurrentData)bf.Deserialize (file); file.Close (); currentLevel = data.currentLevel; Players = data.players; } } #endregion } #region Data Classes #region Main data [Serializable] class CurrentData{ public int currentLevel; public List<playerData> players; } #endregion //sub classes for differnt types of Data [Serializable] public class playerData{ //for campaigns public string playerName; public bool humanPlayer;// is player human or Ai public int race;// which race player is public List<GameObject> fleetPrefabs;//ships in players fleet public List<ShipData> fleetShipData;//data for ships //for Battles public bool active;//is player involved in this battle public List<GameObject> shipBattlePrefabs = new List<GameObject>(); // ships chosen to go to battle public List<ShipData> shipData; // Data of ships in battle public int SelectedShipIndex;//Selected ship (for ship data and prefab public List<GameObject>activeShipsPrefabs;//ships remaining in battle } [Serializable] public class BattleData{ public int currentPlayerIndex; public int turnNumber; public List<playerData> activePlayers; } [Serializable] public class ShipData{ //Ship Stats public string shipName; //Name of ship public int hits; // total Number of Hp public int speed; // Base movement rate of ship public int turns; // Base number of turns a ship can make public int shields; //Total number of shields public int armour; //Armour rating for Ship public int turrets; //Number Of turrets on ship public int leadership; //leadership value for ship public int baseMinTurnDistance; // base minimum distance until a turn is allowed public float minMove; // minimum movement a ship has to make public float bearing; // direction ship is facing public int shipType; // class of ship 0 - capital ship, 1 - escort; public bool smallBase = true; public GameObject stand; // the stand object for the ship public List<Weapon> weapons = new List<Weapon>(); // list of weapons for the ship //modifiable ship Stats public float maxMove; // current maximum move this turn (modified Speed) public float fireStrength; // current strength of weapons 1- normal(used for secial orders) public int turnsRemaining; //how many ship-turns are available this turn public int turnsUsed; //how many times a ship has turned this turn public int minTurnDistance; // current minimum turn distance(used for Burn retros) //special order variables public bool specialOrderAllowed = true; //(has the ship made a special order) public int specialOrder; //the special order the ship is on 0 - none, 1- Ahead full 2-new heading 3 - burn retros 4- lock on 5 - reload 6 brace public int orderCounter; // //status Variables public bool onFire = false; //Is ship on fire public bool crippled = false; //is ship crippled public bool moveComplete = false; //has the ship finished its move //record variables public float movedThisTurn; // how far the ship has moved this turn public int remainingHits; // remaining HP public int activeShields; // number of shields active public float rotated; // amount ship has turned public List<float> originalBearing; // directions ship was facing before turns public List<float> turnDistance; //the distance the ship made the turn at public Vector3 forwardVector; // a unit vector in the direction the ship is facing public Ship target; // the ship that is targeted } //SubSector Data [Serializable] public class subSectorData{ //list of Systems List<PlanetSystem> planeterySystems; } #endregion
using System; using System.IO; using System.Collections; using System.Text; namespace LumiSoft.Net.Mime { #region enum ContentDisposition /// <summary> /// Content disposition. /// </summary> [Obsolete("Use Mime class instead, this class will be removed !")] public enum Disposition { /// <summary> /// Content is attachment. /// </summary> Attachment = 0, /// <summary> /// Content is embbed resource. /// </summary> Inline = 1, /// <summary> /// Content is unknown. /// </summary> Unknown = 40 } #endregion /// <summary> /// Mime parser. /// </summary> /// <example> /// <code> /// // NOTE: load you message to byte[] here (from file,POP3_Client or IMAP_Client, ...). /// byte[] data = null; /// /// MimeParser p = new MimeParser(data); /// /// // Do your stuff here /// string from = p.Form; /// /// </code> /// </example> [Obsolete("Use Mime class instead, this class will be removed !")] public class MimeParser { private string m_Headers = ""; private string m_BoundaryID = ""; private MemoryStream m_MsgStream = null; private ArrayList m_Entries = null; /// <summary> /// Default constructor. /// </summary> /// <param name="msg">Mime message which to parse.</param> public MimeParser(byte[] msg) { m_MsgStream = new MemoryStream(msg); m_Headers = ParseHeaders(m_MsgStream); m_BoundaryID = ParseHeaderFiledSubField("Content-Type:","boundary",m_Headers); } #region function ParseAddress private string[] ParseAddress(string headers,string fieldName) { // ToDo: Return as eAddress string addressFieldValue = ParseHeaderField(fieldName,headers); // string[] addressList = addressFieldValue.Split(new char[]{','}); // for(int i=0;i<addressList.Length;i++){ // addressList[i] = Core.CanonicalDecode(addressList[i].Trim()); // } ArrayList a = new ArrayList(); string buff = ""; bool quotedString = false; for(int i=0;i<addressFieldValue.Length;i++){ // Start or close quoted string ("") if(addressFieldValue[i] == '\"'){ if(quotedString){ quotedString = false; } else{ quotedString = true; } } // If ',' isn't between "" or last one(no ending ','), split string if(i == addressFieldValue.Length - 1 || (!quotedString && addressFieldValue[i] == ',')){ // last one(no ending ','), don't loose last char if(addressFieldValue[i] != ','){ buff += addressFieldValue[i]; } a.Add(Core.CanonicalDecode(buff)); buff = ""; } else{ buff += addressFieldValue[i]; } } // ToDo: don't return "return new string[]{""};", get rid of it if(a.Count > 0){ return (string[])a.ToArray(typeof(string)); } else{ return new string[]{""}; } } #endregion #region function ParseContentType /// <summary> /// Parse content type. /// </summary> /// <param name="headers"></param> /// <returns></returns> internal string ParseContentType(string headers) { string contentType = ParseHeaderField("CONTENT-TYPE:",headers); if(contentType.Length > 0){ return contentType.Split(';')[0]; } else{ return "text/plain"; } } #endregion #region function ParseEntries /// <summary> /// Parses mime entries. /// </summary> /// <param name="msgStrm"></param> /// <param name="pos"></param> /// <param name="boundaryID"></param> internal ArrayList ParseEntries(MemoryStream msgStrm,int pos,string boundaryID) { ArrayList entries = null; // Entries are already parsed if(m_Entries != null){ return m_Entries; } entries = new ArrayList(); // If message doesn't have entries and have 1 entry (simple text message or contains only attachment). if(this.ContentType.ToLower().IndexOf("multipart/") == -1){ entries.Add(new MimeEntry(msgStrm.ToArray(),this)); m_Entries = entries; return m_Entries; } msgStrm.Position = pos; if(boundaryID.Length > 0){ MemoryStream strmEntry = new MemoryStream(); StreamLineReader reader = new StreamLineReader(msgStrm); byte[] lineData = reader.ReadLine(); // Search first entry while(lineData != null){ string line = System.Text.Encoding.Default.GetString(lineData); if(line.StartsWith("--" + boundaryID)){ break; } lineData = reader.ReadLine(); } // Start reading entries while(lineData != null){ // Read entry data string line = System.Text.Encoding.Default.GetString(lineData); // Next boundary if(line.StartsWith("--" + boundaryID) && strmEntry.Length > 0){ // Add Entry entries.Add(new MimeEntry(strmEntry.ToArray(),this)); strmEntry.SetLength(0); } else{ strmEntry.Write(lineData,0,lineData.Length); strmEntry.Write(new byte[]{(byte)'\r',(byte)'\n'},0,2); } lineData = reader.ReadLine(); } } return entries; } #endregion #region function GetEntries /// <summary> /// Gets mime entries, including nested entries. /// </summary> /// <param name="entries"></param> /// <param name="allEntries"></param> private void GetEntries(ArrayList entries,ArrayList allEntries) { if(entries != null){ allEntries.AddRange(entries); } if(entries != null){ foreach(MimeEntry ent in entries){ GetEntries(ent.MimeEntries,allEntries); } } } #endregion #region method ParseHeaderField /// <summary> /// Parse header specified header field value. /// </summary> /// <param name="fieldName">Header field which to parse. Eg. Subject: .</param> /// <returns>Restuns specified header filed value.</returns> public string ParseHeaderField(string fieldName) { return ParseHeaderField(fieldName,m_Headers); } #endregion #region static function ParseDate /// <summary> /// Parses rfc2822 datetime. /// </summary> /// <param name="date">Date string</param> /// <returns></returns> public static DateTime ParseDateS(string date) { /* GMT -0000 EDT -0400 EST -0500 CDT -0500 CST -0600 MDT -0600 MST -0700 PDT -0700 PST -0800 BST +0100 British Summer Time */ date = date.Replace("GMT","-0000"); date = date.Replace("EDT","-0400"); date = date.Replace("EST","-0500"); date = date.Replace("CDT","-0500"); date = date.Replace("CST","-0600"); date = date.Replace("MDT","-0600"); date = date.Replace("MST","-0700"); date = date.Replace("PDT","-0700"); date = date.Replace("PST","-0800"); date = date.Replace("BST","+0100"); // Remove () from datest similar "Mon, 13 Oct 2003 20:50:57 +0300 (EEST)" if(date.IndexOf(" (") > -1){ date = date.Substring(0,date.IndexOf(" (")); } date = date.Trim(); //Remove multiple continues spaces while(date.IndexOf(" ") > -1){ date = date.Replace(" "," "); } string[] formats = new string[]{ "r", "ddd, d MMM yyyy HH':'mm':'ss zzz", "ddd, d MMM yyyy H':'mm':'ss zzz", "ddd, d MMM yy HH':'mm':'ss zzz", "ddd, d MMM yy H':'mm':'ss zzz", "ddd, dd MMM yyyy HH':'mm':'ss zzz", "ddd, dd MMM yyyy H':'mm':'ss zzz", "ddd, dd MMM yy HH':'mm':'ss zzz", "ddd, dd MMM yy H':'mm':'ss zzz", "dd'-'MMM'-'yyyy HH':'mm':'ss zzz", "dd'-'MMM'-'yyyy H':'mm':'ss zzz", "d'-'MMM'-'yyyy HH':'mm':'ss zzz", "d'-'MMM'-'yyyy H':'mm':'ss zzz", "d MMM yyyy HH':'mm':'ss zzz", "d MMM yyyy H':'mm':'ss zzz", "dd MMM yyyy HH':'mm':'ss zzz", "dd MMM yyyy H':'mm':'ss zzz", }; return DateTime.ParseExact(date.Trim(),formats,System.Globalization.DateTimeFormatInfo.InvariantInfo,System.Globalization.DateTimeStyles.None); } #endregion #region static function ParseHeaders /// <summary> /// Parses headers from message or mime entry. /// </summary> /// <param name="entryStrm">Stream from where to read headers.</param> /// <returns>Returns header lines.</returns> public static string ParseHeaders(Stream entryStrm) { /*3.1. GENERAL DESCRIPTION A message consists of header fields and, optionally, a body. The body is simply a sequence of lines containing ASCII charac- ters. It is separated from the headers by a null line (i.e., a line with nothing preceding the CRLF). */ byte[] crlf = new byte[]{(byte)'\r',(byte)'\n'}; MemoryStream msHeaders = new MemoryStream(); StreamLineReader r = new StreamLineReader(entryStrm); byte[] lineData = r.ReadLine(); while(lineData != null){ if(lineData.Length == 0){ break; } msHeaders.Write(lineData,0,lineData.Length); msHeaders.Write(crlf,0,crlf.Length); lineData = r.ReadLine(); } return System.Text.Encoding.Default.GetString(msHeaders.ToArray()); } #endregion #region static function ParseHeaderField /// <summary> /// Parse header specified header field value. /// /// Use this method only if you need to get only one header field, otherwise use /// MimeParser.ParseHeaderField(string fieldName,string headers). /// This avoid parsing headers multiple times. /// </summary> /// <param name="fieldName">Header field which to parse. Eg. Subject: .</param> /// <param name="entryStrm">Stream from where to read headers.</param> /// <returns></returns> public static string ParseHeaderField(string fieldName,Stream entryStrm) { return ParseHeaderField(fieldName,ParseHeaders(entryStrm)); } /// <summary> /// Parse header specified header field value. /// </summary> /// <param name="fieldName">Header field which to parse. Eg. Subject: .</param> /// <param name="headers">Full headers string. Use MimeParser.ParseHeaders() to get this value.</param> public static string ParseHeaderField(string fieldName,string headers) { /* Rfc 2822 2.2 Header Fields Header fields are lines composed of a field name, followed by a colon (":"), followed by a field body, and terminated by CRLF. A field name MUST be composed of printable US-ASCII characters (i.e., characters that have values between 33 and 126, inclusive), except colon. A field body may be composed of any US-ASCII characters, except for CR and LF. However, a field body may contain CRLF when used in header "folding" and "unfolding" as described in section 2.2.3. All field bodies MUST conform to the syntax described in sections 3 and 4 of this standard. Rfc 2822 2.3 (Multiline header fields) The process of moving from this folded multiple-line representation of a header field to its single line representation is called "unfolding". Unfolding is accomplished by simply removing any CRLF that is immediately followed by WSP. Each header field should be treated in its unfolded form for further syntactic and semantic evaluation. Example: Subject: aaaaa<CRLF> <TAB or SP>aaaaa<CRLF> */ using(TextReader r = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(headers)))){ string line = r.ReadLine(); while(line != null){ // Find line where field begins if(line.ToUpper().StartsWith(fieldName.ToUpper())){ // Remove field name and start reading value string fieldValue = line.Substring(fieldName.Length).Trim(); // see if multi line value. See commnt above. line = r.ReadLine(); while(line != null && (line.StartsWith("\t") || line.StartsWith(" "))){ fieldValue += line; line = r.ReadLine(); } return fieldValue; } line = r.ReadLine(); } } return ""; } #endregion #region static function ParseHeaderFiledSubField /// <summary> /// Parses header field sub field value. /// For example: CONTENT-TYPE: application\octet-stream; name="yourFileName.xxx", /// fieldName="CONTENT-TYPE:" and subFieldName="name". /// </summary> /// <param name="fieldName">Main header field name.</param> /// <param name="subFieldName">Header field's sub filed name.</param> /// <param name="headers">Full headrs string.</param> /// <returns></returns> public static string ParseHeaderFiledSubField(string fieldName,string subFieldName,string headers) { string mainFiled = ParseHeaderField(fieldName,headers); // Parse sub field value if(mainFiled.Length > 0){ int index = mainFiled.ToUpper().IndexOf(subFieldName.ToUpper()); if(index > -1){ mainFiled = mainFiled.Substring(index + subFieldName.Length + 1); // Remove "subFieldName=" // subFieldName value may be in "" and without if(mainFiled.StartsWith("\"")){ return mainFiled.Substring(1,mainFiled.IndexOf("\"",1) - 1); } // value without "" else{ int endIndex = mainFiled.Length; if(mainFiled.IndexOf(" ") > -1){ endIndex = mainFiled.IndexOf(" "); } return mainFiled.Substring(0,endIndex); } } } return ""; } #endregion #region Properties Implementation /// <summary> /// Gets message headers. /// </summary> public string Headers { get{ return m_Headers; } } /// <summary> /// Gets sender. /// </summary> public string From { get{ return (ParseAddress(m_Headers,"FROM:"))[0]; } } /// <summary> /// Gets recipients. /// </summary> public string[] To { get{ return ParseAddress(m_Headers,"TO:"); } } /// <summary> /// Gets cc. /// </summary> public string[] Cc { get{ return ParseAddress(m_Headers,"CC:"); } } /// <summary> /// Gets bcc. /// </summary> public string[] Bcc { get{ return ParseAddress(m_Headers,"BCC:"); } } /// <summary> /// Gets subject. /// </summary> public string Subject { get{ return Core.CanonicalDecode(ParseHeaderField("SUBJECT:",m_Headers)); } } /// <summary> /// Gets message body text. /// </summary> public string BodyText { get{ m_Entries = ParseEntries(m_MsgStream,m_Headers.Length,m_BoundaryID); // Find first text entry ArrayList entries = new ArrayList(); GetEntries(this.MimeEntries,entries); foreach(MimeEntry ent in entries){ if(ent.ContentType.ToUpper().IndexOf("TEXT/PLAIN") > -1 && ent.ContentDisposition != Disposition.Attachment){ return ent.DataS; } } return ""; } } /// <summary> /// Gets message body HTML. /// </summary> public string BodyHtml { get{ m_Entries = ParseEntries(m_MsgStream,m_Headers.Length,m_BoundaryID); // Find first text entry ArrayList entries = new ArrayList(); GetEntries(this.MimeEntries,entries); foreach(MimeEntry ent in entries){ if(ent.ContentType.ToUpper().IndexOf("TEXT/HTML") > -1){ return ent.DataS; } } return ""; } } /// <summary> /// Gets messageID. /// </summary> public string MessageID { get{ return ParseHeaderField("MESSAGE-ID:",m_Headers); } } /// <summary> /// Gets message content type. /// </summary> public string ContentType { get{ return ParseContentType(m_Headers); } } /// <summary> /// Gets message date. /// </summary> public DateTime MessageDate { get{ try{ return ParseDateS(ParseHeaderField("DATE:",m_Headers)); } catch{ return DateTime.Today; } } } /// <summary> /// Gets message mime entries. /// </summary> public ArrayList MimeEntries { get{ m_Entries = ParseEntries(m_MsgStream,m_Headers.Length,m_BoundaryID); return m_Entries; } } /// <summary> /// Gets mime entries which Content-Disposition: Attachment or Content-Disposition: Inline. /// </summary> public ArrayList Attachments { get{ ArrayList retVal = new ArrayList(); ArrayList entries = new ArrayList(); GetEntries(this.MimeEntries,entries); // Loop all entries and find attachments foreach(MimeEntry entry in entries){ if(entry.ContentDisposition == Disposition.Attachment || entry.ContentDisposition == Disposition.Inline){ retVal.Add(entry); } } return retVal; } } #endregion } }
namespace AngleSharp.Core.Tests { using AngleSharp.Dom; using NUnit.Framework; using System; /// <summary> /// Tests from https://github.com/html5lib/html5lib-tests: /// tree-construction/doctype01.dat /// </summary> [TestFixture] public class DoctypeTests { static IDocument Html(String code) { return code.ToHtmlDocument(); } [Test] public void DoctypeHtml5Standard() { var doc = Html(@"<!DOCTYPE html>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeHtml5MixedCase() { var doc = Html(@"<!dOctYpE HtMl>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeHtml5MissingSpace() { var doc = Html(@"<!DOCTYPEhtml>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeWithoutName() { var doc = Html(@"<!DOCTYPE>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeOnlySpace() { var doc = Html(@"<!DOCTYPE >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPotato() { var doc = Html(@"<!DOCTYPE potato>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomTrailingSpace() { var doc = Html(@"<!DOCTYPE potato >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomAdditionalIdentifier() { var doc = Html(@"<!DOCTYPE potato taco>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomAdditionalIdentifierAndString() { var doc = Html(@"<!DOCTYPE potato taco ""ddd>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifier() { var doc = Html(@"<!DOCTYPE potato sYstEM>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierTrailingSpaces() { var doc = Html(@"<!DOCTYPE potato sYstEM >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierAdditionalIdentifierWithMoreSpaces() { var doc = Html(@"<!DOCTYPE potato sYstEM ggg>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierAdditionalIdentifierTrailingSpaces() { var doc = Html(@"<!DOCTYPE potato SYSTEM taco >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierWithInformationDoubleInSingleQuotes() { var doc = Html(@"<!DOCTYPE potato SYSTEM 'taco""'>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("taco\"", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierWithInformationNormalQuotes() { var doc = Html(@"<!DOCTYPE potato SYSTEM ""taco"">Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("taco", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomSystemIdentifierWithInformationSingleInDoubleQuotes() { var doc = Html(@"<!DOCTYPE potato SYSTEM ""tai'co"">Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("tai'co", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomInvalidSystemIdentifier() { var doc = Html(@"<!DOCTYPE potato SYSTEMtaco ""ddd"">Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomUnknownIdentifierBeforeSystemIdentifier() { var doc = Html(@"<!DOCTYPE potato grass SYSTEM taco>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifier() { var doc = Html(@"<!DOCTYPE potato pUbLIc>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierTrailingSpace() { var doc = Html(@"<!DOCTYPE potato pUbLIc >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomInvalidPublicIdentifier() { var doc = Html(@"<!DOCTYPE potato pUbLIcgoof>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierWithAdditionalIdentifier() { var doc = Html(@"<!DOCTYPE potato PUBLIC goof>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierWithInformationSingleQuoteInDoubleQuotes() { var doc = Html(@"<!DOCTYPE potato PUBLIC ""go'of"">Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("go'of", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierWithInformationSingleQuotesWithInvalidIdentifier() { var doc = Html(@"<!DOCTYPE potato PUBLIC 'go'of'>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("go", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierWithInformationSingleQuotes() { var doc = Html(@"<!DOCTYPE potato PUBLIC 'go:hh of' >Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("go:hh of", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomPublicIdentifierWithInformationAndSystemIdentifierWithInvalidIdentifier() { var doc = Html(@"<!DOCTYPE potato PUBLIC ""W3C-//dfdf"" SYSTEM ggg>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("potato", docType0.Name); Assert.AreEqual("W3C-//dfdf", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeHtmlPublicAndSystemStrictWithLineBreak() { var doc = Html(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd"">Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD HTML 4.01//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/html4/strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeCustomDots() { var doc = Html(@"<!DOCTYPE ...>Hello"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("...", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("Hello", dochtml1body1Text0.TextContent); } [Test] public void DoctypeHtmlPublicAndSystemTransitionalWithLineBreak() { var doc = Html(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD XHTML 1.0 Transitional//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeHtmlPublicAndSystemFramesetWithLineBreak() { var doc = Html(@"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Frameset//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"">"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD XHTML 1.0 Frameset//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeCustomInvalidIdentifiers() { var doc = Html(@"<!DOCTYPE root-element [SYSTEM OR PUBLIC FPI] ""uri"" [ <!-- internal declarations --> ]>"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual(@"root-element", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1Text0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1Text0.NodeType); Assert.AreEqual("]>", dochtml1body1Text0.TextContent); } [Test] public void DoctypeHtmlPublicAndSystemUnknownWithLineBreaks() { var doc = Html(@"<!DOCTYPE html PUBLIC ""-//WAPFORUM//DTD XHTML Mobile 1.0//EN"" ""http://www.wapforum.org/DTD/xhtml-mobile10.dtd"">"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//WAPFORUM//DTD XHTML Mobile 1.0//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.wapforum.org/DTD/xhtml-mobile10.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeHtmlSystemStrictWithBodyFollowing() { var doc = Html(@"<!DOCTYPE HTML SYSTEM ""http://www.w3.org/DTD/HTML4-strict.dtd""><body><b>Mine!</b></body>"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/DTD/HTML4-strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1b0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(1, dochtml1body1b0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1b0).Attributes.Length); Assert.AreEqual("b", dochtml1body1b0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1b0.NodeType); var dochtml1body1b0Text0 = dochtml1body1b0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1b0Text0.NodeType); Assert.AreEqual("Mine!", dochtml1body1b0Text0.TextContent); } [Test] public void DoctypeHtmlPublicAndSystemStrictFollowedDirectlySameQuotesBothDouble() { var doc = Html(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN""""http://www.w3.org/TR/html4/strict.dtd"">"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD HTML 4.01//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/html4/strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeHtmlPublicAndSystemStrictFollowedDirectlyDifferentQuotesLeadingSingle() { var doc = Html(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN""'http://www.w3.org/TR/html4/strict.dtd'>"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD HTML 4.01//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/html4/strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeHtmlPublicAndSystemStrictFollowedDirectlyDifferentQuotesLeadingDouble() { var doc = Html(@"<!DOCTYPE HTML PUBLIC""-//W3C//DTD HTML 4.01//EN""'http://www.w3.org/TR/html4/strict.dtd'>"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD HTML 4.01//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/html4/strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } [Test] public void DoctypeHtmlPublicAndSystemStrictFollowedDirectlySameQuotesBothSingle() { var doc = Html(@"<!DOCTYPE HTML PUBLIC'-//W3C//DTD HTML 4.01//EN''http://www.w3.org/TR/html4/strict.dtd'>"); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual("html", docType0.Name); Assert.AreEqual("-//W3C//DTD HTML 4.01//EN", docType0.PublicIdentifier); Assert.AreEqual("http://www.w3.org/TR/html4/strict.dtd", docType0.SystemIdentifier); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(0, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); } } }
#region License /* * WebSocketBehavior.cs * * The MIT License * * Copyright (c) 2012-2021 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.Specialized; using System.IO; using WebSocketSharp.Net; using WebSocketSharp.Net.WebSockets; namespace WebSocketSharp.Server { /// <summary> /// Exposes a set of methods and properties used to define the behavior of /// a WebSocket service provided by the <see cref="WebSocketServer"/> or /// <see cref="HttpServer"/> class. /// </summary> /// <remarks> /// This class is an abstract class. /// </remarks> public abstract class WebSocketBehavior : IWebSocketSession { #region Private Fields private WebSocketContext _context; private Func<CookieCollection, CookieCollection, bool> _cookiesValidator; private bool _emitOnPing; private string _id; private bool _ignoreExtensions; private Func<string, bool> _originValidator; private string _protocol; private WebSocketSessionManager _sessions; private DateTime _startTime; private WebSocket _websocket; #endregion #region Protected Constructors /// <summary> /// Initializes a new instance of the <see cref="WebSocketBehavior"/> class. /// </summary> protected WebSocketBehavior () { _startTime = DateTime.MaxValue; } #endregion #region Protected Properties /// <summary> /// Gets the HTTP headers included in a WebSocket handshake request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the headers. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected NameValueCollection Headers { get { return _context != null ? _context.Headers : null; } } /// <summary> /// Gets the query string included in a WebSocket handshake request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the query /// parameters. /// </para> /// <para> /// An empty collection if not included. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected NameValueCollection QueryString { get { return _context != null ? _context.QueryString : null; } } /// <summary> /// Gets the management function for the sessions in the service. /// </summary> /// <value> /// <para> /// A <see cref="WebSocketSessionManager"/> that manages the sessions in /// the service. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> protected WebSocketSessionManager Sessions { get { return _sessions; } } #endregion #region Public Properties /// <summary> /// Gets the current state of the WebSocket connection for a session. /// </summary> /// <value> /// <para> /// One of the <see cref="WebSocketState"/> enum values. /// </para> /// <para> /// It indicates the current state of the connection. /// </para> /// <para> /// <see cref="WebSocketState.Connecting"/> if the session has not /// started yet. /// </para> /// </value> public WebSocketState ConnectionState { get { return _websocket != null ? _websocket.ReadyState : WebSocketState.Connecting; } } /// <summary> /// Gets the information in a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <see cref="WebSocketContext"/> instance that provides the access to /// the information in the handshake request. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> public WebSocketContext Context { get { return _context; } } /// <summary> /// Gets or sets the delegate used to validate the HTTP cookies included in /// a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <c>Func&lt;CookieCollection, CookieCollection, bool&gt;</c> delegate /// or <see langword="null"/> if not needed. /// </para> /// <para> /// The delegate invokes the method called when the WebSocket instance /// for a session validates the handshake request. /// </para> /// <para> /// 1st <see cref="CookieCollection"/> parameter passed to the method /// contains the cookies to validate if present. /// </para> /// <para> /// 2nd <see cref="CookieCollection"/> parameter passed to the method /// receives the cookies to send to the client. /// </para> /// <para> /// The method must return <c>true</c> if the cookies are valid. /// </para> /// <para> /// The default value is <see langword="null"/>. /// </para> /// </value> public Func<CookieCollection, CookieCollection, bool> CookiesValidator { get { return _cookiesValidator; } set { _cookiesValidator = value; } } /// <summary> /// Gets or sets a value indicating whether the WebSocket instance for /// a session emits the message event when receives a ping. /// </summary> /// <value> /// <para> /// <c>true</c> if the WebSocket instance emits the message event /// when receives a ping; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool EmitOnPing { get { return _websocket != null ? _websocket.EmitOnPing : _emitOnPing; } set { if (_websocket != null) { _websocket.EmitOnPing = value; return; } _emitOnPing = value; } } /// <summary> /// Gets the unique ID of a session. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the unique ID of the session. /// </para> /// <para> /// <see langword="null"/> if the session has not started yet. /// </para> /// </value> public string ID { get { return _id; } } /// <summary> /// Gets or sets a value indicating whether the service ignores /// the Sec-WebSocket-Extensions header included in a WebSocket /// handshake request. /// </summary> /// <value> /// <para> /// <c>true</c> if the service ignores the extensions requested /// from a client; otherwise, <c>false</c>. /// </para> /// <para> /// The default value is <c>false</c>. /// </para> /// </value> public bool IgnoreExtensions { get { return _ignoreExtensions; } set { _ignoreExtensions = value; } } /// <summary> /// Gets or sets the delegate used to validate the Origin header included in /// a WebSocket handshake request to the service. /// </summary> /// <value> /// <para> /// A <c>Func&lt;string, bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the WebSocket instance /// for a session validates the handshake request. /// </para> /// <para> /// The <see cref="string"/> parameter passed to the method is the value /// of the Origin header or <see langword="null"/> if the header is not /// present. /// </para> /// <para> /// The method must return <c>true</c> if the header value is valid. /// </para> /// <para> /// The default value is <see langword="null"/>. /// </para> /// </value> public Func<string, bool> OriginValidator { get { return _originValidator; } set { _originValidator = value; } } /// <summary> /// Gets or sets the name of the WebSocket subprotocol for the service. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the name of the subprotocol. /// </para> /// <para> /// The value specified for a set must be a token defined in /// <see href="http://tools.ietf.org/html/rfc2616#section-2.2"> /// RFC 2616</see>. /// </para> /// <para> /// The default value is an empty string. /// </para> /// </value> /// <exception cref="InvalidOperationException"> /// The set operation is not available if the session has already started. /// </exception> /// <exception cref="ArgumentException"> /// The value specified for a set operation is not a token. /// </exception> public string Protocol { get { return _websocket != null ? _websocket.Protocol : (_protocol ?? String.Empty); } set { if (_websocket != null) { var msg = "The session has already started."; throw new InvalidOperationException (msg); } if (value == null || value.Length == 0) { _protocol = null; return; } if (!value.IsToken ()) { var msg = "It is not a token."; throw new ArgumentException (msg, "value"); } _protocol = value; } } /// <summary> /// Gets the time that a session has started. /// </summary> /// <value> /// <para> /// A <see cref="DateTime"/> that represents the time that the session /// has started. /// </para> /// <para> /// <see cref="DateTime.MaxValue"/> if the session has not started yet. /// </para> /// </value> public DateTime StartTime { get { return _startTime; } } #endregion #region Private Methods private string checkHandshakeRequest (WebSocketContext context) { if (_originValidator != null) { if (!_originValidator (context.Origin)) return "It includes no Origin header or an invalid one."; } if (_cookiesValidator != null) { var req = context.CookieCollection; var res = context.WebSocket.CookieCollection; if (!_cookiesValidator (req, res)) return "It includes no cookie or an invalid one."; } return null; } private void onClose (object sender, CloseEventArgs e) { if (_id == null) return; _sessions.Remove (_id); OnClose (e); } private void onError (object sender, ErrorEventArgs e) { OnError (e); } private void onMessage (object sender, MessageEventArgs e) { OnMessage (e); } private void onOpen (object sender, EventArgs e) { _id = _sessions.Add (this); if (_id == null) { _websocket.Close (CloseStatusCode.Away); return; } _startTime = DateTime.Now; OnOpen (); } #endregion #region Internal Methods internal void Start ( WebSocketContext context, WebSocketSessionManager sessions ) { _context = context; _sessions = sessions; _websocket = context.WebSocket; _websocket.CustomHandshakeRequestChecker = checkHandshakeRequest; _websocket.EmitOnPing = _emitOnPing; _websocket.IgnoreExtensions = _ignoreExtensions; _websocket.Protocol = _protocol; var waitTime = sessions.WaitTime; if (waitTime != _websocket.WaitTime) _websocket.WaitTime = waitTime; _websocket.OnOpen += onOpen; _websocket.OnMessage += onMessage; _websocket.OnError += onError; _websocket.OnClose += onClose; _websocket.InternalAccept (); } #endregion #region Protected Methods /// <summary> /// Closes the WebSocket connection for a session. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> protected void Close () { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (); } /// <summary> /// Closes the WebSocket connection for a session with the specified /// code and reason. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <param name="code"> /// <para> /// A <see cref="ushort"/> that specifies the status code indicating /// the reason for the close. /// </para> /// <para> /// The status codes are defined in /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4"> /// Section 7.4</see> of RFC 6455. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that specifies the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <para> /// <paramref name="code"/> is less than 1000 or greater than 4999. /// </para> /// <para> /// -or- /// </para> /// <para> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is 1010 (mandatory extension). /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is 1005 (no status) and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void Close (ushort code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (code, reason); } /// <summary> /// Closes the WebSocket connection for a session with the specified /// code and reason. /// </summary> /// <remarks> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </remarks> /// <param name="code"> /// <para> /// One of the <see cref="CloseStatusCode"/> enum values. /// </para> /// <para> /// It specifies the status code indicating the reason for the close. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that specifies the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.MandatoryExtension"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.NoStatus"/> and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void Close (CloseStatusCode code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.Close (code, reason); } /// <summary> /// Closes the WebSocket connection for a session asynchronously. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> protected void CloseAsync () { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (); } /// <summary> /// Closes the WebSocket connection for a session asynchronously with /// the specified code and reason. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <param name="code"> /// <para> /// A <see cref="ushort"/> that specifies the status code indicating /// the reason for the close. /// </para> /// <para> /// The status codes are defined in /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4"> /// Section 7.4</see> of RFC 6455. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that specifies the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// <para> /// <paramref name="code"/> is less than 1000 or greater than 4999. /// </para> /// <para> /// -or- /// </para> /// <para> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </para> /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is 1010 (mandatory extension). /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is 1005 (no status) and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> protected void CloseAsync (ushort code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (code, reason); } /// <summary> /// Closes the WebSocket connection for a session asynchronously with /// the specified code and reason. /// </summary> /// <remarks> /// <para> /// This method does not wait for the close to be complete. /// </para> /// <para> /// This method does nothing if the current state of the connection is /// Closing or Closed. /// </para> /// </remarks> /// <param name="code"> /// <para> /// One of the <see cref="CloseStatusCode"/> enum values. /// </para> /// <para> /// It specifies the status code indicating the reason for the close. /// </para> /// </param> /// <param name="reason"> /// <para> /// A <see cref="string"/> that specifies the reason for the close. /// </para> /// <para> /// The size must be 123 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.MandatoryExtension"/>. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="code"/> is /// <see cref="CloseStatusCode.NoStatus"/> and there is reason. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="reason"/> could not be UTF-8-encoded. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="reason"/> is greater than 123 bytes. /// </exception> protected void CloseAsync (CloseStatusCode code, string reason) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } _websocket.CloseAsync (code, reason); } /// <summary> /// Called when the WebSocket connection for a session has been closed. /// </summary> /// <param name="e"> /// A <see cref="CloseEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnClose"/> event. /// </param> protected virtual void OnClose (CloseEventArgs e) { } /// <summary> /// Called when the WebSocket instance for a session gets an error. /// </summary> /// <param name="e"> /// A <see cref="ErrorEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnError"/> event. /// </param> protected virtual void OnError (ErrorEventArgs e) { } /// <summary> /// Called when the WebSocket instance for a session receives a message. /// </summary> /// <param name="e"> /// A <see cref="MessageEventArgs"/> that represents the event data passed /// from a <see cref="WebSocket.OnMessage"/> event. /// </param> protected virtual void OnMessage (MessageEventArgs e) { } /// <summary> /// Called when the WebSocket connection for a session has been established. /// </summary> protected virtual void OnOpen () { } /// <summary> /// Sends a ping to a client using the WebSocket connection. /// </summary> /// <returns> /// <c>true</c> if the send has done with no error and a pong has been /// received within a time; otherwise, <c>false</c>. /// </returns> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> protected bool Ping () { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } return _websocket.Ping (); } /// <summary> /// Sends a ping with the specified message to a client using /// the WebSocket connection. /// </summary> /// <returns> /// <c>true</c> if the send has done with no error and a pong has been /// received within a time; otherwise, <c>false</c>. /// </returns> /// <param name="message"> /// <para> /// A <see cref="string"/> that specifies the message to send. /// </para> /// <para> /// The size must be 125 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The session has not started yet. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="message"/> could not be UTF-8-encoded. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="message"/> is greater than 125 bytes. /// </exception> protected bool Ping (string message) { if (_websocket == null) { var msg = "The session has not started yet."; throw new InvalidOperationException (msg); } return _websocket.Ping (message); } /// <summary> /// Sends the specified data to a client using the WebSocket connection. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that specifies the binary data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> protected void Send (byte[] data) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (data); } /// <summary> /// Sends the specified file to a client using the WebSocket connection. /// </summary> /// <param name="fileInfo"> /// <para> /// A <see cref="FileInfo"/> that specifies the file to send. /// </para> /// <para> /// The file is sent as the binary data. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="fileInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// The file does not exist. /// </para> /// <para> /// -or- /// </para> /// <para> /// The file could not be opened. /// </para> /// </exception> protected void Send (FileInfo fileInfo) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (fileInfo); } /// <summary> /// Sends the specified data to a client using the WebSocket connection. /// </summary> /// <param name="data"> /// A <see cref="string"/> that specifies the text data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> protected void Send (string data) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (data); } /// <summary> /// Sends the data from the specified stream instance to a client using /// the WebSocket connection. /// </summary> /// <param name="stream"> /// <para> /// A <see cref="Stream"/> instance from which to read the data to send. /// </para> /// <para> /// The data is sent as the binary data. /// </para> /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> protected void Send (Stream stream, int length) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.Send (stream, length); } /// <summary> /// Sends the specified data to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that specifies the binary data to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> protected void SendAsync (byte[] data, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (data, completed); } /// <summary> /// Sends the specified file to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="fileInfo"> /// <para> /// A <see cref="FileInfo"/> that specifies the file to send. /// </para> /// <para> /// The file is sent as the binary data. /// </para> /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="fileInfo"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// The file does not exist. /// </para> /// <para> /// -or- /// </para> /// <para> /// The file could not be opened. /// </para> /// </exception> protected void SendAsync (FileInfo fileInfo, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (fileInfo, completed); } /// <summary> /// Sends the specified data to a client asynchronously using /// the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that specifies the text data to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> protected void SendAsync (string data, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (data, completed); } /// <summary> /// Sends the data from the specified stream instance to a client /// asynchronously using the WebSocket connection. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="stream"> /// <para> /// A <see cref="Stream"/> instance from which to read the data to send. /// </para> /// <para> /// The data is sent as the binary data. /// </para> /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <param name="completed"> /// <para> /// An <c>Action&lt;bool&gt;</c> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// <para> /// <c>true</c> is passed to the method if the send has done with /// no error; otherwise, <c>false</c>. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the connection is not Open. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> protected void SendAsync (Stream stream, int length, Action<bool> completed) { if (_websocket == null) { var msg = "The current state of the connection is not Open."; throw new InvalidOperationException (msg); } _websocket.SendAsync (stream, length, completed); } #endregion } }
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SafetySharp.Compiler.Normalization { using System; using System.Collections.Generic; using System.Linq; using CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Modeling; using Roslyn.Symbols; using Roslyn.Syntax; using Utilities; using ISSE.SafetyChecking.Utilities; /// <summary> /// Normalizes transition chains <c>stateMachine.Transition(...).Transition(...)...</c>. /// </summary> public sealed class TransitionNormalizer : Normalizer { /// <summary> /// The global name of the <see cref="StateMachineHelpers" /> type. /// </summary> private readonly string _helpersType = typeof(StateMachineHelpers).GetGlobalName(); /// <summary> /// The stack of variable prefixes to uniquely name local variables of nested transitions. /// </summary> private readonly Stack<string> _variablePrefixes = new Stack<string>(); /// <summary> /// The writer that is used to generate the code. /// </summary> private readonly CodeWriter _writer = new CodeWriter(); /// <summary> /// The name of the generated choice variable. /// </summary> private string ChoiceVariable => $"choice{_variablePrefixes.Peek()}".ToSynthesized(); /// <summary> /// The name of the generated transitions count variable. /// </summary> private string CountVariable => $"transitionsCount{_variablePrefixes.Peek()}".ToSynthesized(); /// <summary> /// The name of the generated state machine variable. /// </summary> private string StateMachineVariable => $"stateMachine{_variablePrefixes.Peek()}".ToSynthesized(); /// <summary> /// The name of the generated transitions array variable. /// </summary> private string TransitionsVariable => $"transitions{_variablePrefixes.Peek()}".ToSynthesized(); /// <summary> /// Normalizes the <paramref name="statement" />. /// </summary> public override SyntaxNode VisitExpressionStatement(ExpressionStatementSyntax statement) { var transformed = TransformExpression(statement.Expression); if (transformed == null) return statement; return transformed.EnsureLineCount(statement); } /// <summary> /// Normalizes the <paramref name="expression" />. /// </summary> private StatementSyntax TransformExpression(ExpressionSyntax expression) { // If the expression statement is a sequence of // invocation expressions of StateMachine.Transition() -> // member access expressions -> // invocation expressions StateMachine.Transition() -> // member access expressions -> // ... -> // some other expression of type StateMachine // we have to replace all of that by the generated transition code if (expression.Kind() != SyntaxKind.InvocationExpression) return null; var methodSymbol = expression.GetReferencedSymbol<IMethodSymbol>(SemanticModel); if (!methodSymbol.IsTransitionMethod(SemanticModel)) return null; try { _variablePrefixes.Push(Guid.NewGuid().ToString().Replace("-", "_")); ExpressionSyntax stateMachine; var transitions = DecomposeTransitionChain((InvocationExpressionSyntax)expression, out stateMachine); _writer.Clear(); _writer.AppendLine("#line hidden"); _writer.AppendLine("unsafe"); _writer.AppendBlockStatement(() => { _writer.AppendLine($"#line {stateMachine.GetLineNumber()}"); _writer.AppendLine($"var {StateMachineVariable} = {stateMachine.RemoveTrivia().ToFullString()};"); _writer.AppendLine("#line hidden"); _writer.AppendLine($"var {ChoiceVariable} = {_helpersType}.GetChoice({StateMachineVariable});"); _writer.NewLine(); _writer.AppendLine($"var {TransitionsVariable} = stackalloc int[{transitions.Count}];"); _writer.AppendLine($"var {CountVariable} = 0;"); _writer.NewLine(); GenerateTransitionSelection(transitions); _writer.AppendLine($"if ({CountVariable} != 0)"); _writer.AppendBlockStatement(() => { _writer.AppendLine($"switch ({TransitionsVariable}[{ChoiceVariable}.ChooseIndex({CountVariable})])"); _writer.AppendBlockStatement(() => GenerateTransitionSections(transitions)); }); }); return SyntaxFactory.ParseStatement(_writer.ToString()).WithLeadingNewLines(1); } finally { _variablePrefixes.Pop(); } } /// <summary> /// Generates the code that selects the transitions. /// </summary> private void GenerateTransitionSelection(List<Transition> transitions) { for (var i = 0; i < transitions.Count; ++i) { var transition = transitions[i]; WriteLineNumber(transition.SourceLineNumber); _writer.AppendLine($"if ({_helpersType}.IsInState({StateMachineVariable}, {transition.SourceStates.ToFullString()}))"); _writer.AppendLine("#line hidden"); _writer.AppendBlockStatement(() => { WriteLineNumber(transition.GuardLineNumber); _writer.AppendLine($"if ({transition.Guard.ToFullString()})"); _writer.AppendLine("#line hidden"); _writer.AppendBlockStatement(() => { _writer.AppendLine("#line hidden"); _writer.AppendLine($"{TransitionsVariable}[{CountVariable}++] = {i};"); }); }); _writer.NewLine(); } } /// <summary> /// Generates the transition sections. /// </summary> private void GenerateTransitionSections(List<Transition> transitions) { for (var i = 0; i < transitions.Count; ++i) { var transition = transitions[i]; _writer.AppendLine($"case {i}:"); _writer.AppendBlockStatement(() => { GenerateTransitionEffect(transition); _writer.AppendLine("#line hidden"); _writer.AppendLine("break;"); }); } } /// <summary> /// Generates the code for the effect of the <paramref name="transition" />. /// </summary> private void GenerateTransitionEffect(Transition transition) { WriteLineNumber(transition.TargetLineNumber); _writer.AppendLine( $"{_helpersType}.ChangeState({StateMachineVariable}, {ChoiceVariable}.Choose({transition.TargetStates.ToFullString()}));"); WriteLineNumber(transition.ActionLineNumber); // We have to be careful when writing out the action: If it contains any return statements, // we might prematurely exit the containing method. Therefore, if there is any return statement, // declare a lambda and call it immediately; this is inefficient, but this is a rare situation anyway. if (transition.Action.Descendants<ReturnStatementSyntax>().Any()) { var lambda = "lambda".ToSynthesized(); _writer.AppendLine($"{typeof(Action).GetGlobalName()} {lambda} = () => {transition.Action.ToFullString()};"); _writer.AppendLine("#line hidden"); _writer.AppendLine($"{lambda}();"); } else _writer.AppendLine($"{transition.Action.ToFullString()}"); } /// <summary> /// Writes the line number information. /// </summary> private void WriteLineNumber(int lineNumber) { if (lineNumber != 0) _writer.AppendLine($"#line {lineNumber}"); else _writer.AppendLine("#line hidden"); } /// <summary> /// Collects all calls to <see cref="StateMachine{TState}" /> <c>Transition</c> methods within /// <paramref name="expression" />. /// </summary> private List<Transition> DecomposeTransitionChain(InvocationExpressionSyntax expression, out ExpressionSyntax stateMachine) { var transitions = new List<Transition>(); while (true) { AddTransitions(transitions, expression.ArgumentList); var memberAccess = (MemberAccessExpressionSyntax)expression.Expression; if (memberAccess.Expression.Kind() != SyntaxKind.InvocationExpression) { stateMachine = memberAccess.Expression; break; } expression = (InvocationExpressionSyntax)memberAccess.Expression; var methodSymbol = expression.GetReferencedSymbol<IMethodSymbol>(SemanticModel); if (!methodSymbol.IsTransitionMethod(SemanticModel)) { stateMachine = expression; break; } } transitions.Reverse(); return transitions; } /// <summary> /// Decomposes the source and target states within the <paramref name="arguments" /> and adds all resulting transition to the /// list of <paramref name="transitions" />. /// </summary> private void AddTransitions(List<Transition> transitions, ArgumentListSyntax arguments) { var transition = new Transition(); foreach (var argument in arguments.Arguments) { var parameter = argument.GetParameterSymbol(SemanticModel); switch (parameter.Name) { case "from": transition.SourceStates = RemoveArrayCreation(argument.Expression); transition.SourceLineNumber = argument.GetLineNumber(); break; case "to": transition.TargetStates = RemoveArrayCreation(argument.Expression); transition.TargetLineNumber = argument.GetLineNumber(); break; case "guard": transition.Guard = argument.Expression; transition.GuardLineNumber = argument.Expression.GetLineNumber(); break; case "action": var lambda = argument.Expression as ParenthesizedLambdaExpressionSyntax; if (lambda == null) { transition.Action = (StatementSyntax)Syntax.ExpressionStatement(Syntax.InvocationExpression(argument.Expression)); transition.ActionLineNumber = argument.Expression.GetLineNumber(); } else { transition.ActionLineNumber = lambda.Body.GetLineNumber(); var body = lambda.Body as StatementSyntax; if (body != null) transition.Action = (StatementSyntax)Visit(body); else { var transformedBody = TransformExpression((ExpressionSyntax)lambda.Body); if (transformedBody == null) transition.Action = (StatementSyntax)Syntax.ExpressionStatement(lambda.Body); else transition.Action = SyntaxFactory.Block(transformedBody); } } break; default: Assert.NotReached($"Unknown transition method parameter '{parameter}'."); break; } } if (transition.Guard == null) transition.Guard = (ExpressionSyntax)Syntax.TrueLiteralExpression(); if (transition.Action == null) transition.Action = SyntaxFactory.Block(); transitions.Add(transition); } /// <summary> /// If the expression is an array creation expression, makes the array creation implicit to optimize the code. /// </summary> private static SeparatedSyntaxList<ExpressionSyntax> RemoveArrayCreation(ExpressionSyntax expression) { var explicitCreation = expression as ArrayCreationExpressionSyntax; if (explicitCreation != null) return explicitCreation.Initializer.Expressions; var implicitCreation = expression as ImplicitArrayCreationExpressionSyntax; if (implicitCreation != null) return implicitCreation.Initializer.Expressions; return SyntaxFactory.SingletonSeparatedList(expression); } private struct Transition { public SeparatedSyntaxList<ExpressionSyntax> SourceStates; public SeparatedSyntaxList<ExpressionSyntax> TargetStates; public ExpressionSyntax Guard; public StatementSyntax Action; public int SourceLineNumber; public int TargetLineNumber; public int GuardLineNumber; public int ActionLineNumber; } } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using AdoNetTest.BIN.Configuration; namespace AdoNetTest.BIN { class GFXDLocator { /// <summary> /// Configurable class member properties /// </summary> private static string installPath; private static string scriptFile; private static string peerDiscoveryAddress; private static int peerDiscoveryPort; private static string clientBindAddress; private static int clientPort; private static string defaultDir; private static string logDir; private static string locatorScript; private static Logger.Logger logger; private static object locker = new object(); /// <summary> /// Instance member properties /// </summary> public GFXDState LocatorState { get; set; } private String locatorDir; public string PeerDiscoveryAddress { get { return peerDiscoveryAddress; } } public int PeerDiscoveryPort { get { return peerDiscoveryPort; } } public string ClientBindAddress { get { return clientBindAddress; } } public int ClientPort { get { return clientPort; } } public GFXDLocator() { LoadConfig(); if (logger != null) logger.Close(); logger = new Logger.Logger(logDir, String.Format("{0}.log", typeof(GFXDLocator).FullName)); locatorDir = string.Format(@"{0}\{1}", installPath, defaultDir); LocatorState = GFXDState.STOPPED; } public static void LoadConfig() { //installPath = GFXDConfigManager.GetServerSetting("installPath"); installPath = Environment.GetEnvironmentVariable("GEMFIREXD"); scriptFile = GFXDConfigManager.GetServerSetting("scriptFile"); peerDiscoveryAddress = GFXDConfigManager.GetLocatorSetting("peerDiscoveryAddress"); peerDiscoveryPort = int.Parse(GFXDConfigManager.GetLocatorSetting("peerDiscoveryPort")); clientBindAddress = GFXDConfigManager.GetLocatorSetting("clientBindAddress"); clientPort = int.Parse(GFXDConfigManager.GetLocatorSetting("clientPort")); defaultDir = GFXDConfigManager.GetLocatorSetting("locatorDir"); //logDir = GFXDConfigManager.GetClientSetting("logDir"); logDir = Environment.GetEnvironmentVariable("GFXDADOOUTDIR"); locatorScript = String.Format(@"{0}\{1}", installPath, scriptFile); } public void Start() { Log(String.Format("Starting Locator, LocatorState: {0}", LocatorState)); Log(String.Format("locatorScript: {0}, startCommand: {1}", locatorScript, GetStartCmd())); if (this.LocatorState == GFXDState.STARTED) return; ProcessStartInfo psinfo = new ProcessStartInfo(locatorScript, GetStartCmd()); psinfo.UseShellExecute = true; psinfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = psinfo; if (!proc.Start()) { String msg = "Failed to start locator process."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } bool started = proc.WaitForExit(60000); if (!started) { proc.Kill(); String msg = "Timeout waiting for locator process to start."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } this.LocatorState = GFXDState.STARTED; Log(String.Format("Locator started, LocatorState: {0}", LocatorState)); } public void Stop(bool removeDir) { Log(String.Format("Stopping Locator, LocatorState: {0}", LocatorState)); Log(String.Format("locatorScript: {0}, startCommand: {1}", locatorScript, GetStopCmd())); if (this.LocatorState == GFXDState.STOPPED) return; ProcessStartInfo psinfo = new ProcessStartInfo(locatorScript, GetStopCmd()); psinfo.UseShellExecute = true; psinfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = psinfo; if (!proc.Start()) { String msg = "Failed to stop locator process."; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } bool started = proc.WaitForExit(60000); if (!started) { proc.Kill(); String msg = "Timeout waiting for locator process to stop"; Log(msg); throw new Exception(String.Format("Exception: {0}", msg)); } this.LocatorState = GFXDState.STOPPED; if (removeDir) RemoveLocatorDir(); Log(String.Format("Locator stopped, LocatorState: {0}", LocatorState)); } private string GetStartCmd() { CreateLocatorDir(); return String.Format( @"locator start -dir={0} -peer-discovery-address={1} -peer-discovery-port={2} " + " -client-bind-address={3} -client-port={4} -run-netserver=true", locatorDir, peerDiscoveryAddress, peerDiscoveryPort, clientBindAddress, clientPort); } private string GetStopCmd() { return String.Format(@"locator stop -dir={0}", locatorDir); } private void CreateLocatorDir() { try { if (!Directory.Exists(locatorDir)) Directory.CreateDirectory(locatorDir); } catch (Exception e) { Log(e.Message); Log("Locator Dir.: " + locatorDir); } } private void RemoveLocatorDir() { try { if (Directory.Exists(locatorDir)) Directory.Delete(locatorDir, true); } catch (Exception e) { Log(e.Message); } } private void Log(String msg) { lock (locker) { logger.Write(msg); } } } }
// <copyright file="RiakSecurityManager.cs" company="Basho Technologies, Inc."> // Copyright 2011 - OJ Reeves & Jeremiah Peschka // Copyright 2014 - Basho Technologies, Inc. // // This file is provided 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> namespace RiakClient.Auth { using System; using System.IO; using System.Linq; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using Config; using Extensions; using Messages; using Util; internal class RiakSecurityManager { private static readonly StoreLocation[] StoreLocations = new StoreLocation[] { StoreLocation.CurrentUser, StoreLocation.LocalMachine }; private static readonly string[] SubjectSplit = new[] { ", " }; private readonly string targetHostCommonName; private readonly IRiakAuthenticationConfiguration authConfig; private readonly X509CertificateCollection clientCertificates; private readonly X509Certificate2 certificateAuthorityCert; // Interesting discussion: // http://stackoverflow.com/questions/3780801/whats-the-difference-between-a-public-constructor-in-an-internal-class-and-an-i // http://stackoverflow.com/questions/9302236/why-use-a-public-method-in-an-internal-class internal RiakSecurityManager(string targetHost, IRiakAuthenticationConfiguration authConfig) { if (string.IsNullOrWhiteSpace(targetHost)) { throw new ArgumentNullException("targetHost"); } targetHostCommonName = string.Format("CN={0}", targetHost); this.authConfig = authConfig; if (IsSecurityEnabled) { clientCertificates = GetClientCertificates(); certificateAuthorityCert = GetCertificateAuthorityCert(); } } /// <summary> /// Gets a value indicating whether security is enabled /// </summary> public bool IsSecurityEnabled { get { return (false == MonoUtil.IsRunningOnMono) && (authConfig != null && (!string.IsNullOrWhiteSpace(authConfig.Username))); } } /// <summary> /// Gets a value indicating whether client certs are configured and at least one available /// </summary> public bool ClientCertificatesConfigured { get { return clientCertificates.Count > 0; } } /// <summary> /// Gets the client certs collection /// </summary> public X509CertificateCollection ClientCertificates { get { return clientCertificates; } } /// <summary> /// Method used to validate a server certificate /// </summary> /// <param name="sender">The sender</param> /// <param name="certificate">The server certificate</param> /// <param name="chain">The X509 certificate chain</param> /// <param name="sslPolicyErrors">The set of errors according to SSL policy</param> /// <returns>boolean indicating validity of server certificate</returns> public bool ServerCertificateValidationCallback( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) { return true; } /* * Inspired by the following: * http://msdn.microsoft.com/en-us/library/office/dd633677%28v=exchg.80%29.aspx * http://stackoverflow.com/questions/22076184/how-to-validate-a-certificate * * First, ensure we've got a cert authority file */ if (certificateAuthorityCert != null) { if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { // This ensures the presented cert is for the current host if (EnsureServerCertificateSubject(certificate.Subject)) { if (chain != null && chain.ChainStatus != null) { foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status == X509ChainStatusFlags.UntrustedRoot && EnumerableUtil.NotNullOrEmpty(chain.ChainElements)) { // The root cert must not be installed but we provided a file // See if anything in the chain matches our root cert foreach (X509ChainElement chainElement in chain.ChainElements) { if (chainElement.Certificate.Equals(certificateAuthorityCert)) { return true; } } } else { if (status.Status != X509ChainStatusFlags.NoError) { // If there are any other errors in the certificate chain, the certificate is invalid, // so immediately returns false. return false; } } } } } } } return false; } /// <summary> /// Callback to select a client certificate for authentication /// </summary> /// <param name="sender">The sender</param> /// <param name="targetHost">The host requesting authentication</param> /// <param name="localCertificates">The collection of local certificates</param> /// <param name="remoteCertificate">The remote certificate</param> /// <param name="acceptableIssuers">The collection of acceptable issuers</param> /// <returns>A matching certificate for authentication</returns> public X509Certificate ClientCertificateSelectionCallback( object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) { X509Certificate clientCertToPresent = null; /* * NB: * 1st time in here, targetHost == "riak-test" and acceptableIssuers is empty * 2nd time in here, targetHost == "riak-test" and acceptableIssues is one element in array: * OU=Development, O=Basho Technologies, L=Bellevue, S=WA, C=US */ if (EnumerableUtil.NotNullOrEmpty(localCertificates)) { if (EnumerableUtil.NotNullOrEmpty(acceptableIssuers)) { foreach (X509Certificate cert in localCertificates) { if (acceptableIssuers.Any(issuer => cert.Issuer.Contains(issuer))) { clientCertToPresent = cert; break; } } } if (clientCertToPresent == null) { // Hope that this cert is the right one clientCertToPresent = localCertificates[0]; } } return clientCertToPresent; } /// <summary> /// Gets the protobuf object for an authentication request /// </summary> /// <returns>A correctly constructed protobuf object</returns> public RpbAuthReq GetAuthRequest() { return new RpbAuthReq { user = authConfig.Username.ToRiakString(), password = authConfig.Password.ToRiakString() }; } /// <summary> /// Ensures that the server certificate is for the target host /// </summary> /// <param name="serverCertificateSubject">The presented subject</param> /// <returns>boolean indicating validity</returns> private bool EnsureServerCertificateSubject(string serverCertificateSubject) { string serverCommonName = serverCertificateSubject.Split(SubjectSplit, StringSplitOptions.RemoveEmptyEntries) .FirstOrDefault(s => s.StartsWith("CN=")); return targetHostCommonName.Equals(serverCommonName); } /// <summary> /// Gets a file containing the certificate authority certificate /// </summary> /// <returns>An <see cref="X509Certificate2"/> object</returns> private X509Certificate2 GetCertificateAuthorityCert() { X509Certificate2 certificateAuthorityCert = null; if (!string.IsNullOrWhiteSpace(authConfig.CertificateAuthorityFile) && File.Exists(authConfig.CertificateAuthorityFile)) { certificateAuthorityCert = new X509Certificate2(authConfig.CertificateAuthorityFile); } return certificateAuthorityCert; } /// <summary> /// Returns a collection of client certificates from the configuration setting and local stores /// </summary> /// <returns>Returns <see cref="X509CertificateCollection"/> representing available client certificates</returns> private X509CertificateCollection GetClientCertificates() { var clientCertificates = new X509CertificateCollection(); // http://stackoverflow.com/questions/18462064/associate-a-private-key-with-the-x509certificate2-class-in-net if (!string.IsNullOrWhiteSpace(authConfig.ClientCertificateFile) && File.Exists(authConfig.ClientCertificateFile)) { // TODO 3.0 FUTURE exception if config is set but file doesn't actually exist var cert = new X509Certificate2(authConfig.ClientCertificateFile); clientCertificates.Add(cert); } if (!string.IsNullOrWhiteSpace(authConfig.ClientCertificateSubject)) { foreach (var storeLocation in StoreLocations) { X509Store x509Store = null; try { x509Store = new X509Store(StoreName.My, storeLocation); x509Store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); foreach (var cert in x509Store.Certificates) { if (cert.Subject == authConfig.ClientCertificateSubject) { clientCertificates.Add(cert); } } } finally { x509Store.Close(); } } } // TODO 3.0 FUTURE exception if expected to get certs but count is 0 here return clientCertificates; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; using Microsoft.WindowsAzure.Management.Network.Models; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Service Management API includes operations for managing the virtual /// networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for /// more information) /// </summary> public static partial class NetworkOperationsExtensions { /// <summary> /// Abort Virtual Network migration api validates and aborts the given /// virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse AbortMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).AbortMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Abort Virtual Network migration api validates and aborts the given /// virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> AbortMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.AbortMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// Abort Virtual Network migration api validates and aborts the given /// virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse BeginAbortMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).BeginAbortMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Abort Virtual Network migration api validates and aborts the given /// virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> BeginAbortMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.BeginAbortMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// Commit Virtual Network migration api validates and commits the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse BeginCommitMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).BeginCommitMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Commit Virtual Network migration api validates and commits the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> BeginCommitMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.BeginCommitMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// Prepare Virtual Network migration api validates and prepare the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse BeginPrepareMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).BeginPrepareMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Prepare Virtual Network migration api validates and prepare the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> BeginPrepareMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.BeginPrepareMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// The Begin Setting Network Configuration operation asynchronously /// configures the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse BeginSettingConfiguration(this INetworkOperations operations, NetworkSetConfigurationParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).BeginSettingConfigurationAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Begin Setting Network Configuration operation asynchronously /// configures the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> BeginSettingConfigurationAsync(this INetworkOperations operations, NetworkSetConfigurationParameters parameters) { return operations.BeginSettingConfigurationAsync(parameters, CancellationToken.None); } /// <summary> /// Commit Virtual Network migration api validates and commits the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse CommitMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).CommitMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Commit Virtual Network migration api validates and commits the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> CommitMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.CommitMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// The Get Network Configuration operation retrieves the network /// configuration file for the given subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <returns> /// The Get Network Configuration operation response. /// </returns> public static NetworkGetConfigurationResponse GetConfiguration(this INetworkOperations operations) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).GetConfigurationAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Network Configuration operation retrieves the network /// configuration file for the given subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <returns> /// The Get Network Configuration operation response. /// </returns> public static Task<NetworkGetConfigurationResponse> GetConfigurationAsync(this INetworkOperations operations) { return operations.GetConfigurationAsync(CancellationToken.None); } /// <summary> /// The List Virtual network sites operation retrieves the virtual /// networks configured for the subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <returns> /// The response structure for the Network Operations List operation. /// </returns> public static NetworkListResponse List(this INetworkOperations operations) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List Virtual network sites operation retrieves the virtual /// networks configured for the subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157185.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <returns> /// The response structure for the Network Operations List operation. /// </returns> public static Task<NetworkListResponse> ListAsync(this INetworkOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Prepare Virtual Network migration api validates and prepare the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse PrepareMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).PrepareMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Prepare Virtual Network migration api validates and prepare the /// given virtual network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> PrepareMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.PrepareMigrationAsync(virtualNetworkName, CancellationToken.None); } /// <summary> /// The Set Network Configuration operation asynchronously configures /// the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static OperationStatusResponse SetConfiguration(this INetworkOperations operations, NetworkSetConfigurationParameters parameters) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).SetConfigurationAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Set Network Configuration operation asynchronously configures /// the virtual network. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157181.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set Network Configuration /// operation. /// </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 also includes error /// information regarding the failure. /// </returns> public static Task<OperationStatusResponse> SetConfigurationAsync(this INetworkOperations operations, NetworkSetConfigurationParameters parameters) { return operations.SetConfigurationAsync(parameters, CancellationToken.None); } /// <summary> /// Prepare Virtual Network migration api validates the given virtual /// network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// The Validate Network Migration operation response. /// </returns> public static NetworkMigrationValidationResponse ValidateMigration(this INetworkOperations operations, string virtualNetworkName) { return Task.Factory.StartNew((object s) => { return ((INetworkOperations)s).ValidateMigrationAsync(virtualNetworkName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Prepare Virtual Network migration api validates the given virtual /// network for IaaS Classic to ARM migration. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.Network.INetworkOperations. /// </param> /// <param name='virtualNetworkName'> /// Required. Name of the Virtual Network to be migrated. /// </param> /// <returns> /// The Validate Network Migration operation response. /// </returns> public static Task<NetworkMigrationValidationResponse> ValidateMigrationAsync(this INetworkOperations operations, string virtualNetworkName) { return operations.ValidateMigrationAsync(virtualNetworkName, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// String.PadRight(Int32) /// Right-aligns the characters in this instance, /// padding with spaces on the left for a specified total length /// </summary> public class StringPadRight1 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars) private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars) private const int c_MAX_LONG_STR_LEN = 65535; public static int Main() { StringPadRight1 spl = new StringPadRight1(); TestLibrary.TestFramework.BeginTestCase("for method: System.String.PadRight(Int32)"); if (spl.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive test scenarios public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Total width is greater than old string length"; const string c_TEST_ID = "P001"; int totalWidth; string str; bool condition1 = false; //Verify the space paded bool condition2 = false; //Verify the old string bool expectedValue = true; bool actualValue = false; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); //str = "hello"; totalWidth = GetInt32(str.Length + 1, str.Length + c_MAX_STRING_LEN); //totalWidth = 8; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { string strPaded = str.PadRight(totalWidth); char[] trimChs = new char[] {'\x0020'}; string spaces = new string('\x0020', totalWidth - str.Length); string spacesPaded = strPaded.Substring(str.Length, totalWidth - str.Length); condition1 = (string.CompareOrdinal(spaces, spacesPaded) == 0); condition2 = (string.CompareOrdinal(strPaded.TrimEnd(trimChs), str) == 0); actualValue = condition1 && condition2; if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(str, totalWidth); TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: 0 <= total width <= old string length"; const string c_TEST_ID = "P002"; int totalWidth; string str; bool expectedValue = true; bool actualValue = false; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); totalWidth = GetInt32(0, str.Length - 1); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { string strPaded = str.PadRight(totalWidth); actualValue = (0 == string.CompareOrdinal(strPaded, str)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(str, totalWidth); TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } #endregion #region Negative test scenarios //ArgumentException public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: Total width is less than zero. "; const string c_TEST_ID = "N001"; int totalWidth; string str; totalWidth = -1 * TestLibrary.Generator.GetInt32(-55) - 1; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str.PadRight(totalWidth); TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected" + GetDataString(str, totalWidth)); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e +GetDataString(str, totalWidth)); retVal = false; } return retVal; } //OutOfMemoryException public bool NegTest2() // bug 8-8-2006 Noter(v-yaduoj) { bool retVal = true; const string c_TEST_DESC = "NegTest2: Too great width "; const string c_TEST_ID = "N002"; int totalWidth; string str; totalWidth = Int32.MaxValue; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str.PadRight(totalWidth); TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, "OutOfMemoryException is not thrown as expected" + GetDataString(str, totalWidth)); retVal = false; } catch (OutOfMemoryException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } #endregion #region helper methods for generating test data private bool GetBoolean() { Int32 i = this.GetInt32(1, 2); return (i == 1) ? true : false; } //Get a non-negative integer between minValue and maxValue private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } private Int32 Min(Int32 i1, Int32 i2) { return (i1 <= i2) ? i1 : i2; } private Int32 Max(Int32 i1, Int32 i2) { return (i1 >= i2) ? i1 : i2; } #endregion private string GetDataString(string strSrc, int totalWidth) { string str1, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Total width]\n{0}", totalWidth); return str; } }
/******************************************************************** 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. *********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using Axiom.Core; using Axiom.Graphics; using Axiom.Media; using Multiverse.Base; using Multiverse.Interface; using Multiverse.Lib.LogUtil; namespace Multiverse.Movie { /// <summary> /// A movie codec is the code that decompresses the movie file /// into individual frames, and places them on the target texture. /// The codec should implement the IPlugin.Start() method and use /// that to register itself to the movie manager. There should be /// one codec per movie player type, but the codec itself can /// spawn an arbitrary number of movies. /// </summary> public interface ICodec { /// <summary> /// Called from the manager's plugin start method, to avoid /// dependency issues. /// </summary> void Start(); /// <summary> /// Called from the manager's plugin stop method, to avoid /// dependency issues. /// </summary> void Stop(); /// <summary> /// Each codec should have a string name that will be used /// to identify it generically (without API specifics.) /// </summary> /// <returns> /// The string name of the codec. /// </returns> string Name(); /// <summary> /// Check to see whether this codec understands the given string /// parameter, and whether the given value is valid. /// </summary> /// <param name="name"> /// The name of the parameter to check. /// </param> /// <param name="val"> /// The intended value to set. /// </param> /// <returns></returns> bool ValidateParameter(string name, string val); /// <summary> /// Creates a delay-loaded movie texture object. This texture will /// likely need to override the platform-specific Texture class and /// use its Load() method to create itself only when the texture is /// in use. /// /// If the texture already exists, it will return null. The movie /// texture source object should check for duplicate names and only /// return a single movie texture. /// </summary> /// <param name="name"> /// The name of the texture to create, which will later be referred /// to in loading operations. /// </param> /// <returns>The movie texture object, or null if the operation failed.</returns> IMovieTexture CreateMovieTexture(string name); /// <summary> /// Load a movie file from the Media/Movies directory. /// </summary> /// <param name="name"> /// A unique name for this movie. /// </param> /// <param name="file"> /// The filename (not the full path) of this movie, in the Movies directory. /// </param> /// <returns> /// An IMovie object for the movie, or null if the load failed. /// </returns> IMovie LoadFile(string name, string file); /// <summary> /// Load a movie file from the Media/Movies directory. /// </summary> /// <param name="name"> /// A unique name for this movie. /// </param> /// <param name="file"> /// The filename (not the full path) of this movie, in the Movies directory. /// </param> /// <param name="textureName"> /// The name of the texture we should display to, which will be created /// if it doesn't exist. /// </param> /// <returns> /// An IMovie object for the movie, or null if the load failed. /// </returns> IMovie LoadFile(string name, string file, string textureName); /// <summary> /// Load a movie from the Internet. /// </summary> /// <param name="name"> /// A unique name for this stream /// </param> /// <param name="url"> /// The URL to the stream /// </param> /// <returns> /// An IMovie object for the movie, or null if the load failed. /// </returns> IMovie LoadStream(string name, string url); /// <summary> /// Load a movie from the Internet. /// </summary> /// <param name="name"> /// A unique name for this stream /// </param> /// <param name="url"> /// The URL to the stream /// </param> /// <param name="textureName"> /// The name of the texture we should display to, which will be created /// if it doesn't exist. /// </param> /// <returns> /// An IMovie object for the movie, or null if the load failed. /// </returns> IMovie LoadStream(string name, string url, string textureName); /// <summary> /// Check to see if this codec has a movie with the given name. /// </summary> /// <param name="name">The name to search for</param> /// <returns> /// The movie if it was found, or null if it's not in this codec. /// </returns> IMovie FindMovie(string name); /// <summary> /// Stop and unload all the running movies for this codec. /// </summary> void UnloadAll(); /// <summary> /// Stop a movie from playing and free its resources. /// </summary> /// <param name="im">The movie to destroy</param> /// <returns>True if this movie was owned by this codec, false if not.</returns> bool UnloadMovie(IMovie im); } /// <summary> /// The IMovie object is the representation of a movie that's loaded /// and playing. It also responds to play, pause, stop, and volume /// commands. /// </summary> public interface IMovie { /// <summary> /// The name of the codec used to create this movie. /// </summary> /// <returns> /// The string name. /// </returns> string CodecName(); /// <summary> /// The name of this movie, currently the file name. /// </summary> /// <returns> /// The movie file name. /// </returns> string Name(); /// <summary> /// The full path to this movie. /// </summary> /// <returns> /// The full path - in Windows form if it's a file, or a URL if it's a stream. /// </returns> string Path(); /// <summary> /// The name of the texture we're displaying on. /// </summary> /// <returns> /// Aforementioned name /// </returns> string TextureName(); /// <summary> /// A unique identifier for this movie. This number should /// be generated by a call to Manager.GetNewIdentifier() /// </summary> /// <returns> /// The movie's unique ID. /// </returns> int ID(); /// <summary> /// How large the movie itself is, in pixels. /// </summary> /// <returns> /// The movie's width and height in pixels. /// </returns> Size VideoSize(); /// <summary> /// The texture size is likely to be different from the movie /// size, because it will probably be rounded up to the next /// power of two. /// </summary> /// <returns> /// The width and height in pixels of the texture that this /// movie targets. /// </returns> Size TextureSize(); /// <summary> /// Gets the Axiom texture object we're displaying the movie to. /// </summary> /// <returns> /// The Texture object this movie is playing on, which is registered /// with the Axiom TextureManager. /// </returns> Axiom.Core.Texture Texture(); /// <summary> /// Gets the name of an alternate image to display when the movie /// isn't being displayed. This image will be automatically displayed /// when the movie ends. /// </summary> /// <returns> /// The name of the image in the Textures directory. /// </returns> string AltImage(); /// <summary> /// Sets the name of an alternate image to display when the movie /// isn't being displayed. This image will be automatically displayed /// when the movie ends. /// </summary> /// <param name="image"> /// The name of the image in the Textures directory. /// </param> void SetAltImage(string image); /// <summary> /// Bring up the alternate image for the movie. Note that this will /// not work if the movie is playing; it should be stopped. /// </summary> /// <returns> /// True if the alt image was displayed, false if not. /// </returns> bool ShowAltImage(); /// <summary> /// Unloads the alt image from display. This will unload the texture /// itself, so make sure there is something else to take its place. /// </summary> /// <returns> /// True if the alt image was removed, false if nothing was done. /// </returns> bool HideAltImage(); /// <summary> /// Completely replace an entity in the scene, keeping its position, /// orientation, and scale, but replacing it with a movie width by movie /// height sized plane to play the movie on. /// </summary> /// <param name="name"> /// The name of the world object to replace in the scene. Replaces the /// mesh, material, and texture of the object. /// </param> /// <returns></returns> bool ReplaceWorldObject(string name); /// <summary> /// Adjusts the texture coordinates (via texture matrix) of any texture /// in the material that refers to this movie. /// </summary> /// <param name="material"> /// The name of the material to search. /// </param> /// <returns> /// True if a texture unit state was changed, false if not. /// </returns> bool SetTextureCoordinates(string material); /// <summary> /// Start the movie playing, continuing play until the end. May pause /// briefly to buffer. /// </summary> /// <returns> /// True if the movie was able to start playing, or false if an error /// occurred. /// </returns> bool Play(); /// <summary> /// Temporarily suspend playback on the current frame. Decoding and /// buffering continues to occur, but the display is frozen in position. /// </summary> /// <returns> /// True if the movie paused, or false if it didn't due to an error. /// </returns> bool Pause(); /// <summary> /// Halt playback of this movie and reset the position to the start of /// the movie. Buffering and decoding will also cease. /// </summary> /// <returns> /// True if the movie stopped, or false if it didn't due to an error. /// </returns> bool Stop(); /// <summary> /// Immediately free any of the resources we hold. /// </summary> void Unload(); /// <summary> /// Generic parameter setter, using strings as the transport. Each codec /// should determine which parameters make sense for the given video type /// and override the ValidateParameter() method to test whether or not the /// codec understands it. /// </summary> /// <param name="name"> /// The name of the parameter to set (e.g. "looping") /// </param> /// <param name="value"> /// The value of the parameter to set (e.g. "true") /// </param> /// <returns> /// True if the movie was able to set the parameter, false if not. /// </returns> bool SetParameter(string name, string value); } /// <summary> /// The Movie Manager handles keeping track of all the codecs, and /// serves as a base class for shared functionality, like generating /// a plane for the scene. /// </summary> public class Manager : IPlugin { #region Fields private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Manager)); /// <summary> /// The singleton instance of the movie manager, created on plugin load. /// </summary> public static Manager Instance = null; /// <summary> /// The list of all available codecs in the system, which should implement /// the IPlugin interface and add themselves to this list when they are /// loaded. /// </summary> public static List<ICodec> Codecs = new List<ICodec>(); #endregion #region Generated names /// <summary> /// We use a simple movie identifier system for now. /// </summary> private static int movieIndex = 0; /// <summary> /// The base of the generated names for the movie material. /// </summary> private const string baseMaterialName = "MV_PRIVATE_MATERIAL"; /// <summary> /// The base of the generated names for the movie mesh. /// </summary> private const string baseMeshName = "MV_PRIVATE_MESH"; /// <summary> /// The base of the generated names for the movie texture. /// </summary> private const string baseTextureName = "MV_PRIVATE_TEXTURE"; /// <summary> /// If we create a material for this movie, return what that /// generated name should be. /// </summary> /// <param name="movie"> /// The movie to create a material name for. /// </param> /// <returns> /// A string name for the material. /// </returns> public static string MaterialName(IMovie movie) { return MaterialName(movie.CodecName(), movie.ID()); } /// <summary> /// If we create a material for this movie, return what that /// generated name should be. /// </summary> /// <param name="codec"> /// The codec that's playing the movie. /// </param> /// <param name="id"> /// The int ID of the movie. /// </param> /// <returns> /// A string name for the material. /// </returns> public static string MaterialName(string codec, int id) { return baseMaterialName + "_" + codec + "_" + id; } /// <summary> /// If we create a mesh for this movie, return what that /// generated name should be. /// </summary> /// <param name="movie"> /// The movie to create a mesh name for. /// </param> /// <returns> /// A string name for the mesh. /// </returns> public static string MeshName(IMovie movie) { return MeshName(movie.CodecName(), movie.ID()); } /// <summary> /// If we create a mesh for this movie, return what that /// generated name should be. /// </summary> /// <param name="codec"> /// The codec that's playing the movie. /// </param> /// <param name="id"> /// The int ID of the movie. /// </param> /// <returns> /// A string name for the mesh. /// </returns> public static string MeshName(string codec, int id) { return baseMeshName + "_" + codec + "_" + id; } /// <summary> /// If we create a texture for this movie, return what that /// generated name should be. /// </summary> /// <param name="movie"> /// The movie to create a texture name for. /// </param> /// <returns> /// A string name for the texture. /// </returns> public static string TextureName(IMovie movie) { return TextureName(movie.CodecName(), movie.ID()); } /// <summary> /// If we create a texture for this movie, return what that /// generated name should be. /// </summary> /// <param name="codec"> /// The codec that's playing the movie. /// </param> /// <param name="id"> /// The int ID of the movie. /// </param> /// <returns> /// A string name for the texture. /// </returns> public static string TextureName(string codec, int id) { return baseTextureName + "_" + codec + "_" + id; } #endregion #region IPlugin methods /// <summary> /// Initialize the singleton member and wait for the interpreter to /// load to reflect ourselves. /// </summary> public void Start() { Instance = this; ExternalTextureSourceManager.Instance.SetExternalTextureSource( MovieTextureSource.MV_SOURCE_NAME, new MovieTextureSource()); Assembly assembly = Assembly.GetAssembly(typeof(Manager)); foreach (Type type in assembly.GetTypes()) { if ((type.GetInterface("ICodec") == typeof(ICodec)) && (!type.IsInterface)) { try { ICodec codec = (ICodec)Activator.CreateInstance(type); if (codec != null) { if (codec.Name() != null) { codec.Start(); Codecs.Add(codec); } } } catch (Exception e) { LogManager.Instance.WriteException("Failed to create instance of codec of type {0} from assembly {1}", type, assembly.FullName); LogManager.Instance.WriteException(e.Message); } } } } /// <summary> /// Unload ourselves. /// </summary> public void Stop() { log.Info("Movie manager stop"); foreach (ICodec codec in Codecs) { codec.Stop(); } Codecs.Clear(); Instance = null; } #endregion /// <summary> /// Silly helper class to figure out if the codec's name /// matches in a search. /// </summary> private class CodecFinder { string name; public CodecFinder(string nm) { name = nm; } public bool MatchName(ICodec man) { return man.Name() == name; } } /// <summary> /// Find the codec object using the name of the codec. /// </summary> /// <param name="name"> /// The codec name, which was used to register itself to the /// codec array. /// </param> /// <returns> /// The codec object if it was found, or null if it wasn't. /// </returns> public ICodec FindCodec(string name) { CodecFinder cf = new CodecFinder(name); ICodec ans = Codecs.Find(new Predicate<ICodec>(cf.MatchName)); return ans; } /// <summary> /// Find a movie file by its name. /// </summary> /// <param name="name"> /// The name of the movie to find, as passed in at creation. /// </param> /// <returns> /// The movie file if found, or null if it wasn't. /// </returns> public IMovie FindMovie(string name) { IMovie m = null; foreach (ICodec c in Codecs) { m = c.FindMovie(name); if (m != null) { return m; } } return m; } /// <summary> /// Find a movie from the movies directory and return a path /// to it. /// </summary> /// <param name="name"> /// The filename of the movie. /// </param> /// <returns> /// A Windows path to the movie, possibly relative. /// </returns> public static string ResolveMovieFile(string name) { try { string ans = ResourceManager.ResolveCommonResourceData(name); if (ans == null) { log.ErrorFormat("ResolveMovieFile file '{0}' not found", name); return null; } else { log.InfoFormat("ResolveMovieFile file '{0}' returned '{1}'", name, ans); return ans; } } catch (Exception) { log.ErrorFormat("ResolveMovieFile file '{0}' not found", name); return null; } } /// <summary> /// Get a new unique identifier for a movie. /// </summary> /// <returns> /// An integer id, which should be returned by IMovie.ID(). /// </returns> public static int GetNewIdentifier() { return movieIndex++; } public static int NextPowerOfTwo(int num) { // all hail wikipedia if (num == 0) { return num; } if (((num) & (num - 1)) == 0) { return num; } int ans = num - 1; ans |= (ans >> 1); ans |= (ans >> 2); ans |= (ans >> 4); ans |= (ans >> 8); ans |= (ans >> 16); ans++; return ans; } // XXXMLM - ReplaceMaterial? /// <summary> /// Replace a world object with a width by height textured plane /// that plays the movie. Keeps the original Entity object but /// replaces its mesh, material, and texture. /// </summary> /// <param name="movie"> /// The movie we're going to play on the object. /// </param> /// <param name="name"> /// The name of the world object to replace. /// </param> /// <returns> /// True if the object was replaced, false if it wasn't. /// </returns> public static bool ReplaceWorldObject(IMovie movie, string name) { if (Client.Instance != null) { ObjectNode node = Client.Instance.WorldManager.GetObjectNode(name); if (node == null) { return false; } return AttachToNode(movie, node); } else { // could be in world editor return false; } } /// <summary> /// Private function to do the work of ReplaceWorldObject. /// </summary> /// <param name="movie"> /// The movie we're going to play on the object. /// </param> /// <param name="on"> /// The scene object to replace. /// </param> /// <returns> /// True if the object was replaced, false if it wasn't. /// </returns> private static bool AttachToNode(IMovie movie, ObjectNode on) { SceneNode sn = on.SceneNode; IEnumerator ie = sn.Objects.GetEnumerator(); ie.MoveNext(); MovableObject mo = (MovableObject)ie.Current; Entity en = (Entity)mo; if (ReplaceEntity(en, MeshName(movie), MaterialName(movie), movie.TextureName(), movie.VideoSize(), movie.TextureSize())) { return movie.SetTextureCoordinates(MaterialName(movie)); } else { return false; } } /// <summary> /// Helper function to replace an entity in the scene. Adjusts the /// texture coordinates to flip the video. That may be wrong on /// everything except DirectX / DirectShow. /// </summary> /// <param name="en"> /// The entity we're going to replace. /// </param> /// <param name="meshName"> /// The name of the mesh to create. /// </param> /// <param name="materialName"> /// The name of the material to create. /// </param> /// <param name="textureName"> /// The name of the texture to create. /// </param> /// <param name="videoSize"> /// The size of the movie, in width by height pixels. /// </param> /// <param name="textureSize"> /// The size of the texture, in width by height pixels. /// </param> /// <returns></returns> private static bool ReplaceEntity( Entity en, string meshName, string materialName, string textureName, Size videoSize, Size textureSize) { Mesh me = MeshManager.Instance.CreatePlane( meshName, // name new Axiom.MathLib.Plane(new Axiom.MathLib.Vector3(0, 0, -1), new Axiom.MathLib.Vector3(0, 0, 0)), videoSize.Width, videoSize.Height, 1, // xsegments 1, // ysegments true, // normals 1, // numtexcoords 1.0f,// utile 1.0f,// vtile new Axiom.MathLib.Vector3(0, 1, 0) // upvec ); en.Mesh = me; Axiom.Graphics.Material m = MaterialManager.Instance.GetByName(materialName); if (m == null) { m = (Axiom.Graphics.Material) MaterialManager.Instance.Create(materialName, true); ColorEx c = new ColorEx(1.0f, 1.0f, 1.0f); m.Ambient = c; m.Diffuse = c; for (int i = 0; i < m.GetTechnique(0).NumPasses; i++) { Pass p = m.GetTechnique(0).GetPass(i); p.RemoveAllTextureUnitStates(); p.CreateTextureUnitState(textureName); } } en.MaterialName = materialName; return true; } /// <summary> /// Reset the texture coordinates in the given material for all instances of the /// movie texture to fit the actual size of the movie. Since movies often are /// not sized to a power of two, texture coordinates need to remap the image to /// fill the texture correctly. Sets a texture matrix to adjust the existing coordinates. /// </summary> /// <param name="movie"> /// The movie to get the sizes and texture name from. /// </param> /// <param name="material"> /// The name of the material to search. /// </param> /// <returns> /// True if coordinates were changed, false if not. /// </returns> public static bool SetTextureCoordinates(IMovie movie, string material) { return SetTextureCoordinates(movie.TextureName(), movie.VideoSize(), movie.TextureSize(), material); } /// <summary> /// Helper function to set the texture coordinates. Instead of taking a movie /// object, this takes a specific texture name, video size, texture size, and /// material. Sets a texture matrix to adjust the existing coordinates. /// </summary> /// <param name="textureName"> /// The name of the texture to adjust. /// </param> /// <param name="videoSize"> /// The size of the video in pixels. /// </param> /// <param name="textureSize"> /// The size of the expected texture in pixels. /// </param> /// <param name="material"> /// The name of the material to search for textures. /// </param> /// <returns> /// True if any texture coordinates were adjusted, false if not. /// </returns> public static bool SetTextureCoordinates(string textureName, Size videoSize, Size textureSize, string material) { bool ans = false; Axiom.Graphics.Material m = MaterialManager.Instance.GetByName(material); if (m != null) { for (int i = 0; i < m.NumTechniques; i++) { for (int j = 0; j < m.GetTechnique(i).NumPasses; j++) { Pass p = m.GetTechnique(i).GetPass(j); for (int k = 0; k < p.NumTextureUnitStages; k++) { if (p.GetTextureUnitState(k).TextureName == textureName) { TextureUnitState tu = p.GetTextureUnitState(k); float uRatio = ((float)videoSize.Width) / ((float)textureSize.Width); float vRatio = ((float)videoSize.Height) / ((float)textureSize.Height); tu.SetTextureScale(1.0f / uRatio, 1.0f / vRatio); tu.SetTextureScroll(-0.5f * (1.0f - uRatio), -0.5f * (1.0f - vRatio)); ans = true; } } } } } return ans; } /// <summary> /// Load an alternate image into the scene for the given texture name. /// Future movies that play should look for this texture and unload it /// if it exists. /// </summary> /// <param name="name"> /// The name of the texture to replace. /// </param> /// <param name="file"> /// The name of the file in the Textures directory to display. /// </param> /// <returns> /// True if the texture was created, false if it wasn't. /// </returns> public static bool ShowAltImage(string name, string file) { Axiom.Core.Texture texture = TextureManager.Instance.GetByName(name); if (texture != null) { if (texture.IsLoaded) { texture.Unload(); } TextureManager.Instance.Remove(name); } try { Axiom.Media.Image img = Axiom.Media.Image.FromFile(file); if (img != null) { texture = TextureManager.Instance.LoadImage(name, img); return texture != null; } } catch (Exception e) { LogUtil.ExceptionLog.ErrorFormat("Exception: {0}", e); return false; } return false; } public static bool HideAltImage(string name) { Axiom.Core.Texture texture = TextureManager.Instance.GetByName(name); if (texture != null) { if (texture.IsLoaded) { texture.Unload(); } TextureManager.Instance.Remove(name); return true; } return false; } } /// <summary> /// An IMovieTexture is a delay-loaded texture representation of a movie in /// a scene. Its entire purpose in life is to override the implementation /// of the Axiom texture to catch when the texture is loaded and start the /// movie when it's loaded. The external texture source passes through the /// parameters. This object is created by the codec in ICodec.CreateMovieTexture(). /// </summary> public interface IMovieTexture { /// <summary> /// Add a new material that this texture will be played on. This material /// will have its texture coordinates updated when the movie loads. /// </summary> /// <param name="material"> /// The name of the material, which will be checked for uniqueness and /// only added once. /// </param> void AddMaterial(string material); /// <summary> /// Parse the string parameters and set the movie object appropriately. /// Default parameters that are required are MovieTextureSource.MV_MOVIE_NAME /// and MovieTextureSource.MV_CODEC_NAME. /// </summary> /// <param name="name"> /// The name of the parameter to set, from the material file. /// </param> /// <param name="val"> /// All values of the parameter in string form. /// </param> void SetParameter(string name, string val); } /// <summary> /// The movie texture source is our implementation of the external texture source API /// so that the material serializer knows who to call when it finds a texture_source /// of MovieTextureSource.MV_SOURCE_NAME. An mvMovie is expected to have a codec /// that it calls to play the movie itself. The Movie.Manager API can also be called /// directly from script. Once the movie is loaded, the movie object can be retrieved /// via the usual Movie.Manager calls. The defined texture should be registered into /// the texture manager with TextureManager.Instance.Add() by the IMovieTexture /// implementation. /// </summary> public class MovieTextureSource : ExternalTextureSource { /// <summary> /// The name we use to register ourselves as an external texture source. /// </summary> public const string MV_SOURCE_NAME = "mvMovie"; /// <summary> /// The parameter name for the unique name to refer to this movie as. Also /// is the name of the texture that's created. A required parameter. /// </summary> public const string MV_MOVIE_NAME = "name"; /// <summary> /// The parameter name for the name of the codec to use to decode this movie. /// A required parameter. /// </summary> public const string MV_CODEC_NAME = "codec"; /// <summary> /// The file path or URL to the movie to load. If this is null, the movie /// won't be loaded on startup, but a texture will be registered for the /// codec with the given movie name. /// </summary> public const string MV_PATH_NAME = "path"; /// <summary> /// The name of an alt texture to display from the Textures directory. /// Not a required parameter. /// </summary> public const string MV_ALT_NAME = "alt"; /// <summary> /// Create a class logger /// </summary> private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MovieTextureSource)); /// <summary> /// Store and validate parameters before we create the texture. /// </summary> private IDictionary parameters = new Hashtable(); /// <summary> /// A list of all the textures we've created so far so we don't create /// duplicates. /// </summary> private IDictionary textures = new Hashtable(); /// <summary> /// Construct this object before anything has been initialized. /// </summary> public MovieTextureSource() { pluginName = "MVMovieTextureSource"; } /// <summary> /// The render system has been created, so initialize our data. /// </summary> /// <returns></returns> public override bool Initialize() { log.Info(MV_SOURCE_NAME + ": Initialize"); return true; } /// <summary> /// We're all done, so stop the world. /// </summary> public override void Shutdown() { log.Info(MV_SOURCE_NAME + ": Shutdown"); } /// <summary> /// Send a string parameter to the movie texture currently under /// construction. This list is cleared once the texture is created. /// </summary> /// <param name="name"> /// The name of the parameter to set. /// </param> /// <param name="value"> /// What to set the parameter to. /// </param> public override void SetParameter(string name, string value) { if (name[0] != '#') { log.InfoFormat(MV_SOURCE_NAME + ": SetParameter {0}, {1}", name, value); parameters[name] = value; } } /// <summary> /// Turn the parameters that we've recorded so far into a texture object /// that can be loaded later. The texture will simply be registered with /// the texture manager by the IMovieTexture object when it's successfully /// created. /// </summary> /// <param name="materialName"> /// The name of the parent material, which will be used as the movie and /// texture name if no movie name is provided. /// </param> public override void CreateDefinedTexture(string materialName) { string name = (parameters[MV_MOVIE_NAME] as string); if (name == null) { log.WarnFormat(MV_SOURCE_NAME + ": No name parameter on movie, using material name ({0})", materialName); name = materialName; } log.InfoFormat(MV_SOURCE_NAME + ": CreateDefinedTexture {0}", name); if (textures[name] == null) { string codecname = (parameters[MV_CODEC_NAME] as string); if (codecname == null) { log.ErrorFormat(MV_SOURCE_NAME + ": No codec parameter on texture '{0}'", name); } else { ICodec codec = Manager.Instance.FindCodec(codecname); if (codec == null) { log.ErrorFormat(MV_SOURCE_NAME + ": Could not find codec '{0}'", codecname); } else { IMovieTexture mt = codec.CreateMovieTexture(name); if (mt == null) { log.ErrorFormat(MV_SOURCE_NAME + ": Could not create movie texture '{0}'", name); } else { IDictionaryEnumerator ie = parameters.GetEnumerator(); while (ie.MoveNext()) { mt.SetParameter(ie.Key as string, ie.Value as string); } textures[name] = mt; } } } } else { log.InfoFormat(MV_SOURCE_NAME + ": Texture '{0}' already exists, adding material", name); } IMovieTexture imt = (textures[name] as IMovieTexture); if (imt != null) { imt.AddMaterial(materialName); } parameters.Clear(); } /// <summary> /// Destroy an advanced texture since we're done with it. Doesn't appear to get /// called at the moment. /// </summary> /// <param name="name"> /// The name of the texture to destroy. /// </param> public override void DestroyAdvancedTexture(string name) { log.InfoFormat(MV_SOURCE_NAME + ": DestroyAdvancedTexture {0}", name); textures[name] = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; namespace IronPython.Compiler { public delegate object CallTarget0(); internal static class PythonCallTargets { public static object OriginalCallTargetN(PythonFunction function, params object[] args) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object[], object>)function.func_code.Target)(function, args); } #region Generated Python Lazy Call Targets // *** BEGIN GENERATED CODE *** // generated by function: gen_lazy_call_targets from: generate_calls.py public static object OriginalCallTarget0(PythonFunction function) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object>)function.func_code.Target)(function); } public static object OriginalCallTarget1(PythonFunction function, object arg0) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object>)function.func_code.Target)(function, arg0); } public static object OriginalCallTarget2(PythonFunction function, object arg0, object arg1) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object>)function.func_code.Target)(function, arg0, arg1); } public static object OriginalCallTarget3(PythonFunction function, object arg0, object arg1, object arg2) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2); } public static object OriginalCallTarget4(PythonFunction function, object arg0, object arg1, object arg2, object arg3) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3); } public static object OriginalCallTarget5(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4); } public static object OriginalCallTarget6(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5); } public static object OriginalCallTarget7(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } public static object OriginalCallTarget8(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public static object OriginalCallTarget9(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public static object OriginalCallTarget10(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public static object OriginalCallTarget11(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public static object OriginalCallTarget12(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public static object OriginalCallTarget13(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public static object OriginalCallTarget14(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public static object OriginalCallTarget15(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } // *** END GENERATED CODE *** #endregion public const int MaxArgs = 15; internal static Type GetPythonTargetType(bool wrapper, int parameters, out Delegate originalTarget) { if (!wrapper) { switch (parameters) { #region Generated Python Call Target Switch // *** BEGIN GENERATED CODE *** // generated by function: gen_python_switch from: generate_calls.py case 0: originalTarget = (Func<PythonFunction, object>)OriginalCallTarget0; return typeof(Func<PythonFunction, object>); case 1: originalTarget = (Func<PythonFunction, object, object>)OriginalCallTarget1; return typeof(Func<PythonFunction, object, object>); case 2: originalTarget = (Func<PythonFunction, object, object, object>)OriginalCallTarget2; return typeof(Func<PythonFunction, object, object, object>); case 3: originalTarget = (Func<PythonFunction, object, object, object, object>)OriginalCallTarget3; return typeof(Func<PythonFunction, object, object, object, object>); case 4: originalTarget = (Func<PythonFunction, object, object, object, object, object>)OriginalCallTarget4; return typeof(Func<PythonFunction, object, object, object, object, object>); case 5: originalTarget = (Func<PythonFunction, object, object, object, object, object, object>)OriginalCallTarget5; return typeof(Func<PythonFunction, object, object, object, object, object, object>); case 6: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object>)OriginalCallTarget6; return typeof(Func<PythonFunction, object, object, object, object, object, object, object>); case 7: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object>)OriginalCallTarget7; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object>); case 8: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object>)OriginalCallTarget8; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object>); case 9: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget9; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>); case 10: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget10; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>); case 11: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget11; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>); case 12: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget12; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 13: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget13; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 14: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget14; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 15: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget15; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); // *** END GENERATED CODE *** #endregion } } originalTarget = (Func<PythonFunction, object[], object>)OriginalCallTargetN; return typeof(Func<PythonFunction, object[], object>); } } internal class PythonFunctionRecursionCheckN { private readonly Func<PythonFunction, object[], object> _target; public PythonFunctionRecursionCheckN(Func<PythonFunction, object[], object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object[] args) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, args); } finally { PythonOps.FunctionPopFrame(); } } } #region Generated Python Recursion Enforcement // *** BEGIN GENERATED CODE *** // generated by function: gen_recursion_checks from: generate_calls.py internal class PythonFunctionRecursionCheck0 { private readonly Func<PythonFunction, object> _target; public PythonFunctionRecursionCheck0(Func<PythonFunction, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck1 { private readonly Func<PythonFunction, object, object> _target; public PythonFunctionRecursionCheck1(Func<PythonFunction, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck2 { private readonly Func<PythonFunction, object, object, object> _target; public PythonFunctionRecursionCheck2(Func<PythonFunction, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck3 { private readonly Func<PythonFunction, object, object, object, object> _target; public PythonFunctionRecursionCheck3(Func<PythonFunction, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck4 { private readonly Func<PythonFunction, object, object, object, object, object> _target; public PythonFunctionRecursionCheck4(Func<PythonFunction, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck5 { private readonly Func<PythonFunction, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck5(Func<PythonFunction, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck6 { private readonly Func<PythonFunction, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck6(Func<PythonFunction, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck7 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck7(Func<PythonFunction, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck8 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck8(Func<PythonFunction, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck9 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck9(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck10 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck10(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck11 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck11(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck12 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck12(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck13 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck13(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck14 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck14(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck15 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck15(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { try { PythonOps.FunctionPushFrame(function.Context.LanguageContext); return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } finally { PythonOps.FunctionPopFrame(); } } } // *** END GENERATED CODE *** #endregion }
using FluentMigrator.Runner.Helpers; #region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Data; using System.IO; using FluentMigrator.Builders.Execute; namespace FluentMigrator.Runner.Processors.SqlServer { public sealed class SqlServerProcessor : GenericProcessorBase { public override string DatabaseType { get { return "SqlServer"; } } public override bool SupportsTransactions { get { return true; } } public SqlServerProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { } private static string SafeSchemaName(string schemaName) { return string.IsNullOrEmpty(schemaName) ? "dbo" : FormatHelper.FormatSqlEscape(schemaName); } public override bool SchemaExists(string schemaName) { return Exists("SELECT * FROM sys.schemas WHERE NAME = '{0}'", SafeSchemaName(schemaName)); } public override bool TableExists(string schemaName, string tableName) { try { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}'", SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName)); } catch (Exception e) { Console.WriteLine(e); } return false; } public override bool ColumnExists(string schemaName, string tableName, string columnName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND COLUMN_NAME = '{2}'", SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName)); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_CATALOG = DB_NAME() AND TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND CONSTRAINT_NAME = '{2}'", SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(constraintName)); } public override bool IndexExists(string schemaName, string tableName, string indexName) { return Exists("SELECT * FROM sys.indexes WHERE name = '{0}' and object_id=OBJECT_ID('{1}.{2}')", FormatHelper.FormatSqlEscape(indexName), SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName)); } public override bool SequenceExists(string schemaName, string sequenceName) { return Exists("SELECT * FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_SCHEMA = '{0}' AND SEQUENCE_NAME = '{1}'", SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(sequenceName)); } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { string defaultValueAsString = string.Format("%{0}%", FormatHelper.FormatSqlEscape(defaultValue.ToString())); return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND COLUMN_NAME = '{2}' AND COLUMN_DEFAULT LIKE '{3}'", SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName), defaultValueAsString); } public override void Execute(string template, params object[] args) { Process(String.Format(template, args)); } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection, Transaction)) using (var reader = command.ExecuteReader()) { return reader.Read(); } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("SELECT * FROM [{0}].[{1}]", SafeSchemaName(schemaName), tableName); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); var ds = new DataSet(); using (var command = Factory.CreateCommand(String.Format(template, args), Connection, Transaction)) { var adapter = Factory.CreateDataAdapter(command); adapter.Fill(ds); return ds; } } protected override void Process(string sql) { Announcer.Sql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); if (sql.IndexOf("GO", StringComparison.OrdinalIgnoreCase) >= 0) { ExecuteBatchNonQuery(sql); } else { ExecuteNonQuery(sql); } } private void ExecuteNonQuery(string sql) { using (var command = Factory.CreateCommand(sql, Connection, Transaction)) { try { command.CommandTimeout = Options.Timeout; command.ExecuteNonQuery(); } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occured executing the following sql:"); message.WriteLine(sql); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } } private void ExecuteBatchNonQuery(string sql) { sql += "\nGO"; // make sure last batch is executed. string sqlBatch = string.Empty; using (var command = Factory.CreateCommand(string.Empty, Connection, Transaction)) { try { foreach (string line in sql.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.ToUpperInvariant().Trim() == "GO") { if (!string.IsNullOrEmpty(sqlBatch)) { command.CommandText = sqlBatch; command.CommandTimeout = Options.Timeout; command.ExecuteNonQuery(); sqlBatch = string.Empty; } } else { sqlBatch += line + "\n"; } } } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occurred executing the following sql:"); message.WriteLine(sql); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } } public override void Process(PerformDBOperationExpression expression) { Announcer.Say("Performing DB Operation"); if (Options.PreviewOnly) return; EnsureConnectionIsOpen(); if (expression.Operation != null) expression.Operation(Connection, Transaction); } } }
// DirectXTK MakeSpriteFont tool // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 using System; using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.ComponentModel; namespace MakeSpriteFont { // Reusable, reflection based helper for parsing commandline options. public class CommandLineParser { object optionsObject; Queue<FieldInfo> requiredOptions = new Queue<FieldInfo>(); Dictionary<string, FieldInfo> optionalOptions = new Dictionary<string, FieldInfo>(); List<string> requiredUsageHelp = new List<string>(); List<string> optionalUsageHelp = new List<string>(); // Constructor. public CommandLineParser(object optionsObject) { this.optionsObject = optionsObject; // Reflect to find what commandline options are available. foreach (FieldInfo field in optionsObject.GetType().GetFields()) { string fieldName = GetOptionName(field); if (GetAttribute<RequiredAttribute>(field) != null) { // Record a required option. requiredOptions.Enqueue(field); requiredUsageHelp.Add(string.Format("<{0}>", fieldName)); } else { // Record an optional option. optionalOptions.Add(fieldName.ToLowerInvariant(), field); if (field.FieldType == typeof(bool)) { optionalUsageHelp.Add(string.Format("/{0}", fieldName)); } else { optionalUsageHelp.Add(string.Format("/{0}:value", fieldName)); } } } } public bool ParseCommandLine(string[] args) { // Parse each argument in turn. foreach (string arg in args) { if (!ParseArgument(arg.Trim())) { return false; } } // Make sure we got all the required options. FieldInfo missingRequiredOption = requiredOptions.FirstOrDefault(field => !IsList(field) || GetList(field).Count == 0); if (missingRequiredOption != null) { ShowError("Missing argument '{0}'", GetOptionName(missingRequiredOption)); return false; } return true; } bool ParseArgument(string arg) { if (arg.StartsWith("/")) { // Parse an optional argument. char[] separators = { ':' }; string[] split = arg.Substring(1).Split(separators, 2, StringSplitOptions.None); string name = split[0]; string value = (split.Length > 1) ? split[1] : "true"; FieldInfo field; if (!optionalOptions.TryGetValue(name.ToLowerInvariant(), out field)) { ShowError("Unknown option '{0}'", name); return false; } return SetOption(field, value); } else { // Parse a required argument. if (requiredOptions.Count == 0) { ShowError("Too many arguments"); return false; } FieldInfo field = requiredOptions.Peek(); if (!IsList(field)) { requiredOptions.Dequeue(); } return SetOption(field, arg); } } bool SetOption(FieldInfo field, string value) { try { if (IsList(field)) { // Append this value to a list of options. GetList(field).Add(ChangeType(value, ListElementType(field))); } else { // Set the value of a single option. field.SetValue(optionsObject, ChangeType(value, field.FieldType)); } return true; } catch { ShowError("Invalid value '{0}' for option '{1}'", value, GetOptionName(field)); return false; } } static object ChangeType(string value, Type type) { TypeConverter converter = TypeDescriptor.GetConverter(type); return converter.ConvertFromInvariantString(value); } static bool IsList(FieldInfo field) { return typeof(IList).IsAssignableFrom(field.FieldType); } IList GetList(FieldInfo field) { return (IList)field.GetValue(optionsObject); } static Type ListElementType(FieldInfo field) { var interfaces = from i in field.FieldType.GetInterfaces() where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>) select i; return interfaces.First().GetGenericArguments()[0]; } static string GetOptionName(FieldInfo field) { var nameAttribute = GetAttribute<NameAttribute>(field); if (nameAttribute != null) { return nameAttribute.Name; } else { return field.Name; } } void ShowError(string message, params object[] args) { string name = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName); Console.Error.WriteLine(message, args); Console.Error.WriteLine(); Console.Error.WriteLine("Usage: {0} {1}", name, string.Join(" ", requiredUsageHelp)); if (optionalUsageHelp.Count > 0) { Console.Error.WriteLine(); Console.Error.WriteLine("Options:"); foreach (string optional in optionalUsageHelp) { Console.Error.WriteLine(" {0}", optional); } } } static T GetAttribute<T>(ICustomAttributeProvider provider) where T : Attribute { return provider.GetCustomAttributes(typeof(T), false).OfType<T>().FirstOrDefault(); } // Used on optionsObject fields to indicate which options are required. [AttributeUsage(AttributeTargets.Field)] public sealed class RequiredAttribute : Attribute { } // Used on an optionsObject field to rename the corresponding commandline option. [AttributeUsage(AttributeTargets.Field)] public sealed class NameAttribute : Attribute { public NameAttribute(string name) { this.Name = name; } public string Name { get; private set; } } } }
/*------------------------------------------------------------------------- LargeObject.cs This class is a port of the class LargeObject.java implemented by PostgreSQL Global Development Group Copyright (c) 2004, Emiliano Necciari Original Code: Copyright (c) 2003, PostgreSQL Global Development Group Note: (Francisco Figueiredo Jr.) Changed case of method names to conform to .Net names standard. Also changed type names to their true names. i.e. int -> Int32 This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ------------------------------------------------------------------------- */ using System; using System.IO; using Npgsql; namespace NpgsqlTypes { public class LargeObject { /* * Indicates a seek from the begining of a file */ public const Int32 SEEK_SET = 0; /* * Indicates a seek from the current position */ public const Int32 SEEK_CUR = 1; /* * Indicates a seek from the end of a file */ public const Int32 SEEK_END = 2; private Fastpath fp; // Fastpath API to use private Int32 oid; // OID of this object private Int32 fd; // the descriptor of the open large object private Boolean closed = false; // true when we are closed /* * This opens a large object. * * <p>If the object does not exist, then an SQLException is thrown. * * @param fp FastPath API for the connection to use * @param oid of the Large Object to open * @param mode Mode of opening the large object * (defined in LargeObjectManager) * @exception SQLException if a database-access error occurs. * @see org.postgresql.largeobject.LargeObjectManager */ public LargeObject(Fastpath fp, Int32 oid, Int32 mode) { this.fp = fp; this.oid = oid; FastpathArg[] args = new FastpathArg[2]; args[0] = new FastpathArg(oid); args[1] = new FastpathArg(mode); this.fd = fp.GetInteger("lo_open", args); } /* * @return the OID of this LargeObject */ public Int32 GetOID() { return oid; } /* * This method closes the object. You must not call methods in this * object after this is called. * @exception SQLException if a database-access error occurs. */ public void Close() { if (!closed) { // finally close FastpathArg[] args = new FastpathArg[1]; args[0] = new FastpathArg(fd); fp.FastpathCall("lo_close", false, args); // true here as we dont care!! closed = true; } } /* * Reads some data from the object, and return as a byte[] array * * @param len number of bytes to read * @return byte[] array containing data read * @exception SQLException if a database-access error occurs. */ public Byte[] Read(Int32 len) { // This is the original method, where the entire block (len bytes) // is retrieved in one go. FastpathArg[] args = new FastpathArg[2]; args[0] = new FastpathArg(fd); args[1] = new FastpathArg(len); return fp.GetData("loread", args); // This version allows us to break this down Int32o 4k blocks //if (len<=4048) { //// handle as before, return the whole block in one go //FastpathArg args[] = new FastpathArg[2]; //args[0] = new FastpathArg(fd); //args[1] = new FastpathArg(len); //return fp.getData("loread",args); //} else { //// return in 4k blocks //byte[] buf=new byte[len]; //int off=0; //while (len>0) { //int bs=4048; //len-=bs; //if (len<0) { //bs+=len; //len=0; //} //read(buf,off,bs); //off+=bs; //} //return buf; //} } /* * Reads some data from the object into an existing array * * @param buf destination array * @param off offset within array * @param len number of bytes to read * @return the number of bytes actually read * @exception SQLException if a database-access error occurs. */ public Int32 Read(Byte[] buf, Int32 off, Int32 len) { Byte[] b = Read(len); if (b.Length < len) len = b.Length; Array.Copy(b,0,buf,off,len); return len; } /* * Writes an array to the object * * @param buf array to write * @exception SQLException if a database-access error occurs. */ public void Write(Byte[] buf) { FastpathArg[] args = new FastpathArg[2]; args[0] = new FastpathArg(fd); args[1] = new FastpathArg(buf); fp.FastpathCall("lowrite", false, args); } /* * Writes some data from an array to the object * * @param buf destination array * @param off offset within array * @param len number of bytes to write * @exception SQLException if a database-access error occurs. */ public void Write(Byte[] buf, Int32 off, Int32 len) { Byte[] data = new Byte[len]; System.Array.Copy(buf, off, data, 0, len); Write(data); } /* * Sets the current position within the object. * * <p>This is similar to the fseek() call in the standard C library. It * allows you to have random access to the large object. * * @param pos position within object * @param ref Either SEEK_SET, SEEK_CUR or SEEK_END * @exception SQLException if a database-access error occurs. */ public void Seek(Int32 pos, Int32 refi) { FastpathArg[] args = new FastpathArg[3]; args[0] = new FastpathArg(fd); args[1] = new FastpathArg(pos); args[2] = new FastpathArg(refi); fp.FastpathCall("lo_lseek", false, args); } /* * Sets the current position within the object. * * <p>This is similar to the fseek() call in the standard C library. It * allows you to have random access to the large object. * * @param pos position within object from begining * @exception SQLException if a database-access error occurs. */ public void Seek(Int32 pos) { Seek(pos, SEEK_SET); } /* * @return the current position within the object * @exception SQLException if a database-access error occurs. */ public Int32 Tell() { FastpathArg[] args = new FastpathArg[1]; args[0] = new FastpathArg(fd); return fp.GetInteger("lo_tell", args); } /* * This method is inefficient, as the only way to find out the size of * the object is to seek to the end, record the current position, then * return to the original position. * * <p>A better method will be found in the future. * * @return the size of the large object * @exception SQLException if a database-access error occurs. */ public Int32 Size() { Int32 cp = Tell(); Seek(0, SEEK_END); Int32 sz = Tell(); Seek(cp, SEEK_SET); return sz; } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\GameNetworkManager.h:27 namespace UnrealEngine { public partial class AGameNetworkManager : AInfo { public AGameNetworkManager(IntPtr adress) : base(adress) { } public AGameNetworkManager(UObject Parent = null, string Name = "GameNetworkManager") : base(IntPtr.Zero) { NativePointer = E_NewObject_AGameNetworkManager(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_AdjustedNetSpeed_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_AdjustedNetSpeed_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_BadPingThreshold_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_BadPingThreshold_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyDetection_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyDetection_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyForceCorrectionsDuringResolution_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyForceCorrectionsDuringResolution_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyResolution_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyResolution_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_AGameNetworkManager_bUseDistanceBasedRelevancy_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_bUseDistanceBasedRelevancy_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_CLIENTADJUSTUPDATECOST_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_CLIENTADJUSTUPDATECOST_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_PROP_AGameNetworkManager_ClientAuthorativePosition_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientAuthorativePosition_SET(IntPtr Ptr, bool Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_ClientErrorUpdateRateLimit_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientErrorUpdateRateLimit_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeStationary_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeStationary_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeThrottled_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeThrottled_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleAtNetSpeed_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleAtNetSpeed_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleOverPlayerCount_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleOverPlayerCount_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_JoinInProgressStandbyWaitTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_JoinInProgressStandbyWaitTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_LastNetSpeedUpdateTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_LastNetSpeedUpdateTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MaxClientForcedUpdateDuration_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MaxClientForcedUpdateDuration_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MaxClientSmoothingDeltaTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MaxClientSmoothingDeltaTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MAXCLIENTUPDATEINTERVAL_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MAXCLIENTUPDATEINTERVAL_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_MaxDynamicBandwidth_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MaxDynamicBandwidth_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MaxMoveDeltaTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MaxMoveDeltaTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MAXNEARZEROVELOCITYSQUARED_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MAXNEARZEROVELOCITYSQUARED_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MAXPOSITIONERRORSQUARED_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MAXPOSITIONERRORSQUARED_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_MinDynamicBandwidth_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MinDynamicBandwidth_SET(IntPtr Ptr, int Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MovementTimeDiscrepancyDriftAllowance_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MovementTimeDiscrepancyDriftAllowance_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMaxTimeMargin_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMaxTimeMargin_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMinTimeMargin_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMinTimeMargin_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MovementTimeDiscrepancyResolutionRate_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MovementTimeDiscrepancyResolutionRate_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_MoveRepSize_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_MoveRepSize_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_PercentForBadPing_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_PercentForBadPing_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_PercentMissingForRxStandby_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_PercentMissingForRxStandby_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_PercentMissingForTxStandby_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_PercentMissingForTxStandby_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_StandbyRxCheatTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_StandbyRxCheatTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_AGameNetworkManager_StandbyTxCheatTime_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_StandbyTxCheatTime_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_PROP_AGameNetworkManager_TotalNetBandwidth_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_AGameNetworkManager_TotalNetBandwidth_SET(IntPtr Ptr, int Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_AGameNetworkManager(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_AGameNetworkManager_CalculatedNetSpeed(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_AGameNetworkManager_EnableStandbyCheatDetection(IntPtr self, bool bIsEnabled); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_AGameNetworkManager_ExceedsAllowablePositionError(IntPtr self, IntPtr locDiff); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_AGameNetworkManager_IsInLowBandwidthMode(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_AGameNetworkManager_NetworkVelocityNearZero(IntPtr self, IntPtr inVelocity); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_AGameNetworkManager_StandbyCheatDetected(IntPtr self, byte standbyType); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_AGameNetworkManager_UpdateNetSpeeds(IntPtr self, bool bIsLanMatch); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_AGameNetworkManager_UpdateNetSpeedsTimer(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_AGameNetworkManager_WithinUpdateDelayBounds(IntPtr self, IntPtr pC, float lastUpdateTime); #endregion #region Property public int AdjustedNetSpeed { get => E_PROP_AGameNetworkManager_AdjustedNetSpeed_GET(NativePointer); set => E_PROP_AGameNetworkManager_AdjustedNetSpeed_SET(NativePointer, value); } public int BadPingThreshold { get => E_PROP_AGameNetworkManager_BadPingThreshold_GET(NativePointer); set => E_PROP_AGameNetworkManager_BadPingThreshold_SET(NativePointer, value); } public bool bMovementTimeDiscrepancyDetection { get => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyDetection_GET(NativePointer); set => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyDetection_SET(NativePointer, value); } public bool bMovementTimeDiscrepancyForceCorrectionsDuringResolution { get => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyForceCorrectionsDuringResolution_GET(NativePointer); set => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyForceCorrectionsDuringResolution_SET(NativePointer, value); } public bool bMovementTimeDiscrepancyResolution { get => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyResolution_GET(NativePointer); set => E_PROP_AGameNetworkManager_bMovementTimeDiscrepancyResolution_SET(NativePointer, value); } public bool bUseDistanceBasedRelevancy { get => E_PROP_AGameNetworkManager_bUseDistanceBasedRelevancy_GET(NativePointer); set => E_PROP_AGameNetworkManager_bUseDistanceBasedRelevancy_SET(NativePointer, value); } public float CLIENTADJUSTUPDATECOST { get => E_PROP_AGameNetworkManager_CLIENTADJUSTUPDATECOST_GET(NativePointer); set => E_PROP_AGameNetworkManager_CLIENTADJUSTUPDATECOST_SET(NativePointer, value); } public bool ClientAuthorativePosition { get => E_PROP_AGameNetworkManager_ClientAuthorativePosition_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientAuthorativePosition_SET(NativePointer, value); } public float ClientErrorUpdateRateLimit { get => E_PROP_AGameNetworkManager_ClientErrorUpdateRateLimit_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientErrorUpdateRateLimit_SET(NativePointer, value); } public float ClientNetSendMoveDeltaTime { get => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTime_SET(NativePointer, value); } public float ClientNetSendMoveDeltaTimeStationary { get => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeStationary_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeStationary_SET(NativePointer, value); } public float ClientNetSendMoveDeltaTimeThrottled { get => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeThrottled_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientNetSendMoveDeltaTimeThrottled_SET(NativePointer, value); } public int ClientNetSendMoveThrottleAtNetSpeed { get => E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleAtNetSpeed_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleAtNetSpeed_SET(NativePointer, value); } public int ClientNetSendMoveThrottleOverPlayerCount { get => E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleOverPlayerCount_GET(NativePointer); set => E_PROP_AGameNetworkManager_ClientNetSendMoveThrottleOverPlayerCount_SET(NativePointer, value); } public float JoinInProgressStandbyWaitTime { get => E_PROP_AGameNetworkManager_JoinInProgressStandbyWaitTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_JoinInProgressStandbyWaitTime_SET(NativePointer, value); } public float LastNetSpeedUpdateTime { get => E_PROP_AGameNetworkManager_LastNetSpeedUpdateTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_LastNetSpeedUpdateTime_SET(NativePointer, value); } public float MaxClientForcedUpdateDuration { get => E_PROP_AGameNetworkManager_MaxClientForcedUpdateDuration_GET(NativePointer); set => E_PROP_AGameNetworkManager_MaxClientForcedUpdateDuration_SET(NativePointer, value); } public float MaxClientSmoothingDeltaTime { get => E_PROP_AGameNetworkManager_MaxClientSmoothingDeltaTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_MaxClientSmoothingDeltaTime_SET(NativePointer, value); } public float MAXCLIENTUPDATEINTERVAL { get => E_PROP_AGameNetworkManager_MAXCLIENTUPDATEINTERVAL_GET(NativePointer); set => E_PROP_AGameNetworkManager_MAXCLIENTUPDATEINTERVAL_SET(NativePointer, value); } public int MaxDynamicBandwidth { get => E_PROP_AGameNetworkManager_MaxDynamicBandwidth_GET(NativePointer); set => E_PROP_AGameNetworkManager_MaxDynamicBandwidth_SET(NativePointer, value); } public float MaxMoveDeltaTime { get => E_PROP_AGameNetworkManager_MaxMoveDeltaTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_MaxMoveDeltaTime_SET(NativePointer, value); } public float MAXNEARZEROVELOCITYSQUARED { get => E_PROP_AGameNetworkManager_MAXNEARZEROVELOCITYSQUARED_GET(NativePointer); set => E_PROP_AGameNetworkManager_MAXNEARZEROVELOCITYSQUARED_SET(NativePointer, value); } public float MAXPOSITIONERRORSQUARED { get => E_PROP_AGameNetworkManager_MAXPOSITIONERRORSQUARED_GET(NativePointer); set => E_PROP_AGameNetworkManager_MAXPOSITIONERRORSQUARED_SET(NativePointer, value); } public int MinDynamicBandwidth { get => E_PROP_AGameNetworkManager_MinDynamicBandwidth_GET(NativePointer); set => E_PROP_AGameNetworkManager_MinDynamicBandwidth_SET(NativePointer, value); } public float MovementTimeDiscrepancyDriftAllowance { get => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyDriftAllowance_GET(NativePointer); set => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyDriftAllowance_SET(NativePointer, value); } public float MovementTimeDiscrepancyMaxTimeMargin { get => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMaxTimeMargin_GET(NativePointer); set => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMaxTimeMargin_SET(NativePointer, value); } public float MovementTimeDiscrepancyMinTimeMargin { get => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMinTimeMargin_GET(NativePointer); set => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyMinTimeMargin_SET(NativePointer, value); } public float MovementTimeDiscrepancyResolutionRate { get => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyResolutionRate_GET(NativePointer); set => E_PROP_AGameNetworkManager_MovementTimeDiscrepancyResolutionRate_SET(NativePointer, value); } public float MoveRepSize { get => E_PROP_AGameNetworkManager_MoveRepSize_GET(NativePointer); set => E_PROP_AGameNetworkManager_MoveRepSize_SET(NativePointer, value); } public float PercentForBadPing { get => E_PROP_AGameNetworkManager_PercentForBadPing_GET(NativePointer); set => E_PROP_AGameNetworkManager_PercentForBadPing_SET(NativePointer, value); } public float PercentMissingForRxStandby { get => E_PROP_AGameNetworkManager_PercentMissingForRxStandby_GET(NativePointer); set => E_PROP_AGameNetworkManager_PercentMissingForRxStandby_SET(NativePointer, value); } public float PercentMissingForTxStandby { get => E_PROP_AGameNetworkManager_PercentMissingForTxStandby_GET(NativePointer); set => E_PROP_AGameNetworkManager_PercentMissingForTxStandby_SET(NativePointer, value); } public float StandbyRxCheatTime { get => E_PROP_AGameNetworkManager_StandbyRxCheatTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_StandbyRxCheatTime_SET(NativePointer, value); } public float StandbyTxCheatTime { get => E_PROP_AGameNetworkManager_StandbyTxCheatTime_GET(NativePointer); set => E_PROP_AGameNetworkManager_StandbyTxCheatTime_SET(NativePointer, value); } public int TotalNetBandwidth { get => E_PROP_AGameNetworkManager_TotalNetBandwidth_GET(NativePointer); set => E_PROP_AGameNetworkManager_TotalNetBandwidth_SET(NativePointer, value); } #endregion #region ExternMethods /// <summary> /// @RETURN new per/client bandwidth given number of players in the game /// </summary> public virtual int CalculatedNetSpeed() => E_AGameNetworkManager_CalculatedNetSpeed(this); /// <summary> /// Turns standby detection on/off /// </summary> /// <param name="bIsEnabled">true to turn it on, false to disable it</param> public virtual void EnableStandbyCheatDetection(bool bIsEnabled) => E_AGameNetworkManager_EnableStandbyCheatDetection(this, bIsEnabled); /// <summary> /// </summary> /// <return>true</return> public virtual bool ExceedsAllowablePositionError(FVector locDiff) => E_AGameNetworkManager_ExceedsAllowablePositionError(this, locDiff); /// <summary> /// Returns true if we should be in low bandwidth mode /// </summary> public virtual bool IsInLowBandwidthMode() => E_AGameNetworkManager_IsInLowBandwidthMode(this); /// <summary> /// </summary> /// <return>true</return> public virtual bool NetworkVelocityNearZero(FVector inVelocity) => E_AGameNetworkManager_NetworkVelocityNearZero(this, inVelocity); /// <summary> /// Notifies the game code that a standby cheat was detected /// </summary> /// <param name="standbyType">the type of cheat detected</param> public virtual void StandbyCheatDetected(EStandbyType standbyType) => E_AGameNetworkManager_StandbyCheatDetected(this, (byte)standbyType); /// <summary> /// Update network speeds for listen servers based on number of connected players. /// </summary> public virtual void UpdateNetSpeeds(bool bIsLanMatch) => E_AGameNetworkManager_UpdateNetSpeeds(this, bIsLanMatch); /// <summary> /// Timer which calls UpdateNetSpeeds() once a second. /// </summary> public virtual void UpdateNetSpeedsTimer() => E_AGameNetworkManager_UpdateNetSpeedsTimer(this); /// <summary> /// </summary> /// <return>true</return> public virtual bool WithinUpdateDelayBounds(APlayerController pC, float lastUpdateTime) => E_AGameNetworkManager_WithinUpdateDelayBounds(this, pC, lastUpdateTime); #endregion public static implicit operator IntPtr(AGameNetworkManager self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator AGameNetworkManager(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<AGameNetworkManager>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Caching; using System.Collections.Concurrent; using System.Threading; using System.Diagnostics; using System.IO; using System.Drawing; using ILPathways.Utilities; namespace Isle.BizServices { //A self-managing queue system to handle thumbnailing in a synchronous, serial manner from asynchronous calls from multiple threads public class ThumbnailServices { //Take an existing image (ie a custom image), resize it to thumbnail size, then copy it into the thumbnail folder, overwriting as necessary public static void CopyCustomImageToThumbnail( Image originalImage, int resourceID ) { if ( UtilityManager.GetAppKeyValue( "creatingThumbnails" ) == "yes" && resourceID > 0 && originalImage != null ) { var size = new Size( 400, 300 ); var stream = new MemoryStream(); new Bitmap( originalImage, size ).Save( stream, System.Drawing.Imaging.ImageFormat.Png ); var bytes = stream.ToArray(); var thumbnailFolder = UtilityManager.GetAppKeyValue( "serverThumbnailFolder", @"\\OERSQL\OerThumbs\large\" ); File.WriteAllBytes( thumbnailFolder + resourceID + "-large.png", bytes ); } } //This gets called from other methods public static void CreateThumbnail( string filename, string url, bool overwriteIfExists ) { //Skip if not creating thumbs in this env if ( UtilityManager.GetAppKeyValue( "creatingThumbnails", "no" ) != "yes" ) { return; } //Create the round var bullet = new ThumbnailItem() { Filename = filename, Url = url, OverwriteIfExists = overwriteIfExists, Firing = false }; //Load the round into the end of the chain var chain = GetChain(); chain.Enqueue( bullet ); //Pull the trigger ThreadPool.QueueUserWorkItem( delegate { Fire(); //chain.First().Fire(); } ); }// //Examine the chain without creating one if it doesn't exist public static List<ThumbnailItem> ExamineChain() { var result = new List<ThumbnailItem>(); var cache = MemoryCache.Default; var chain = cache[ "ThumbnailChain" ] as ConcurrentQueue<ThumbnailItem>; if ( chain != null ) { foreach ( var item in chain ) { result.Add( new ThumbnailItem() //Ensure we do not pass by reference { Filename = item.Filename, Url = item.Url, OverwriteIfExists = item.OverwriteIfExists, Firing = item.Firing } ); } } return result; } //Get the chain of ammo using thread-safe FIFO list static private ConcurrentQueue<ThumbnailItem> GetChain() { var cache = MemoryCache.Default; var chain = cache[ "ThumbnailChain" ] as ConcurrentQueue<ThumbnailItem>; if ( chain == null ) { DumpChain(); chain = new ConcurrentQueue<ThumbnailItem>(); string thumbnailerLog = UtilityManager.GetAppKeyValue( "thumbnailerLog", "C:\\Thumbnail Generator 4\\lastrun.txt" ); Log( thumbnailerLog, "", true ); //Refresh the log file var item = new CacheItem( "ThumbnailChain", chain ); var policy = new CacheItemPolicy(); policy.SlidingExpiration = new TimeSpan( 0, 15, 0 ); cache.Add( item, policy ); } return chain; } //Get rid of the chain static private void DumpChain() { var cache = MemoryCache.Default; cache.Remove( "ThumbnailChain" ); } //Write to thumbnail log file static private void Log( string fileName, string text, bool overWrite ) { var success = false; while ( !success ) { try { if ( overWrite ) { File.WriteAllText( fileName, text + System.Environment.NewLine ); } else { File.AppendAllText( fileName, text + System.Environment.NewLine ); } success = true; } catch ( IOException ex ) { Thread.Sleep( 50 ); } } }// //Make a thumbnail static private void Fire() { //Aim correctly string thumbnailerLog = UtilityManager.GetAppKeyValue( "thumbnailerLog", "C:\\Thumbnail Generator 4\\lastrun.txt" ); string thumbnailerWorkingDirectory = UtilityManager.GetAppKeyValue( "thumbnailGeneratorV2Folder", "C:\\Thumbnail Generator 4" ); string thumbnailGenerator = UtilityManager.GetAppKeyValue( "thumbnailGenerator", "C:\\Thumbnail Generator 4\\ThumbnailerV4User.exe" ); //Feed the ammo var chain = GetChain(); //Start shooting while ( chain != null && chain.Count() > 0 ) { if ( chain.Where( m => m.Firing ).Count() == 0 ) { //Load the first round var chambered = chain.First(); //Prevent other rounds from firing chambered.Firing = true; //Only use live ammo on production/where desired if ( ServiceHelper.GetAppKeyValue( "creatingThumbnails", "no" ) == "yes" ) { //Fire try { var arguments = chambered.Filename + " \"" + chambered.Url + "\" " + ( chambered.OverwriteIfExists ? "true" : "false" ); var processInfo = new ProcessStartInfo( thumbnailGenerator, arguments ); processInfo.WorkingDirectory = thumbnailerWorkingDirectory; processInfo.CreateNoWindow = false; processInfo.UseShellExecute = false; var process = Process.Start( processInfo ); process.WaitForExit( 30000 ); process.Close(); Log( thumbnailerLog, "Thumbnail " + chambered.Filename + " should now exist.", false ); Log( thumbnailerLog, "Waiting for Chrome to finish closing", false ); Thread.Sleep( 5000 ); } catch ( Exception ex ) { Log( thumbnailerLog, "Project Level Error: " + System.Environment.NewLine + ex.Message.ToString(), false ); } } else { //Shoot blank Thread.Sleep( 5000 ); Log( thumbnailerLog, "Simulated thumbnail created successfully: " + chambered.Filename, false ); } //Eject the spent casing try { var spent = new ThumbnailItem(); chain.TryDequeue( out spent ); } catch ( Exception ex ) { //Prevent rogue threads - better to miss thumbnails than overload the server Log( thumbnailerLog, "Thumbnail chain jammed! Dumping entries..." + System.Environment.NewLine + ex.Message.ToString(), false ); DumpChain(); } } else { //Ensure only one thread is working on the entire queue at a time Log( thumbnailerLog, "Another thread is handling this. Current thread is exiting.", false ); return; //Wait and try firing again //Thread.Sleep( 1000 ); } } //Eject empty magazine Log( thumbnailerLog, "All thumbnails should be finished", false ); DumpChain(); } //Ammunition public class ThumbnailItem { public bool Firing { get; set; } public string Filename { get; set; } public string Url { get; set; } public bool OverwriteIfExists { get; set; } } } //End ThumbnailServices }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Google.ProtocolBuffers.TestProtos { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class UnitTestEmbedOptimizeForProtoFile { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestEmbedOptimizedForSize__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize.Builder> internal__static_protobuf_unittest_TestEmbedOptimizedForSize__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static UnitTestEmbedOptimizeForProtoFile() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjFnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfZW1iZWRfb3B0aW1pemVfZm9y", "LnByb3RvEhFwcm90b2J1Zl91bml0dGVzdBokZ29vZ2xlL3Byb3RvYnVmL2Nz", "aGFycF9vcHRpb25zLnByb3RvGitnb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rf", "b3B0aW1pemVfZm9yLnByb3RvIqEBChlUZXN0RW1iZWRPcHRpbWl6ZWRGb3JT", "aXplEkEKEG9wdGlvbmFsX21lc3NhZ2UYASABKAsyJy5wcm90b2J1Zl91bml0", "dGVzdC5UZXN0T3B0aW1pemVkRm9yU2l6ZRJBChByZXBlYXRlZF9tZXNzYWdl", "GAIgAygLMicucHJvdG9idWZfdW5pdHRlc3QuVGVzdE9wdGltaXplZEZvclNp", "emVCS0gBwj5GCiFHb29nbGUuUHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90b3MS", "IVVuaXRUZXN0RW1iZWRPcHRpbWl6ZUZvclByb3RvRmlsZQ==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_protobuf_unittest_TestEmbedOptimizedForSize__Descriptor = Descriptor.MessageTypes[0]; internal__static_protobuf_unittest_TestEmbedOptimizedForSize__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestEmbedOptimizedForSize__Descriptor, new string[] { "OptionalMessage", "RepeatedMessage", }); pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); RegisterAllExtensions(registry); global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry); global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.RegisterAllExtensions(registry); return registry; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor, global::Google.ProtocolBuffers.TestProtos.UnitTestOptimizeForProtoFile.Descriptor, }, assigner); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class TestEmbedOptimizedForSize : pb::GeneratedMessage<TestEmbedOptimizedForSize, TestEmbedOptimizedForSize.Builder> { private TestEmbedOptimizedForSize() { } private static readonly TestEmbedOptimizedForSize defaultInstance = new TestEmbedOptimizedForSize().MakeReadOnly(); private static readonly string[] _testEmbedOptimizedForSizeFieldNames = new string[] { "optional_message", "repeated_message" }; private static readonly uint[] _testEmbedOptimizedForSizeFieldTags = new uint[] { 10, 18 }; public static TestEmbedOptimizedForSize DefaultInstance { get { return defaultInstance; } } public override TestEmbedOptimizedForSize DefaultInstanceForType { get { return DefaultInstance; } } protected override TestEmbedOptimizedForSize ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestEmbedOptimizeForProtoFile.internal__static_protobuf_unittest_TestEmbedOptimizedForSize__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<TestEmbedOptimizedForSize, TestEmbedOptimizedForSize.Builder> InternalFieldAccessors { get { return global::Google.ProtocolBuffers.TestProtos.UnitTestEmbedOptimizeForProtoFile.internal__static_protobuf_unittest_TestEmbedOptimizedForSize__FieldAccessorTable; } } public const int OptionalMessageFieldNumber = 1; private bool hasOptionalMessage; private global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize optionalMessage_; public bool HasOptionalMessage { get { return hasOptionalMessage; } } public global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize OptionalMessage { get { return optionalMessage_ ?? global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.DefaultInstance; } } public const int RepeatedMessageFieldNumber = 2; private pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize> repeatedMessage_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize>(); public scg::IList<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize> RepeatedMessageList { get { return repeatedMessage_; } } public int RepeatedMessageCount { get { return repeatedMessage_.Count; } } public global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize GetRepeatedMessage(int index) { return repeatedMessage_[index]; } public override bool IsInitialized { get { if (HasOptionalMessage) { if (!OptionalMessage.IsInitialized) return false; } foreach (global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize element in RepeatedMessageList) { if (!element.IsInitialized) return false; } return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _testEmbedOptimizedForSizeFieldNames; if (hasOptionalMessage) { output.WriteMessage(1, field_names[0], OptionalMessage); } if (repeatedMessage_.Count > 0) { output.WriteMessageArray(2, field_names[1], repeatedMessage_); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasOptionalMessage) { size += pb::CodedOutputStream.ComputeMessageSize(1, OptionalMessage); } foreach (global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize element in RepeatedMessageList) { size += pb::CodedOutputStream.ComputeMessageSize(2, element); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static TestEmbedOptimizedForSize ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static TestEmbedOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static TestEmbedOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private TestEmbedOptimizedForSize MakeReadOnly() { repeatedMessage_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(TestEmbedOptimizedForSize prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<TestEmbedOptimizedForSize, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(TestEmbedOptimizedForSize cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private TestEmbedOptimizedForSize result; private TestEmbedOptimizedForSize PrepareBuilder() { if (resultIsReadOnly) { TestEmbedOptimizedForSize original = result; result = new TestEmbedOptimizedForSize(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override TestEmbedOptimizedForSize MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize.Descriptor; } } public override TestEmbedOptimizedForSize DefaultInstanceForType { get { return global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize.DefaultInstance; } } public override TestEmbedOptimizedForSize BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is TestEmbedOptimizedForSize) { return MergeFrom((TestEmbedOptimizedForSize) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(TestEmbedOptimizedForSize other) { if (other == global::Google.ProtocolBuffers.TestProtos.TestEmbedOptimizedForSize.DefaultInstance) return this; PrepareBuilder(); if (other.HasOptionalMessage) { MergeOptionalMessage(other.OptionalMessage); } if (other.repeatedMessage_.Count != 0) { result.repeatedMessage_.Add(other.repeatedMessage_); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_testEmbedOptimizedForSizeFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _testEmbedOptimizedForSizeFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder subBuilder = global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.CreateBuilder(); if (result.hasOptionalMessage) { subBuilder.MergeFrom(OptionalMessage); } input.ReadMessage(subBuilder, extensionRegistry); OptionalMessage = subBuilder.BuildPartial(); break; } case 18: { input.ReadMessageArray(tag, field_name, result.repeatedMessage_, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.DefaultInstance, extensionRegistry); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasOptionalMessage { get { return result.hasOptionalMessage; } } public global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize OptionalMessage { get { return result.OptionalMessage; } set { SetOptionalMessage(value); } } public Builder SetOptionalMessage(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasOptionalMessage = true; result.optionalMessage_ = value; return this; } public Builder SetOptionalMessage(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasOptionalMessage = true; result.optionalMessage_ = builderForValue.Build(); return this; } public Builder MergeOptionalMessage(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasOptionalMessage && result.optionalMessage_ != global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.DefaultInstance) { result.optionalMessage_ = global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.CreateBuilder(result.optionalMessage_).MergeFrom(value).BuildPartial(); } else { result.optionalMessage_ = value; } result.hasOptionalMessage = true; return this; } public Builder ClearOptionalMessage() { PrepareBuilder(); result.hasOptionalMessage = false; result.optionalMessage_ = null; return this; } public pbc::IPopsicleList<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize> RepeatedMessageList { get { return PrepareBuilder().repeatedMessage_; } } public int RepeatedMessageCount { get { return result.RepeatedMessageCount; } } public global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize GetRepeatedMessage(int index) { return result.GetRepeatedMessage(index); } public Builder SetRepeatedMessage(int index, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.repeatedMessage_[index] = value; return this; } public Builder SetRepeatedMessage(int index, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.repeatedMessage_[index] = builderForValue.Build(); return this; } public Builder AddRepeatedMessage(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.repeatedMessage_.Add(value); return this; } public Builder AddRepeatedMessage(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.repeatedMessage_.Add(builderForValue.Build()); return this; } public Builder AddRangeRepeatedMessage(scg::IEnumerable<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize> values) { PrepareBuilder(); result.repeatedMessage_.Add(values); return this; } public Builder ClearRepeatedMessage() { PrepareBuilder(); result.repeatedMessage_.Clear(); return this; } } static TestEmbedOptimizedForSize() { object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestEmbedOptimizeForProtoFile.Descriptor, null); } } #endregion } #endregion Designer generated code
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using Newtonsoft.Json.Utilities; using System.Globalization; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; #endif #if HAVE_BIG_INTEGER using System.Numerics; #endif namespace Newtonsoft.Json.Linq { /// <summary> /// Represents a value in JSON (string, integer, date, etc). /// </summary> public partial class JValue : JToken, IEquatable<JValue>, IFormattable, IComparable, IComparable<JValue> #if HAVE_ICONVERTIBLE , IConvertible #endif { private JTokenType _valueType; private object _value; internal JValue(object value, JTokenType type) { _value = value; _valueType = type; } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class from another <see cref="JValue"/> object. /// </summary> /// <param name="other">A <see cref="JValue"/> object to copy from.</param> public JValue(JValue other) : this(other.Value, other.Type) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(long value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(decimal value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(char value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> [CLSCompliant(false)] public JValue(ulong value) : this(value, JTokenType.Integer) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(double value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(float value) : this(value, JTokenType.Float) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTime value) : this(value, JTokenType.Date) { } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(DateTimeOffset value) : this(value, JTokenType.Date) { } #endif /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(bool value) : this(value, JTokenType.Boolean) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(string value) : this(value, JTokenType.String) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Guid value) : this(value, JTokenType.Guid) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(Uri value) : this(value, (value != null) ? JTokenType.Uri : JTokenType.Null) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(TimeSpan value) : this(value, JTokenType.TimeSpan) { } /// <summary> /// Initializes a new instance of the <see cref="JValue"/> class with the given value. /// </summary> /// <param name="value">The value.</param> public JValue(object value) : this(value, GetValueType(null, value)) { } internal override bool DeepEquals(JToken node) { JValue other = node as JValue; if (other == null) { return false; } if (other == this) { return true; } return ValuesEquals(this, other); } /// <summary> /// Gets a value indicating whether this token has child tokens. /// </summary> /// <value> /// <c>true</c> if this token has child values; otherwise, <c>false</c>. /// </value> public override bool HasValues { get { return false; } } #if HAVE_BIG_INTEGER private static int CompareBigInteger(BigInteger i1, object i2) { int result = i1.CompareTo(ConvertUtils.ToBigInteger(i2)); if (result != 0) { return result; } // converting a fractional number to a BigInteger will lose the fraction // check for fraction if result is two numbers are equal if (i2 is decimal) { decimal d = (decimal)i2; return (0m).CompareTo(Math.Abs(d - Math.Truncate(d))); } else if (i2 is double || i2 is float) { double d = Convert.ToDouble(i2, CultureInfo.InvariantCulture); return (0d).CompareTo(Math.Abs(d - Math.Truncate(d))); } return result; } #endif internal static int Compare(JTokenType valueType, object objA, object objB) { if (objA == objB) { return 0; } if (objB == null) { return 1; } if (objA == null) { return -1; } switch (valueType) { case JTokenType.Integer: #if HAVE_BIG_INTEGER if (objA is BigInteger) { return CompareBigInteger((BigInteger)objA, objB); } if (objB is BigInteger) { return -CompareBigInteger((BigInteger)objB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } else if (objA is float || objB is float || objA is double || objB is double) { return CompareFloat(objA, objB); } else { return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture)); } case JTokenType.Float: #if HAVE_BIG_INTEGER if (objA is BigInteger) { return CompareBigInteger((BigInteger)objA, objB); } if (objB is BigInteger) { return -CompareBigInteger((BigInteger)objB, objA); } #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture)); } return CompareFloat(objA, objB); case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture); string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture); return string.CompareOrdinal(s1, s2); case JTokenType.Boolean: bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture); bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture); return b1.CompareTo(b2); case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (objA is DateTime) { #endif DateTime date1 = (DateTime)objA; DateTime date2; #if HAVE_DATE_TIME_OFFSET if (objB is DateTimeOffset) { date2 = ((DateTimeOffset)objB).DateTime; } else #endif { date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture); } return date1.CompareTo(date2); #if HAVE_DATE_TIME_OFFSET } else { DateTimeOffset date1 = (DateTimeOffset)objA; DateTimeOffset date2; if (objB is DateTimeOffset) { date2 = (DateTimeOffset)objB; } else { date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture)); } return date1.CompareTo(date2); } #endif case JTokenType.Bytes: byte[] bytes2 = objB as byte[]; if (bytes2 == null) { throw new ArgumentException("Object must be of type byte[]."); } byte[] bytes1 = objA as byte[]; Debug.Assert(bytes1 != null); return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2); case JTokenType.Guid: if (!(objB is Guid)) { throw new ArgumentException("Object must be of type Guid."); } Guid guid1 = (Guid)objA; Guid guid2 = (Guid)objB; return guid1.CompareTo(guid2); case JTokenType.Uri: Uri uri2 = objB as Uri; if (uri2 == null) { throw new ArgumentException("Object must be of type Uri."); } Uri uri1 = (Uri)objA; return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString()); case JTokenType.TimeSpan: if (!(objB is TimeSpan)) { throw new ArgumentException("Object must be of type TimeSpan."); } TimeSpan ts1 = (TimeSpan)objA; TimeSpan ts2 = (TimeSpan)objB; return ts1.CompareTo(ts2); default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(valueType), valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType)); } } private static int CompareFloat(object objA, object objB) { double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); // take into account possible floating point errors if (MathUtils.ApproxEquals(d1, d2)) { return 0; } return d1.CompareTo(d2); } #if HAVE_EXPRESSIONS private static bool Operation(ExpressionType operation, object objA, object objB, out object result) { if (objA is string || objB is string) { if (operation == ExpressionType.Add || operation == ExpressionType.AddAssign) { result = objA?.ToString() + objB?.ToString(); return true; } } #if HAVE_BIG_INTEGER if (objA is BigInteger || objB is BigInteger) { if (objA == null || objB == null) { result = null; return true; } // not that this will lose the fraction // BigInteger doesn't have operators with non-integer types BigInteger i1 = ConvertUtils.ToBigInteger(objA); BigInteger i2 = ConvertUtils.ToBigInteger(objB); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = i1 + i2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = i1 - i2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = i1 * i2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = i1 / i2; return true; } } else #endif if (objA is ulong || objB is ulong || objA is decimal || objB is decimal) { if (objA == null || objB == null) { result = null; return true; } decimal d1 = Convert.ToDecimal(objA, CultureInfo.InvariantCulture); decimal d2 = Convert.ToDecimal(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is float || objB is float || objA is double || objB is double) { if (objA == null || objB == null) { result = null; return true; } double d1 = Convert.ToDouble(objA, CultureInfo.InvariantCulture); double d2 = Convert.ToDouble(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = d1 + d2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = d1 - d2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = d1 * d2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = d1 / d2; return true; } } else if (objA is int || objA is uint || objA is long || objA is short || objA is ushort || objA is sbyte || objA is byte || objB is int || objB is uint || objB is long || objB is short || objB is ushort || objB is sbyte || objB is byte) { if (objA == null || objB == null) { result = null; return true; } long l1 = Convert.ToInt64(objA, CultureInfo.InvariantCulture); long l2 = Convert.ToInt64(objB, CultureInfo.InvariantCulture); switch (operation) { case ExpressionType.Add: case ExpressionType.AddAssign: result = l1 + l2; return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: result = l1 - l2; return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: result = l1 * l2; return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: result = l1 / l2; return true; } } result = null; return false; } #endif internal override JToken CloneToken() { return new JValue(this); } /// <summary> /// Creates a <see cref="JValue"/> comment with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> comment with the given value.</returns> public static JValue CreateComment(string value) { return new JValue(value, JTokenType.Comment); } /// <summary> /// Creates a <see cref="JValue"/> string with the given value. /// </summary> /// <param name="value">The value.</param> /// <returns>A <see cref="JValue"/> string with the given value.</returns> public static JValue CreateString(string value) { return new JValue(value, JTokenType.String); } /// <summary> /// Creates a <see cref="JValue"/> null value. /// </summary> /// <returns>A <see cref="JValue"/> null value.</returns> public static JValue CreateNull() { return new JValue(null, JTokenType.Null); } /// <summary> /// Creates a <see cref="JValue"/> undefined value. /// </summary> /// <returns>A <see cref="JValue"/> undefined value.</returns> public static JValue CreateUndefined() { return new JValue(null, JTokenType.Undefined); } private static JTokenType GetValueType(JTokenType? current, object value) { if (value == null) { return JTokenType.Null; } #if HAVE_ADO_NET else if (value == DBNull.Value) { return JTokenType.Null; } #endif else if (value is string) { return GetStringValueType(current); } else if (value is long || value is int || value is short || value is sbyte || value is ulong || value is uint || value is ushort || value is byte) { return JTokenType.Integer; } else if (value is Enum) { return JTokenType.Integer; } #if HAVE_BIG_INTEGER else if (value is BigInteger) { return JTokenType.Integer; } #endif else if (value is double || value is float || value is decimal) { return JTokenType.Float; } else if (value is DateTime) { return JTokenType.Date; } #if HAVE_DATE_TIME_OFFSET else if (value is DateTimeOffset) { return JTokenType.Date; } #endif else if (value is byte[]) { return JTokenType.Bytes; } else if (value is bool) { return JTokenType.Boolean; } else if (value is Guid) { return JTokenType.Guid; } else if (value is Uri) { return JTokenType.Uri; } else if (value is TimeSpan) { return JTokenType.TimeSpan; } throw new ArgumentException("Could not determine JSON object type for type {0}.".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } private static JTokenType GetStringValueType(JTokenType? current) { if (current == null) { return JTokenType.String; } switch (current.GetValueOrDefault()) { case JTokenType.Comment: case JTokenType.String: case JTokenType.Raw: return current.GetValueOrDefault(); default: return JTokenType.String; } } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { get { return _valueType; } } /// <summary> /// Gets or sets the underlying token value. /// </summary> /// <value>The underlying token value.</value> public object Value { get { return _value; } set { Type currentType = _value?.GetType(); Type newType = value?.GetType(); if (currentType != newType) { _valueType = GetValueType(_valueType, value); } _value = value; } } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/>s which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) { JsonConverter matchingConverter = JsonSerializer.GetMatchingConverter(converters, _value.GetType()); if (matchingConverter != null && matchingConverter.CanWrite) { matchingConverter.WriteJson(writer, _value, JsonSerializer.CreateDefault()); return; } } switch (_valueType) { case JTokenType.Comment: writer.WriteComment(_value?.ToString()); return; case JTokenType.Raw: writer.WriteRawValue(_value?.ToString()); return; case JTokenType.Null: writer.WriteNull(); return; case JTokenType.Undefined: writer.WriteUndefined(); return; case JTokenType.Integer: if (_value is int) { writer.WriteValue((int)_value); } else if (_value is long) { writer.WriteValue((long)_value); } else if (_value is ulong) { writer.WriteValue((ulong)_value); } #if HAVE_BIG_INTEGER else if (_value is BigInteger) { writer.WriteValue((BigInteger)_value); } #endif else { writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Float: if (_value is decimal) { writer.WriteValue((decimal)_value); } else if (_value is double) { writer.WriteValue((double)_value); } else if (_value is float) { writer.WriteValue((float)_value); } else { writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.String: writer.WriteValue(_value?.ToString()); return; case JTokenType.Boolean: writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture)); return; case JTokenType.Date: #if HAVE_DATE_TIME_OFFSET if (_value is DateTimeOffset) { writer.WriteValue((DateTimeOffset)_value); } else #endif { writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture)); } return; case JTokenType.Bytes: writer.WriteValue((byte[])_value); return; case JTokenType.Guid: writer.WriteValue((_value != null) ? (Guid?)_value : null); return; case JTokenType.TimeSpan: writer.WriteValue((_value != null) ? (TimeSpan?)_value : null); return; case JTokenType.Uri: writer.WriteValue((Uri)_value); return; } throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(Type), _valueType, "Unexpected token type."); } internal override int GetDeepHashCode() { int valueHashCode = (_value != null) ? _value.GetHashCode() : 0; // GetHashCode on an enum boxes so cast to int return ((int)_valueType).GetHashCode() ^ valueHashCode; } private static bool ValuesEquals(JValue v1, JValue v2) { return (v1 == v2 || (v1._valueType == v2._valueType && Compare(v1._valueType, v1._value, v2._value) == 0)); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <returns> /// <c>true</c> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <c>false</c>. /// </returns> /// <param name="other">An object to compare with this object.</param> public bool Equals(JValue other) { if (other == null) { return false; } return ValuesEquals(this, other); } /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Object"/>. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Object"/>.</param> /// <returns> /// <c>true</c> if the specified <see cref="Object"/> is equal to the current <see cref="Object"/>; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return Equals(obj as JValue); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="Object"/>. /// </returns> public override int GetHashCode() { if (_value == null) { return 0; } return _value.GetHashCode(); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { if (_value == null) { return string.Empty; } return _value.ToString(); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(IFormatProvider formatProvider) { return ToString(null, formatProvider); } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The format provider.</param> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { if (_value == null) { return string.Empty; } IFormattable formattable = _value as IFormattable; if (formattable != null) { return formattable.ToString(format, formatProvider); } else { return _value.ToString(); } } #if HAVE_DYNAMIC /// <summary> /// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JValue>(parameter, this, new JValueDynamicProxy()); } private class JValueDynamicProxy : DynamicProxy<JValue> { public override bool TryConvert(JValue instance, ConvertBinder binder, out object result) { if (binder.Type == typeof(JValue) || binder.Type == typeof(JToken)) { result = instance; return true; } object value = instance.Value; if (value == null) { result = null; return ReflectionUtils.IsNullable(binder.Type); } result = ConvertUtils.Convert(value, CultureInfo.InvariantCulture, binder.Type); return true; } public override bool TryBinaryOperation(JValue instance, BinaryOperationBinder binder, object arg, out object result) { JValue value = arg as JValue; object compareValue = value != null ? value.Value : arg; switch (binder.Operation) { case ExpressionType.Equal: result = (Compare(instance.Type, instance.Value, compareValue) == 0); return true; case ExpressionType.NotEqual: result = (Compare(instance.Type, instance.Value, compareValue) != 0); return true; case ExpressionType.GreaterThan: result = (Compare(instance.Type, instance.Value, compareValue) > 0); return true; case ExpressionType.GreaterThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) >= 0); return true; case ExpressionType.LessThan: result = (Compare(instance.Type, instance.Value, compareValue) < 0); return true; case ExpressionType.LessThanOrEqual: result = (Compare(instance.Type, instance.Value, compareValue) <= 0); return true; case ExpressionType.Add: case ExpressionType.AddAssign: case ExpressionType.Subtract: case ExpressionType.SubtractAssign: case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: case ExpressionType.Divide: case ExpressionType.DivideAssign: if (Operation(binder.Operation, instance.Value, compareValue, out result)) { result = new JValue(result); return true; } break; } result = null; return false; } } #endif int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } JValue value = obj as JValue; JTokenType comparisonType; object otherValue; if (value != null) { otherValue = value.Value; comparisonType = (_valueType == JTokenType.String && _valueType != value._valueType) ? value._valueType : _valueType; } else { otherValue = obj; comparisonType = _valueType; } return Compare(comparisonType, _value, otherValue); } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: /// Value /// Meaning /// Less than zero /// This instance is less than <paramref name="obj"/>. /// Zero /// This instance is equal to <paramref name="obj"/>. /// Greater than zero /// This instance is greater than <paramref name="obj"/>. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="obj"/> is not of the same type as this instance. /// </exception> public int CompareTo(JValue obj) { if (obj == null) { return 1; } JTokenType comparisonType = (_valueType == JTokenType.String && _valueType != obj._valueType) ? obj._valueType : _valueType; return Compare(comparisonType, _value, obj._value); } #if HAVE_ICONVERTIBLE TypeCode IConvertible.GetTypeCode() { if (_value == null) { return TypeCode.Empty; } IConvertible convertable = _value as IConvertible; if (convertable == null) { return TypeCode.Object; } return convertable.GetTypeCode(); } bool IConvertible.ToBoolean(IFormatProvider provider) { return (bool)this; } char IConvertible.ToChar(IFormatProvider provider) { return (char)this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return (sbyte)this; } byte IConvertible.ToByte(IFormatProvider provider) { return (byte)this; } short IConvertible.ToInt16(IFormatProvider provider) { return (short)this; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return (ushort)this; } int IConvertible.ToInt32(IFormatProvider provider) { return (int)this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return (uint)this; } long IConvertible.ToInt64(IFormatProvider provider) { return (long)this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return (ulong)this; } float IConvertible.ToSingle(IFormatProvider provider) { return (float)this; } double IConvertible.ToDouble(IFormatProvider provider) { return (double)this; } decimal IConvertible.ToDecimal(IFormatProvider provider) { return (decimal)this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return (DateTime)this; } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ToObject(conversionType); } #endif } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Region.CoreModules.World.Permissions; using OpenSim.Tests.Common; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class ScenePresenceCrossingTests : OpenSimTestCase { [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression // tests really shouldn't). Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } [Test] public void TestCrossOnSameSimulator() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); // TestEventQueueGetModule eqmA = new TestEventQueueGetModule(); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); // IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. // entityTransferConfig.Set("wait_for_callback", false); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); // SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA, eqmA); SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence originalSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); originalSp.AbsolutePosition = new Vector3(128, 32, 10); // originalSp.Flying = true; // Console.WriteLine("First pos {0}", originalSp.AbsolutePosition); // eqmA.ClearEvents(); AgentUpdateArgs moveArgs = new AgentUpdateArgs(); //moveArgs.BodyRotation = Quaternion.CreateFromEulers(Vector3.Zero); moveArgs.BodyRotation = Quaternion.CreateFromEulers(new Vector3(0, 0, (float)-(Math.PI / 2))); moveArgs.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; moveArgs.SessionID = acd.SessionID; originalSp.HandleAgentUpdate(originalSp.ControllingClient, moveArgs); sceneA.Update(1); // Console.WriteLine("Second pos {0}", originalSp.AbsolutePosition); // FIXME: This is a sufficient number of updates to for the presence to reach the northern border. // But really we want to do this in a more robust way. for (int i = 0; i < 100; i++) { sceneA.Update(1); // Console.WriteLine("Pos {0}", originalSp.AbsolutePosition); } // Need to sort processing of EnableSimulator message on adding scene presences before we can test eqm // messages // Dictionary<UUID, List<TestEventQueueGetModule.Event>> eqmEvents = eqmA.Events; // // Assert.That(eqmEvents.Count, Is.EqualTo(1)); // Assert.That(eqmEvents.ContainsKey(originalSp.UUID), Is.True); // // List<TestEventQueueGetModule.Event> spEqmEvents = eqmEvents[originalSp.UUID]; // // Assert.That(spEqmEvents.Count, Is.EqualTo(1)); // Assert.That(spEqmEvents[0].Name, Is.EqualTo("CrossRegion")); // sceneA should now only have a child agent ScenePresence spAfterCrossSceneA = sceneA.GetScenePresence(originalSp.UUID); Assert.That(spAfterCrossSceneA.IsChildAgent, Is.True); ScenePresence spAfterCrossSceneB = sceneB.GetScenePresence(originalSp.UUID); // Agent remains a child until the client triggers complete movement Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); TestClient sceneBTc = ((TestClient)spAfterCrossSceneB.ControllingClient); int agentMovementCompleteReceived = 0; sceneBTc.OnReceivedMoveAgentIntoRegion += (ri, pos, look) => agentMovementCompleteReceived++; sceneBTc.CompleteMovement(); Assert.That(agentMovementCompleteReceived, Is.EqualTo(1)); Assert.That(spAfterCrossSceneB.IsChildAgent, Is.False); } /// <summary> /// Test a cross attempt where the user can see into the neighbour but does not have permission to become /// root there. /// </summary> [Test] public void TestCrossOnSameSimulatorNoRootDestPerm() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); // We need to set up the permisions module on scene B so that our later use of agent limit to deny // QueryAccess won't succeed anyway because administrators are always allowed in and the default // IsAdministrator if no permissions module is present is true. SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), new PermissionsModule(), etmB); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); // Make sure sceneB will not accept this avatar. sceneB.RegionInfo.EstateSettings.PublicAccess = false; ScenePresence originalSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); originalSp.AbsolutePosition = new Vector3(128, 32, 10); AgentUpdateArgs moveArgs = new AgentUpdateArgs(); //moveArgs.BodyRotation = Quaternion.CreateFromEulers(Vector3.Zero); moveArgs.BodyRotation = Quaternion.CreateFromEulers(new Vector3(0, 0, (float)-(Math.PI / 2))); moveArgs.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; moveArgs.SessionID = acd.SessionID; originalSp.HandleAgentUpdate(originalSp.ControllingClient, moveArgs); sceneA.Update(1); // Console.WriteLine("Second pos {0}", originalSp.AbsolutePosition); // FIXME: This is a sufficient number of updates to for the presence to reach the northern border. // But really we want to do this in a more robust way. for (int i = 0; i < 100; i++) { sceneA.Update(1); // Console.WriteLine("Pos {0}", originalSp.AbsolutePosition); } // sceneA agent should still be root ScenePresence spAfterCrossSceneA = sceneA.GetScenePresence(originalSp.UUID); Assert.That(spAfterCrossSceneA.IsChildAgent, Is.False); ScenePresence spAfterCrossSceneB = sceneB.GetScenePresence(originalSp.UUID); // sceneB agent should also still be root Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); // sceneB should ignore unauthorized attempt to upgrade agent to root TestClient sceneBTc = ((TestClient)spAfterCrossSceneB.ControllingClient); int agentMovementCompleteReceived = 0; sceneBTc.OnReceivedMoveAgentIntoRegion += (ri, pos, look) => agentMovementCompleteReceived++; sceneBTc.CompleteMovement(); Assert.That(agentMovementCompleteReceived, Is.EqualTo(0)); Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public const int STATUS_PHYSICS = 1; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_PHANTOM = 16; public const int STATUS_SANDBOX = 32; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_CAST_SHADOWS = 512; public const int AGENT = 1; public const int AGENT_BY_LEGACY_NAME = 1; public const int AGENT_BY_USERNAME = 0x10; public const int NPC = 0x20; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public const int CONTROL_FWD = 1; public const int CONTROL_BACK = 2; public const int CONTROL_LEFT = 4; public const int CONTROL_RIGHT = 8; public const int CONTROL_UP = 16; public const int CONTROL_DOWN = 32; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_ML_LBUTTON = 1073741824; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_CONTROL_CAMERA = 2048; public const int AGENT_FLYING = 1; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_SCRIPTED = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_SITTING = 16; public const int AGENT_ON_OBJECT = 32; public const int AGENT_AWAY = 64; public const int AGENT_WALKING = 128; public const int AGENT_IN_AIR = 256; public const int AGENT_TYPING = 512; public const int AGENT_CROUCHING = 1024; public const int AGENT_BUSY = 2048; public const int AGENT_ALWAYS_RUN = 4096; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_TEXTURE = 12; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_RANGE_BLOCK = 45; public const int VEHICLE_ROLL_FRAME = 46; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int VEHICLE_FLAG_NO_X = 1024; public const int VEHICLE_FLAG_NO_Y = 2048; public const int VEHICLE_FLAG_NO_Z = 4096; public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public const int VEHICLE_FLAG_NO_DEFLECTION = 16392; public const int VEHICLE_FLAG_LOCK_ROTATION = 32784; public const int INVENTORY_ALL = -1; public const int INVENTORY_NONE = -1; public const int INVENTORY_TEXTURE = 0; public const int INVENTORY_SOUND = 1; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_GESTURE = 21; public const int ATTACH_CHEST = 1; public const int ATTACH_HEAD = 2; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_LHAND = 5; public const int ATTACH_RHAND = 6; public const int ATTACH_LFOOT = 7; public const int ATTACH_RFOOT = 8; public const int ATTACH_BACK = 9; public const int ATTACH_PELVIS = 10; public const int ATTACH_MOUTH = 11; public const int ATTACH_CHIN = 12; public const int ATTACH_LEAR = 13; public const int ATTACH_REAR = 14; public const int ATTACH_LEYE = 15; public const int ATTACH_REYE = 16; public const int ATTACH_NOSE = 17; public const int ATTACH_RUARM = 18; public const int ATTACH_RLARM = 19; public const int ATTACH_LUARM = 20; public const int ATTACH_LLARM = 21; public const int ATTACH_RHIP = 22; public const int ATTACH_RULEG = 23; public const int ATTACH_RLLEG = 24; public const int ATTACH_LHIP = 25; public const int ATTACH_LULEG = 26; public const int ATTACH_LLLEG = 27; public const int ATTACH_BELLY = 28; public const int ATTACH_RPEC = 29; public const int ATTACH_LPEC = 30; public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; #region osMessageAttachments constants /// <summary> /// Instructs osMessageAttachements to send the message to attachments /// on every point. /// </summary> /// <remarks> /// One might expect this to be named OS_ATTACH_ALL, but then one might /// also expect functions designed to attach or detach or get /// attachments to work with it too. Attaching a no-copy item to /// many attachments could be dangerous. /// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the /// message from being sent. /// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or /// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being /// sent- this is expected behaviour. /// </remarks> public const int OS_ATTACH_MSG_ALL = -65535; /// <summary> /// Instructs osMessageAttachements to invert how the attachment points /// list should be treated (e.g. go from inclusive operation to /// exclusive operation). /// </summary> /// <remarks> /// This might be used if you want to deliver a message to one set of /// attachments and a different message to everything else. With /// this flag, you only need to build one explicit list for both calls. /// </remarks> public const int OS_ATTACH_MSG_INVERT_POINTS = 1; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the host object CreatorID /// </summary> /// <remarks> /// This would be used if distributed in an object vendor/updater server. /// </remarks> public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the sending script CreatorID /// </summary> /// <remarks> /// This might be used if the script is distributed independently of a /// containing object. /// </remarks> public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4; #endregion public const int LAND_LEVEL = 0; public const int LAND_RAISE = 1; public const int LAND_LOWER = 2; public const int LAND_SMOOTH = 3; public const int LAND_NOISE = 4; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_LARGE_BRUSH = 3; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_NAME = 2; public const int DATA_BORN = 3; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_STATUS = 6; public const int DATA_SIM_RATING = 7; public const int DATA_PAYINFO = 8; public const int DATA_SIM_RELEASE = 128; public const int ANIM_ON = 1; public const int LOOP = 2; public const int REVERSE = 4; public const int PING_PONG = 8; public const int SMOOTH = 16; public const int ROTATE = 32; public const int SCALE = 64; public const int ALL_SIDES = -1; public const int LINK_SET = -1; public const int LINK_ROOT = 1; public const int LINK_ALL_OTHERS = -2; public const int LINK_ALL_CHILDREN = -3; public const int LINK_THIS = -4; public const int CHANGED_INVENTORY = 1; public const int CHANGED_COLOR = 2; public const int CHANGED_SHAPE = 4; public const int CHANGED_SCALE = 8; public const int CHANGED_TEXTURE = 16; public const int CHANGED_LINK = 32; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION = 256; public const int CHANGED_TELEPORT = 512; public const int CHANGED_REGION_RESTART = 1024; public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public const int CHANGED_MEDIA = 2048; public const int CHANGED_ANIMATION = 16384; public const int TYPE_INVALID = 0; public const int TYPE_INTEGER = 1; public const int TYPE_FLOAT = 2; public const int TYPE_STRING = 3; public const int TYPE_KEY = 4; public const int TYPE_VECTOR = 5; public const int TYPE_ROTATION = 6; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REQUEST = 2; public const int REMOTE_DATA_REPLY = 3; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; public const int HTTP_VERBOSE_THROTTLE = 4; public const int HTTP_CUSTOM_HEADER = 5; public const int HTTP_PRAGMA_NO_CACHE = 6; // llSetContentType public const int CONTENT_TYPE_TEXT = 0; //text/plain public const int CONTENT_TYPE_HTML = 1; //text/html public const int CONTENT_TYPE_XML = 2; //application/xml public const int CONTENT_TYPE_XHTML = 3; //application/xhtml+xml public const int CONTENT_TYPE_ATOM = 4; //application/atom+xml public const int CONTENT_TYPE_JSON = 5; //application/json public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml public const int CONTENT_TYPE_FORM = 7; //application/x-www-form-urlencoded public const int CONTENT_TYPE_RSS = 8; //application/rss+xml public const int PRIM_MATERIAL = 2; public const int PRIM_PHYSICS = 3; public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_PHANTOM = 5; public const int PRIM_POSITION = 6; public const int PRIM_SIZE = 7; public const int PRIM_ROTATION = 8; public const int PRIM_TYPE = 9; public const int PRIM_TEXTURE = 17; public const int PRIM_COLOR = 18; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_FLEXIBLE = 21; public const int PRIM_TEXGEN = 22; public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; // Huh? public const int PRIM_GLOW = 25; public const int PRIM_TEXT = 26; public const int PRIM_NAME = 27; public const int PRIM_DESC = 28; public const int PRIM_ROT_LOCAL = 29; public const int PRIM_OMEGA = 32; public const int PRIM_POS_LOCAL = 33; public const int PRIM_LINK_TARGET = 34; public const int PRIM_SLICE = 35; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_WOOD = 3; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int PRIM_SCULPT_FLAG_INVERT = 64; public const int PRIM_SCULPT_FLAG_MIRROR = 128; public const int PROFILE_NONE = 0; public const int PROFILE_SCRIPT_MEMORY = 1; public const int MASK_BASE = 0; public const int MASK_OWNER = 1; public const int MASK_GROUP = 2; public const int MASK_EVERYONE = 3; public const int MASK_NEXT = 4; public const int PERM_TRANSFER = 8192; public const int PERM_MODIFY = 16384; public const int PERM_COPY = 32768; public const int PERM_MOVE = 524288; public const int PERM_ALL = 2147483647; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject //llManageEstateAccess public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const string EOF = "\n\n\n"; public const double PI = 3.14159274f; public const double TWO_PI = 6.28318548f; public const double PI_BY_TWO = 1.57079637f; public const double DEG_TO_RAD = 0.01745329238f; public const double RAD_TO_DEG = 57.29578f; public const double SQRT2 = 1.414213538f; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; public const int STRING_TRIM = 3; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const int PUBLIC_CHANNEL = 0x00000000; // Constants for llGetObjectDetails public const int OBJECT_UNKNOWN_DETAIL = -1; public const int OBJECT_NAME = 1; public const int OBJECT_DESC = 2; public const int OBJECT_POS = 3; public const int OBJECT_ROT = 4; public const int OBJECT_VELOCITY = 5; public const int OBJECT_OWNER = 6; public const int OBJECT_GROUP = 7; public const int OBJECT_CREATOR = 8; public const int OBJECT_RUNNING_SCRIPT_COUNT = 9; public const int OBJECT_TOTAL_SCRIPT_COUNT = 10; public const int OBJECT_SCRIPT_MEMORY = 11; public const int OBJECT_SCRIPT_TIME = 12; public const int OBJECT_PRIM_EQUIVALENCE = 13; public const int OBJECT_SERVER_COST = 14; public const int OBJECT_STREAMING_COST = 15; public const int OBJECT_PHYSICS_COST = 16; public const int OBJECT_CHARACTER_TIME = 17; public const int OBJECT_ROOT = 18; public const int OBJECT_ATTACHED_POINT = 19; public const int OBJECT_PATHFINDING_TYPE = 20; public const int OBJECT_PHYSICS = 21; public const int OBJECT_PHANTOM = 22; public const int OBJECT_TEMP_ON_REZ = 23; // Pathfinding types public const int OPT_OTHER = -1; public const int OPT_LEGACY_LINKSET = 0; public const int OPT_AVATAR = 1; public const int OPT_CHARACTER = 2; public const int OPT_WALKABLE = 3; public const int OPT_STATIC_OBSTACLE = 4; public const int OPT_MATERIAL_VOLUME = 5; public const int OPT_EXCLUSION_VOLUME = 6; // for llGetAgentList public const int AGENT_LIST_PARCEL = 1; public const int AGENT_LIST_PARCEL_OWNER = 2; public const int AGENT_LIST_REGION = 4; // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_DISTANCE = 7; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_ACTIVE = 12; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_AREA = 4; public const int PARCEL_DETAILS_ID = 5; public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented //osSetParcelDetails public const int PARCEL_DETAILS_CLAIMDATE = 10; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_BUY = 2; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_OPEN_MEDIA = 6; public const int CLICK_ACTION_ZOOM = 7; // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // constants for llGetPrimMediaParams/llSetPrimMediaParams public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public const int PRIM_MEDIA_CONTROLS = 1; public const int PRIM_MEDIA_CURRENT_URL = 2; public const int PRIM_MEDIA_HOME_URL = 3; public const int PRIM_MEDIA_AUTO_LOOP = 4; public const int PRIM_MEDIA_AUTO_PLAY = 5; public const int PRIM_MEDIA_AUTO_SCALE = 6; public const int PRIM_MEDIA_AUTO_ZOOM = 7; public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public const int PRIM_MEDIA_WIDTH_PIXELS = 9; public const int PRIM_MEDIA_HEIGHT_PIXELS = 10; public const int PRIM_MEDIA_WHITELIST_ENABLE = 11; public const int PRIM_MEDIA_WHITELIST = 12; public const int PRIM_MEDIA_PERMS_INTERACT = 13; public const int PRIM_MEDIA_PERMS_CONTROL = 14; public const int PRIM_MEDIA_CONTROLS_STANDARD = 0; public const int PRIM_MEDIA_CONTROLS_MINI = 1; public const int PRIM_MEDIA_PERM_NONE = 0; public const int PRIM_MEDIA_PERM_OWNER = 1; public const int PRIM_MEDIA_PERM_GROUP = 2; public const int PRIM_MEDIA_PERM_ANYONE = 4; public const int PRIM_PHYSICS_SHAPE_TYPE = 30; public const int PRIM_PHYSICS_SHAPE_PRIM = 0; public const int PRIM_PHYSICS_SHAPE_CONVEX = 2; public const int PRIM_PHYSICS_SHAPE_NONE = 1; public const int PRIM_PHYSICS_MATERIAL = 31; public const int DENSITY = 1; public const int FRICTION = 2; public const int RESTITUTION = 4; public const int GRAVITY_MULTIPLIER = 8; // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public const int STATS_TIME_DILATION = 0; public const int STATS_SIM_FPS = 1; public const int STATS_PHYSICS_FPS = 2; public const int STATS_AGENT_UPDATES = 3; public const int STATS_ROOT_AGENTS = 4; public const int STATS_CHILD_AGENTS = 5; public const int STATS_TOTAL_PRIMS = 6; public const int STATS_ACTIVE_PRIMS = 7; public const int STATS_FRAME_MS = 8; public const int STATS_NET_MS = 9; public const int STATS_PHYSICS_MS = 10; public const int STATS_IMAGE_MS = 11; public const int STATS_OTHER_MS = 12; public const int STATS_IN_PACKETS_PER_SECOND = 13; public const int STATS_OUT_PACKETS_PER_SECOND = 14; public const int STATS_UNACKED_BYTES = 15; public const int STATS_AGENT_MS = 16; public const int STATS_PENDING_DOWNLOADS = 17; public const int STATS_PENDING_UPLOADS = 18; public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_SCRIPT_LPS = 20; // Constants for osNpc* functions public const int OS_NPC_FLY = 0; public const int OS_NPC_NO_FLY = 1; public const int OS_NPC_LAND_AT_TARGET = 2; public const int OS_NPC_RUNNING = 4; public const int OS_NPC_SIT_NOW = 0; public const int OS_NPC_CREATOR_OWNED = 0x1; public const int OS_NPC_NOT_OWNED = 0x2; public const int OS_NPC_SENSE_AS_AGENT = 0x4; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSLInteger RC_REJECT_TYPES = 0; public static readonly LSLInteger RC_DETECT_PHANTOM = 1; public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4; public static readonly LSLInteger RC_REJECT_LAND = 8; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_GET_LINK_NUM = 4; public static readonly LSLInteger RCERR_UNKNOWN = -1; public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3; public const int KFM_MODE = 1; public const int KFM_LOOP = 1; public const int KFM_REVERSE = 3; public const int KFM_FORWARD = 0; public const int KFM_PING_PONG = 2; public const int KFM_DATA = 2; public const int KFM_TRANSLATION = 2; public const int KFM_ROTATION = 1; public const int KFM_COMMAND = 0; public const int KFM_CMD_PLAY = 0; public const int KFM_CMD_STOP = 1; public const int KFM_CMD_PAUSE = 2; /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDuration { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Duration operations. /// </summary> public partial class Duration : IServiceOperations<AutoRestDurationTestService>, IDuration { /// <summary> /// Initializes a new instance of the Duration class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public Duration(AutoRestDurationTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDurationTestService /// </summary> public AutoRestDurationTestService Client { get; private set; } /// <summary> /// Get null duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<TimeSpan?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put a positive duration value /// </summary> /// <param name='durationBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutPositiveDurationWithHttpMessagesAsync(TimeSpan? durationBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (durationBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "durationBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("durationBody", durationBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a positive duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<TimeSpan?>> GetPositiveDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetPositiveDuration", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/positiveduration").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get an invalid duration value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<TimeSpan?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duration/invalid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<TimeSpan?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<TimeSpan?>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
#region License /* * HttpListenerResponse.cs * * This code is derived from HttpListenerResponse.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * 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 #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion #region Contributors /* * Contributors: * - Nicholas Devenish */ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace CustomWebSocketSharp.Net { /// <summary> /// Provides the access to a response to a request received by the <see cref="HttpListener"/>. /// </summary> /// <remarks> /// The HttpListenerResponse class cannot be inherited. /// </remarks> public sealed class HttpListenerResponse : IDisposable { #region Private Fields private bool _closeConnection; private Encoding _contentEncoding; private long _contentLength; private string _contentType; private HttpListenerContext _context; private CookieCollection _cookies; private bool _disposed; private WebHeaderCollection _headers; private bool _headersSent; private bool _keepAlive; private string _location; private ResponseStream _outputStream; private bool _sendChunked; private int _statusCode; private string _statusDescription; private Version _version; #endregion #region Internal Constructors internal HttpListenerResponse (HttpListenerContext context) { _context = context; _keepAlive = true; _statusCode = 200; _statusDescription = "OK"; _version = HttpVersion.Version11; } #endregion #region Internal Properties internal bool CloseConnection { get { return _closeConnection; } set { _closeConnection = value; } } internal bool HeadersSent { get { return _headersSent; } set { _headersSent = value; } } #endregion #region Public Properties /// <summary> /// Gets or sets the encoding for the entity body data included in the response. /// </summary> /// <value> /// A <see cref="Encoding"/> that represents the encoding for the entity body data, /// or <see langword="null"/> if no encoding is specified. /// </value> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public Encoding ContentEncoding { get { return _contentEncoding; } set { checkDisposed (); _contentEncoding = value; } } /// <summary> /// Gets or sets the number of bytes in the entity body data included in the response. /// </summary> /// <value> /// A <see cref="long"/> that represents the value of the Content-Length entity-header. /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation is less than zero. /// </exception> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public long ContentLength64 { get { return _contentLength; } set { checkDisposedOrHeadersSent (); if (value < 0) throw new ArgumentOutOfRangeException ("Less than zero.", "value"); _contentLength = value; } } /// <summary> /// Gets or sets the media type of the entity body included in the response. /// </summary> /// <value> /// A <see cref="string"/> that represents the media type of the entity body, /// or <see langword="null"/> if no media type is specified. This value is /// used for the value of the Content-Type entity-header. /// </value> /// <exception cref="ArgumentException"> /// The value specified for a set operation is empty. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public string ContentType { get { return _contentType; } set { checkDisposed (); if (value != null && value.Length == 0) throw new ArgumentException ("An empty string.", "value"); _contentType = value; } } /// <summary> /// Gets or sets the cookies sent with the response. /// </summary> /// <value> /// A <see cref="CookieCollection"/> that contains the cookies sent with the response. /// </value> public CookieCollection Cookies { get { return _cookies ?? (_cookies = new CookieCollection ()); } set { _cookies = value; } } /// <summary> /// Gets or sets the HTTP headers sent to the client. /// </summary> /// <value> /// A <see cref="WebHeaderCollection"/> that contains the headers sent to the client. /// </value> /// <exception cref="InvalidOperationException"> /// The value specified for a set operation isn't valid for a response. /// </exception> public WebHeaderCollection Headers { get { return _headers ?? (_headers = new WebHeaderCollection (HttpHeaderType.Response, false)); } set { if (value != null && value.State != HttpHeaderType.Response) throw new InvalidOperationException ( "The specified headers aren't valid for a response."); _headers = value; } } /// <summary> /// Gets or sets a value indicating whether the server requests a persistent connection. /// </summary> /// <value> /// <c>true</c> if the server requests a persistent connection; otherwise, <c>false</c>. /// The default value is <c>true</c>. /// </value> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public bool KeepAlive { get { return _keepAlive; } set { checkDisposedOrHeadersSent (); _keepAlive = value; } } /// <summary> /// Gets a <see cref="Stream"/> to use to write the entity body data. /// </summary> /// <value> /// A <see cref="Stream"/> to use to write the entity body data. /// </value> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public Stream OutputStream { get { checkDisposed (); return _outputStream ?? (_outputStream = _context.Connection.GetResponseStream ()); } } /// <summary> /// Gets or sets the HTTP version used in the response. /// </summary> /// <value> /// A <see cref="Version"/> that represents the version used in the response. /// </value> /// <exception cref="ArgumentNullException"> /// The value specified for a set operation is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// The value specified for a set operation doesn't have its <c>Major</c> property set to 1 or /// doesn't have its <c>Minor</c> property set to either 0 or 1. /// </exception> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public Version ProtocolVersion { get { return _version; } set { checkDisposedOrHeadersSent (); if (value == null) throw new ArgumentNullException ("value"); if (value.Major != 1 || (value.Minor != 0 && value.Minor != 1)) throw new ArgumentException ("Not 1.0 or 1.1.", "value"); _version = value; } } /// <summary> /// Gets or sets the URL to which the client is redirected to locate a requested resource. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Location response-header, /// or <see langword="null"/> if no redirect location is specified. /// </value> /// <exception cref="ArgumentException"> /// The value specified for a set operation isn't an absolute URL. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public string RedirectLocation { get { return _location; } set { checkDisposed (); if (value == null) { _location = null; return; } Uri uri = null; if (!value.MaybeUri () || !Uri.TryCreate (value, UriKind.Absolute, out uri)) throw new ArgumentException ("Not an absolute URL.", "value"); _location = value; } } /// <summary> /// Gets or sets a value indicating whether the response uses the chunked transfer encoding. /// </summary> /// <value> /// <c>true</c> if the response uses the chunked transfer encoding; /// otherwise, <c>false</c>. The default value is <c>false</c>. /// </value> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public bool SendChunked { get { return _sendChunked; } set { checkDisposedOrHeadersSent (); _sendChunked = value; } } /// <summary> /// Gets or sets the HTTP status code returned to the client. /// </summary> /// <value> /// An <see cref="int"/> that represents the status code for the response to /// the request. The default value is same as <see cref="HttpStatusCode.OK"/>. /// </value> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> /// <exception cref="System.Net.ProtocolViolationException"> /// The value specified for a set operation is invalid. Valid values are /// between 100 and 999 inclusive. /// </exception> public int StatusCode { get { return _statusCode; } set { checkDisposedOrHeadersSent (); if (value < 100 || value > 999) throw new System.Net.ProtocolViolationException ( "A value isn't between 100 and 999 inclusive."); _statusCode = value; _statusDescription = value.GetStatusDescription (); } } /// <summary> /// Gets or sets the description of the HTTP status code returned to the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the description of the status code. The default /// value is the <see href="http://tools.ietf.org/html/rfc2616#section-10">RFC 2616</see> /// description for the <see cref="HttpListenerResponse.StatusCode"/> property value, /// or <see cref="String.Empty"/> if an RFC 2616 description doesn't exist. /// </value> /// <exception cref="ArgumentException"> /// The value specified for a set operation contains invalid characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public string StatusDescription { get { return _statusDescription; } set { checkDisposedOrHeadersSent (); if (value == null || value.Length == 0) { _statusDescription = _statusCode.GetStatusDescription (); return; } if (!value.IsText () || value.IndexOfAny (new[] { '\r', '\n' }) > -1) throw new ArgumentException ("Contains invalid characters.", "value"); _statusDescription = value; } } #endregion #region Private Methods private bool canAddOrUpdate (Cookie cookie) { if (_cookies == null || _cookies.Count == 0) return true; var found = findCookie (cookie).ToList (); if (found.Count == 0) return true; var ver = cookie.Version; foreach (var c in found) if (c.Version == ver) return true; return false; } private void checkDisposed () { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); } private void checkDisposedOrHeadersSent () { if (_disposed) throw new ObjectDisposedException (GetType ().ToString ()); if (_headersSent) throw new InvalidOperationException ("Cannot be changed after the headers are sent."); } private void close (bool force) { _disposed = true; _context.Connection.Close (force); } private IEnumerable<Cookie> findCookie (Cookie cookie) { var name = cookie.Name; var domain = cookie.Domain; var path = cookie.Path; if (_cookies != null) foreach (Cookie c in _cookies) if (c.Name.Equals (name, StringComparison.OrdinalIgnoreCase) && c.Domain.Equals (domain, StringComparison.OrdinalIgnoreCase) && c.Path.Equals (path, StringComparison.Ordinal)) yield return c; } #endregion #region Internal Methods internal WebHeaderCollection WriteHeadersTo (MemoryStream destination) { var headers = new WebHeaderCollection (HttpHeaderType.Response, true); if (_headers != null) headers.Add (_headers); if (_contentType != null) { var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 && _contentEncoding != null ? String.Format ("{0}; charset={1}", _contentType, _contentEncoding.WebName) : _contentType; headers.InternalSet ("Content-Type", type, true); } if (headers["Server"] == null) headers.InternalSet ("Server", "websocket-sharp/1.0", true); var prov = CultureInfo.InvariantCulture; if (headers["Date"] == null) headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true); if (!_sendChunked) headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true); else headers.InternalSet ("Transfer-Encoding", "chunked", true); /* * Apache forces closing the connection for these status codes: * - 400 Bad Request * - 408 Request Timeout * - 411 Length Required * - 413 Request Entity Too Large * - 414 Request-Uri Too Long * - 500 Internal Server Error * - 503 Service Unavailable */ var closeConn = !_context.Request.KeepAlive || !_keepAlive || _statusCode == 400 || _statusCode == 408 || _statusCode == 411 || _statusCode == 413 || _statusCode == 414 || _statusCode == 500 || _statusCode == 503; var reuses = _context.Connection.Reuses; if (closeConn || reuses >= 100) { headers.InternalSet ("Connection", "close", true); } else { headers.InternalSet ( "Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true); if (_context.Request.ProtocolVersion < HttpVersion.Version11) headers.InternalSet ("Connection", "keep-alive", true); } if (_location != null) headers.InternalSet ("Location", _location, true); if (_cookies != null) foreach (Cookie cookie in _cookies) headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true); var enc = _contentEncoding ?? Encoding.Default; var writer = new StreamWriter (destination, enc, 256); writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription); writer.Write (headers.ToStringMultiValue (true)); writer.Flush (); // Assumes that the destination was at position 0. destination.Position = enc.GetPreamble ().Length; return headers; } #endregion #region Public Methods /// <summary> /// Closes the connection to the client without returning a response. /// </summary> public void Abort () { if (_disposed) return; close (true); } /// <summary> /// Adds an HTTP header with the specified <paramref name="name"/> and /// <paramref name="value"/> to the headers for the response. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to add. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value of the header to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> or <paramref name="value"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The header cannot be allowed to add to the current headers. /// </exception> public void AddHeader (string name, string value) { Headers.Set (name, value); } /// <summary> /// Appends the specified <paramref name="cookie"/> to the cookies sent with the response. /// </summary> /// <param name="cookie"> /// A <see cref="Cookie"/> to append. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="cookie"/> is <see langword="null"/>. /// </exception> public void AppendCookie (Cookie cookie) { Cookies.Add (cookie); } /// <summary> /// Appends a <paramref name="value"/> to the specified HTTP header sent with the response. /// </summary> /// <param name="name"> /// A <see cref="string"/> that represents the name of the header to append /// <paramref name="value"/> to. /// </param> /// <param name="value"> /// A <see cref="string"/> that represents the value to append to the header. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> is <see langword="null"/> or empty. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="name"/> or <paramref name="value"/> contains invalid characters. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="name"/> is a restricted header name. /// </para> /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The length of <paramref name="value"/> is greater than 65,535 characters. /// </exception> /// <exception cref="InvalidOperationException"> /// The current headers cannot allow the header to append a value. /// </exception> public void AppendHeader (string name, string value) { Headers.Add (name, value); } /// <summary> /// Returns the response to the client and releases the resources used by /// this <see cref="HttpListenerResponse"/> instance. /// </summary> public void Close () { if (_disposed) return; close (false); } /// <summary> /// Returns the response with the specified array of <see cref="byte"/> to the client and /// releases the resources used by this <see cref="HttpListenerResponse"/> instance. /// </summary> /// <param name="responseEntity"> /// An array of <see cref="byte"/> that contains the response entity body data. /// </param> /// <param name="willBlock"> /// <c>true</c> if this method blocks execution while flushing the stream to the client; /// otherwise, <c>false</c>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="responseEntity"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public void Close (byte[] responseEntity, bool willBlock) { checkDisposed (); if (responseEntity == null) throw new ArgumentNullException ("responseEntity"); var len = responseEntity.Length; var output = OutputStream; if (willBlock) { output.Write (responseEntity, 0, len); close (false); return; } output.BeginWrite ( responseEntity, 0, len, ar => { output.EndWrite (ar); close (false); }, null); } /// <summary> /// Copies some properties from the specified <see cref="HttpListenerResponse"/> to /// this response. /// </summary> /// <param name="templateResponse"> /// A <see cref="HttpListenerResponse"/> to copy. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="templateResponse"/> is <see langword="null"/>. /// </exception> public void CopyFrom (HttpListenerResponse templateResponse) { if (templateResponse == null) throw new ArgumentNullException ("templateResponse"); if (templateResponse._headers != null) { if (_headers != null) _headers.Clear (); Headers.Add (templateResponse._headers); } else if (_headers != null) { _headers = null; } _contentLength = templateResponse._contentLength; _statusCode = templateResponse._statusCode; _statusDescription = templateResponse._statusDescription; _keepAlive = templateResponse._keepAlive; _version = templateResponse._version; } /// <summary> /// Configures the response to redirect the client's request to /// the specified <paramref name="url"/>. /// </summary> /// <remarks> /// This method sets the <see cref="HttpListenerResponse.RedirectLocation"/> property to /// <paramref name="url"/>, the <see cref="HttpListenerResponse.StatusCode"/> property to /// <c>302</c>, and the <see cref="HttpListenerResponse.StatusDescription"/> property to /// <c>"Found"</c>. /// </remarks> /// <param name="url"> /// A <see cref="string"/> that represents the URL to redirect the client's request to. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="url"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="url"/> isn't an absolute URL. /// </exception> /// <exception cref="InvalidOperationException"> /// The response has already been sent. /// </exception> /// <exception cref="ObjectDisposedException"> /// This object is closed. /// </exception> public void Redirect (string url) { checkDisposedOrHeadersSent (); if (url == null) throw new ArgumentNullException ("url"); Uri uri = null; if (!url.MaybeUri () || !Uri.TryCreate (url, UriKind.Absolute, out uri)) throw new ArgumentException ("Not an absolute URL.", "url"); _location = url; _statusCode = 302; _statusDescription = "Found"; } /// <summary> /// Adds or updates a <paramref name="cookie"/> in the cookies sent with the response. /// </summary> /// <param name="cookie"> /// A <see cref="Cookie"/> to set. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="cookie"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="cookie"/> already exists in the cookies and couldn't be replaced. /// </exception> public void SetCookie (Cookie cookie) { if (cookie == null) throw new ArgumentNullException ("cookie"); if (!canAddOrUpdate (cookie)) throw new ArgumentException ("Cannot be replaced.", "cookie"); Cookies.Add (cookie); } #endregion #region Explicit Interface Implementations /// <summary> /// Releases all resources used by the <see cref="HttpListenerResponse"/>. /// </summary> void IDisposable.Dispose () { if (_disposed) return; close (true); // Same as the Abort method. } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Windows.Storage.FileProperties; using Windows.Storage.Streams; using Windows.Storage; namespace System.IO { /// <summary> /// Contains extension methods that provide convenience helpers for WinRT IO. /// </summary> public static class WindowsRuntimeStorageExtensions { #region Extensions on IStorageFile for retreaving a managed Stream [CLSCompliant(false)] public static Task<Stream> OpenStreamForReadAsync(this IStorageFile windowsRuntimeFile) { if (windowsRuntimeFile == null) throw new ArgumentNullException(nameof(windowsRuntimeFile)); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); return OpenStreamForReadAsyncCore(windowsRuntimeFile); } private static async Task<Stream> OpenStreamForReadAsyncCore(this IStorageFile windowsRuntimeFile) { Contract.Requires(windowsRuntimeFile != null); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); try { IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.Read) .AsTask().ConfigureAwait(continueOnCapturedContext: false); Stream managedStream = windowsRuntimeStream.AsStreamForRead(); return managedStream; } catch (Exception ex) { // From this API, managed dev expect IO exceptions for "something wrong": WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return null; } } [CLSCompliant(false)] public static Task<Stream> OpenStreamForWriteAsync(this IStorageFile windowsRuntimeFile) { if (windowsRuntimeFile == null) throw new ArgumentNullException(nameof(windowsRuntimeFile)); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); return OpenStreamForWriteAsyncCore(windowsRuntimeFile, 0); } private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFile windowsRuntimeFile, Int64 offset) { Contract.Requires(windowsRuntimeFile != null); Contract.Requires(offset >= 0); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); try { IRandomAccessStream windowsRuntimeStream = await windowsRuntimeFile.OpenAsync(FileAccessMode.ReadWrite) .AsTask().ConfigureAwait(continueOnCapturedContext: false); Stream managedStream = windowsRuntimeStream.AsStreamForWrite(); managedStream.Position = offset; return managedStream; } catch (Exception ex) { // From this API, managed dev expect IO exceptions for "something wrong": WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return null; } } #endregion Extensions on IStorageFile for retreaving a managed Stream #region Extensions on IStorageFolder for retreaving a managed Stream [CLSCompliant(false)] public static Task<Stream> OpenStreamForReadAsync(this IStorageFolder rootDirectory, String relativePath) { if (rootDirectory == null) throw new ArgumentNullException(nameof(rootDirectory)); if (relativePath == null) throw new ArgumentNullException(nameof(relativePath)); if (String.IsNullOrWhiteSpace(relativePath)) throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, nameof(relativePath)); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); return OpenStreamForReadAsyncCore(rootDirectory, relativePath); } private static async Task<Stream> OpenStreamForReadAsyncCore(this IStorageFolder rootDirectory, String relativePath) { Contract.Requires(rootDirectory != null); Contract.Requires(!String.IsNullOrWhiteSpace(relativePath)); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); try { IStorageFile windowsRuntimeFile = await rootDirectory.GetFileAsync(relativePath) .AsTask().ConfigureAwait(continueOnCapturedContext: false); Stream managedStream = await windowsRuntimeFile.OpenStreamForReadAsync() .ConfigureAwait(continueOnCapturedContext: false); return managedStream; } catch (Exception ex) { // From this API, managed dev expect IO exceptions for "something wrong": WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return null; } } [CLSCompliant(false)] public static Task<Stream> OpenStreamForWriteAsync(this IStorageFolder rootDirectory, String relativePath, CreationCollisionOption creationCollisionOption) { if (rootDirectory == null) throw new ArgumentNullException(nameof(rootDirectory)); if (relativePath == null) throw new ArgumentNullException(nameof(relativePath)); if (String.IsNullOrWhiteSpace(relativePath)) throw new ArgumentException(SR.Argument_RelativePathMayNotBeWhitespaceOnly, nameof(relativePath)); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); return OpenStreamForWriteAsyncCore(rootDirectory, relativePath, creationCollisionOption); } private static async Task<Stream> OpenStreamForWriteAsyncCore(this IStorageFolder rootDirectory, String relativePath, CreationCollisionOption creationCollisionOption) { Contract.Requires(rootDirectory != null); Contract.Requires(!String.IsNullOrWhiteSpace(relativePath)); Contract.Requires(creationCollisionOption == CreationCollisionOption.FailIfExists || creationCollisionOption == CreationCollisionOption.GenerateUniqueName || creationCollisionOption == CreationCollisionOption.OpenIfExists || creationCollisionOption == CreationCollisionOption.ReplaceExisting, "The specified creationCollisionOption has a value that is not a value we considered when devising the" + " policy about Append-On-OpenIfExists used in this method. Apparently a new enum value was added to the" + " CreationCollisionOption type and we need to make sure that the policy still makes sense."); Contract.Ensures(Contract.Result<Task<Stream>>() != null); Contract.EndContractBlock(); try { // Open file and set up default options for opening it: IStorageFile windowsRuntimeFile = await rootDirectory.CreateFileAsync(relativePath, creationCollisionOption) .AsTask().ConfigureAwait(continueOnCapturedContext: false); Int64 offset = 0; // If the specified creationCollisionOption was OpenIfExists, then we will try to APPEND, otherwise we will OVERWRITE: if (creationCollisionOption == CreationCollisionOption.OpenIfExists) { BasicProperties fileProperties = await windowsRuntimeFile.GetBasicPropertiesAsync() .AsTask().ConfigureAwait(continueOnCapturedContext: false); UInt64 fileSize = fileProperties.Size; Debug.Assert(fileSize <= Int64.MaxValue, ".NET streams assume that file sizes are not larger than Int64.MaxValue," + " so we are not supporting the situation where this is not the case."); offset = checked((Int64)fileSize); } // Now open a file with the correct options: Stream managedStream = await OpenStreamForWriteAsyncCore(windowsRuntimeFile, offset).ConfigureAwait(continueOnCapturedContext: false); return managedStream; } catch (Exception ex) { // From this API, managed dev expect IO exceptions for "something wrong": WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return null; } } #endregion Extensions on IStorageFolder for retreaving a managed Stream } // class WindowsRuntimeStorageExtensions } // namespace // WindowsRuntimeStorageExtensions.cs
// // Mono.CSharp.Debugger/MonoSymbolWriter.cs // // Author: // Martin Baulig (martin@ximian.com) // // This is the default implementation of the System.Diagnostics.SymbolStore.ISymbolWriter // interface. // // (C) 2002 Ximian, Inc. http://www.ximian.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.IO; namespace SquabPie.Mono.CompilerServices.SymbolWriter { public class MonoSymbolWriter { List<SourceMethodBuilder> methods; List<SourceFileEntry> sources; List<CompileUnitEntry> comp_units; protected readonly MonoSymbolFile file; string filename; private SourceMethodBuilder current_method; Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder> (); public MonoSymbolWriter (string filename) { this.methods = new List<SourceMethodBuilder> (); this.sources = new List<SourceFileEntry> (); this.comp_units = new List<CompileUnitEntry> (); this.file = new MonoSymbolFile (); this.filename = filename + ".mdb"; } public MonoSymbolFile SymbolFile { get { return file; } } public void CloseNamespace () { } public void DefineLocalVariable (int index, string name) { if (current_method == null) return; current_method.AddLocal (index, name); } public void DefineCapturedLocal (int scope_id, string name, string captured_name) { file.DefineCapturedVariable (scope_id, name, captured_name, CapturedVariable.CapturedKind.Local); } public void DefineCapturedParameter (int scope_id, string name, string captured_name) { file.DefineCapturedVariable (scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter); } public void DefineCapturedThis (int scope_id, string captured_name) { file.DefineCapturedVariable (scope_id, "this", captured_name, CapturedVariable.CapturedKind.This); } public void DefineCapturedScope (int scope_id, int id, string captured_name) { file.DefineCapturedScope (scope_id, id, captured_name); } public void DefineScopeVariable (int scope, int index) { if (current_method == null) return; current_method.AddScopeVariable (scope, index); } public void MarkSequencePoint (int offset, SourceFileEntry file, int line, int column, bool is_hidden) { if (current_method == null) return; current_method.MarkSequencePoint (offset, file, line, column, is_hidden); } public SourceMethodBuilder OpenMethod (ICompileUnit file, int ns_id, IMethodDef method) { SourceMethodBuilder builder = new SourceMethodBuilder (file, ns_id, method); current_method_stack.Push (current_method); current_method = builder; methods.Add (current_method); return builder; } public void CloseMethod () { current_method = (SourceMethodBuilder) current_method_stack.Pop (); } public SourceFileEntry DefineDocument (string url) { SourceFileEntry entry = new SourceFileEntry (file, url); sources.Add (entry); return entry; } public SourceFileEntry DefineDocument (string url, byte[] guid, byte[] checksum) { SourceFileEntry entry = new SourceFileEntry (file, url, guid, checksum); sources.Add (entry); return entry; } public CompileUnitEntry DefineCompilationUnit (SourceFileEntry source) { CompileUnitEntry entry = new CompileUnitEntry (file, source); comp_units.Add (entry); return entry; } public int DefineNamespace (string name, CompileUnitEntry unit, string[] using_clauses, int parent) { if ((unit == null) || (using_clauses == null)) throw new NullReferenceException (); return unit.DefineNamespace (name, using_clauses, parent); } public int OpenScope (int start_offset) { if (current_method == null) return 0; current_method.StartBlock (CodeBlockEntry.Type.Lexical, start_offset); return 0; } public void CloseScope (int end_offset) { if (current_method == null) return; current_method.EndBlock (end_offset); } public void OpenCompilerGeneratedBlock (int start_offset) { if (current_method == null) return; current_method.StartBlock (CodeBlockEntry.Type.CompilerGenerated, start_offset); } public void CloseCompilerGeneratedBlock (int end_offset) { if (current_method == null) return; current_method.EndBlock (end_offset); } public void StartIteratorBody (int start_offset) { current_method.StartBlock (CodeBlockEntry.Type.IteratorBody, start_offset); } public void EndIteratorBody (int end_offset) { current_method.EndBlock (end_offset); } public void StartIteratorDispatcher (int start_offset) { current_method.StartBlock (CodeBlockEntry.Type.IteratorDispatcher, start_offset); } public void EndIteratorDispatcher (int end_offset) { current_method.EndBlock (end_offset); } public void DefineAnonymousScope (int id) { file.DefineAnonymousScope (id); } public void WriteSymbolFile (Guid guid) { foreach (SourceMethodBuilder method in methods) method.DefineMethod (file); try { // We mmap the file, so unlink the previous version since it may be in use File.Delete (filename); } catch { // We can safely ignore } using (FileStream fs = new FileStream (filename, FileMode.Create, FileAccess.Write)) { file.CreateSymbolFile (guid, fs); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Semantics; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1063: Implement IDisposable Correctly /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class ImplementIDisposableCorrectlyAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1063"; private const string HelpLinkUri = "https://msdn.microsoft.com/library/ms244737.aspx"; private const string DisposeMethodName = "Dispose"; private const string GarbageCollectorTypeName = "System.GC"; private const string SuppressFinalizeMethodName = "SuppressFinalize"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageIDisposableReimplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageIDisposableReimplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageFinalizeOverride = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeOverride), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDisposeOverride = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeOverride), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDisposeSignature = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeSignature), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageRenameDispose = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageRenameDispose), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDisposeBoolSignature = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeBoolSignature), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageDisposeImplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageDisposeImplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageFinalizeImplementation = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageFinalizeImplementation), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageProvideDisposeBool = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyMessageProvideDisposeBool), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.ImplementIDisposableCorrectlyDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); internal static DiagnosticDescriptor IDisposableReimplementationRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageIDisposableReimplementation, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor FinalizeOverrideRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageFinalizeOverride, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor DisposeOverrideRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDisposeOverride, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor DisposeSignatureRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDisposeSignature, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor RenameDisposeRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageRenameDispose, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor DisposeBoolSignatureRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDisposeBoolSignature, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor DisposeImplementationRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageDisposeImplementation, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor FinalizeImplementationRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageFinalizeImplementation, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor ProvideDisposeBoolRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageProvideDisposeBool, DiagnosticCategory.Design, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(IDisposableReimplementationRule, FinalizeOverrideRule, DisposeOverrideRule, DisposeSignatureRule, RenameDisposeRule, DisposeBoolSignatureRule, DisposeImplementationRule, FinalizeImplementationRule, ProvideDisposeBoolRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterCompilationStartAction( context => { INamedTypeSymbol disposableType = WellKnownTypes.IDisposable(context.Compilation); if (disposableType == null) { return; } var disposeInterfaceMethod = disposableType.GetMembers(DisposeMethodName).Single() as IMethodSymbol; if (disposeInterfaceMethod == null) { return; } INamedTypeSymbol garbageCollectorType = context.Compilation.GetTypeByMetadataName(GarbageCollectorTypeName); if (garbageCollectorType == null) { return; } var suppressFinalizeMethod = garbageCollectorType.GetMembers(SuppressFinalizeMethodName).Single() as IMethodSymbol; if (suppressFinalizeMethod == null) { return; } var analyzer = new Analyzer(context.Compilation, disposableType, disposeInterfaceMethod, suppressFinalizeMethod); analyzer.Initialize(context); }); } private static bool IsDisposeBoolMethod(IMethodSymbol method) { if (method.Name == DisposeMethodName && method.MethodKind == MethodKind.Ordinary && method.ReturnsVoid && method.Parameters.Length == 1) { IParameterSymbol parameter = method.Parameters[0]; if (parameter.Type != null && parameter.Type.SpecialType == SpecialType.System_Boolean && parameter.RefKind == RefKind.None) { return true; } } return false; } /// <summary> /// Analyzes single instance of compilation. /// </summary> private class Analyzer { private readonly Compilation _compilation; private readonly INamedTypeSymbol _disposableType; private readonly IMethodSymbol _disposeInterfaceMethod; private readonly IMethodSymbol _suppressFinalizeMethod; public Analyzer(Compilation compilation, INamedTypeSymbol disposableType, IMethodSymbol disposeInterfaceMethod, IMethodSymbol suppressFinalizeMethod) { _compilation = compilation; _disposableType = disposableType; _disposeInterfaceMethod = disposeInterfaceMethod; _suppressFinalizeMethod = suppressFinalizeMethod; } public void Initialize(CompilationStartAnalysisContext context) { context.RegisterSymbolAction(AnalyzeNamedTypeSymbol, SymbolKind.NamedType); context.RegisterOperationBlockAction(AnalyzeOperationBlock); } private void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context) { var type = context.Symbol as INamedTypeSymbol; if (type != null && type.TypeKind == TypeKind.Class) { bool implementsDisposableInBaseType = ImplementsDisposableInBaseType(type); if (ImplementsDisposableDirectly(type)) { IMethodSymbol disposeMethod = FindDisposeMethod(type); if (disposeMethod != null) { // This is difference from FxCop implementation // IDisposable Reimplementation Rule is violated only if type re-implements Dispose method, not just interface // For example see unit tests: // CSharp_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation // Basic_CA1063_IDisposableReimplementation_NoDiagnostic_ImplementingInheritedInterfaceWithNoDisposeReimplementation CheckIDisposableReimplementationRule(type, context, implementsDisposableInBaseType); CheckDisposeSignatureRule(disposeMethod, type, context); CheckRenameDisposeRule(disposeMethod, type, context); if (!type.IsSealed && type.DeclaredAccessibility != Accessibility.Private) { IMethodSymbol disposeBoolMethod = FindDisposeBoolMethod(type); if (disposeBoolMethod != null) { CheckDisposeBoolSignatureRule(disposeBoolMethod, type, context); } else { CheckProvideDisposeBoolRule(type, context); } } } else if (type.Interfaces.Contains(_disposableType)) { // Reports violation, when type mentions IDisposable as implemented interface, // even when Dispose method is not implemented, but inherited from base type // For example see unit test: // CSharp_CA1063_IDisposableReimplementation_Diagnostic_ReImplementingIDisposableWithNoDisposeMethod CheckIDisposableReimplementationRule(type, context, implementsDisposableInBaseType); } } if (implementsDisposableInBaseType) { foreach (IMethodSymbol method in type.GetMembers().OfType<IMethodSymbol>()) { CheckDisposeOverrideRule(method, type, context); } CheckFinalizeOverrideRule(type, context); } } } private void AnalyzeOperationBlock(OperationBlockAnalysisContext context) { var method = context.OwningSymbol as IMethodSymbol; if (method == null) { return; } bool isFinalizerMethod = method.IsFinalizer(); bool isDisposeMethod = method.Name == DisposeMethodName; if (isFinalizerMethod || isDisposeMethod) { INamedTypeSymbol type = method.ContainingType; if (type != null && type.TypeKind == TypeKind.Class && !type.IsSealed && type.DeclaredAccessibility != Accessibility.Private) { if (ImplementsDisposableDirectly(type)) { IMethodSymbol disposeMethod = FindDisposeMethod(type); if (disposeMethod != null) { if (method == disposeMethod) { CheckDisposeImplementationRule(method, type, context.OperationBlocks, context); } else if (isFinalizerMethod) { // Check implementation of finalizer only if the class explicitly implements IDisposable // If class implements interface inherited from IDisposable and IDisposable is implemented in base class // then implementation of finalizer is ignored CheckFinalizeImplementationRule(method, type, context.OperationBlocks, context); } } } } } } /// <summary> /// Check rule: Remove IDisposable from the list of interfaces implemented by {0} and override the base class Dispose implementation instead. /// </summary> private static void CheckIDisposableReimplementationRule(INamedTypeSymbol type, SymbolAnalysisContext context, bool implementsDisposableInBaseType) { if (implementsDisposableInBaseType) { context.ReportDiagnostic(type.CreateDiagnostic(IDisposableReimplementationRule, type.Name)); } } /// <summary> /// Checks rule: Ensure that {0} is declared as public and sealed. /// </summary> private static void CheckDisposeSignatureRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context) { if (!method.IsPublic() || method.IsAbstract || method.IsVirtual || (method.IsOverride && !method.IsSealed)) { context.ReportDiagnostic(method.CreateDiagnostic(DisposeSignatureRule, $"{type.Name}.{method.Name}")); } } /// <summary> /// Checks rule: Rename {0} to 'Dispose' and ensure that it is declared as public and sealed. /// </summary> private static void CheckRenameDisposeRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context) { if (method.Name != DisposeMethodName) { context.ReportDiagnostic(method.CreateDiagnostic(RenameDisposeRule, $"{type.Name}.{method.Name}")); } } /// <summary> /// Checks rule: Remove {0}, override Dispose(bool disposing), and put the dispose logic in the code path where 'disposing' is true. /// </summary> private void CheckDisposeOverrideRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context) { if (method.MethodKind == MethodKind.Ordinary && method.IsOverride && method.ReturnsVoid && method.Parameters.Length == 0) { bool isDisposeOverride = false; for (IMethodSymbol m = method.OverriddenMethod; m != null; m = m.OverriddenMethod) { if (m == FindDisposeMethod(m.ContainingType)) { isDisposeOverride = true; break; } } if (isDisposeOverride) { context.ReportDiagnostic(method.CreateDiagnostic(DisposeOverrideRule, $"{type.Name}.{method.Name}")); } } } /// <summary> /// Checks rule: Remove the finalizer from type {0}, override Dispose(bool disposing), and put the finalization logic in the code path where 'disposing' is false. /// </summary> private static void CheckFinalizeOverrideRule(INamedTypeSymbol type, SymbolAnalysisContext context) { if (type.HasFinalizer()) { context.ReportDiagnostic(type.CreateDiagnostic(FinalizeOverrideRule, type.Name)); } } /// <summary> /// Checks rule: Provide an overridable implementation of Dispose(bool) on {0} or mark the type as sealed. A call to Dispose(false) should only clean up native resources. A call to Dispose(true) should clean up both managed and native resources. /// </summary> private static void CheckProvideDisposeBoolRule(INamedTypeSymbol type, SymbolAnalysisContext context) { context.ReportDiagnostic(type.CreateDiagnostic(ProvideDisposeBoolRule, type.Name)); } /// <summary> /// Checks rule: Ensure that {0} is declared as protected, virtual, and unsealed. /// </summary> private static void CheckDisposeBoolSignatureRule(IMethodSymbol method, INamedTypeSymbol type, SymbolAnalysisContext context) { if (method.DeclaredAccessibility != Accessibility.Protected || !(method.IsVirtual || method.IsAbstract || method.IsOverride) || method.IsSealed) { context.ReportDiagnostic(method.CreateDiagnostic(DisposeBoolSignatureRule, $"{type.Name}.{method.Name}")); } } /// <summary> /// Checks rule: Modify {0} so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns. /// </summary> private void CheckDisposeImplementationRule(IMethodSymbol method, INamedTypeSymbol type, ImmutableArray<IOperation> operationBlocks, OperationBlockAnalysisContext context) { var validator = new DisposeImplementationValidator(_suppressFinalizeMethod, type); if (!validator.Validate(operationBlocks)) { context.ReportDiagnostic(method.CreateDiagnostic(DisposeImplementationRule, $"{type.Name}.{method.Name}")); } } /// <summary> /// Checks rule: Modify {0} so that it calls Dispose(false) and then returns. /// </summary> private static void CheckFinalizeImplementationRule(IMethodSymbol method, INamedTypeSymbol type, ImmutableArray<IOperation> operationBlocks, OperationBlockAnalysisContext context) { // TODO: Implement check of Finalize } /// <summary> /// Checks if type implements IDisposable interface or an interface inherited from IDisposable. /// Only direct implementation is taken into account, implementation in base type is ignored. /// </summary> private bool ImplementsDisposableDirectly(ITypeSymbol type) { return type.Interfaces.Any(i => i.Inherits(_disposableType)); } /// <summary> /// Checks if base type implements IDisposable interface directly or indirectly. /// </summary> private bool ImplementsDisposableInBaseType(ITypeSymbol type) { return type.BaseType != null && type.BaseType.AllInterfaces.Contains(_disposableType); } /// <summary> /// Returns method that implements IDisposable.Dispose operation. /// Only direct implementation is taken into account, implementation in base type is ignored. /// </summary> private IMethodSymbol FindDisposeMethod(INamedTypeSymbol type) { var disposeMethod = type.FindImplementationForInterfaceMember(_disposeInterfaceMethod) as IMethodSymbol; if (disposeMethod != null && disposeMethod.ContainingType == type) { return disposeMethod; } return null; } /// <summary> /// Returns method: void Dispose(bool) /// </summary> private static IMethodSymbol FindDisposeBoolMethod(INamedTypeSymbol type) { return type.GetMembers(DisposeMethodName).OfType<IMethodSymbol>().FirstOrDefault(IsDisposeBoolMethod); } } /// <summary> /// Validates implementation of Dispose method. The method must call Dispose(true) and then GC.SuppressFinalize(this). /// </summary> private struct DisposeImplementationValidator { // this type will be created per compilation // this is actually a bug - https://github.com/dotnet/roslyn-analyzers/issues/845 #pragma warning disable RS1008 private readonly IMethodSymbol _suppressFinalizeMethod; private readonly INamedTypeSymbol _type; #pragma warning restore RS1008 private bool _callsDisposeBool; private bool _callsSuppressFinalize; public DisposeImplementationValidator(IMethodSymbol suppressFinalizeMethod, INamedTypeSymbol type) { _callsDisposeBool = false; _callsSuppressFinalize = false; _suppressFinalizeMethod = suppressFinalizeMethod; _type = type; } public bool Validate(ImmutableArray<IOperation> operations) { _callsDisposeBool = false; _callsSuppressFinalize = false; if (ValidateOperations(operations)) { return _callsDisposeBool && _callsSuppressFinalize; } return false; } private bool ValidateOperations(ImmutableArray<IOperation> operations) { foreach (IOperation operation in operations) { if (!ValidateOperation(operation)) { return false; } } return true; } private bool ValidateOperation(IOperation operation) { switch (operation.Kind) { case OperationKind.EmptyStatement: case OperationKind.LabelStatement: return true; case OperationKind.BlockStatement: var blockStatement = (IBlockStatement)operation; return ValidateOperations(blockStatement.Statements); case OperationKind.ExpressionStatement: var expressionStatement = (IExpressionStatement)operation; return ValidateExpression(expressionStatement); default: return false; } } private bool ValidateExpression(IExpressionStatement expressionStatement) { if (expressionStatement.Expression == null || expressionStatement.Expression.Kind != OperationKind.InvocationExpression) { return false; } var invocationExpression = (IInvocationExpression)expressionStatement.Expression; if (!_callsDisposeBool) { bool result = IsDisposeBoolCall(invocationExpression); if (result) { _callsDisposeBool = true; } return result; } else if (!_callsSuppressFinalize) { bool result = IsSuppressFinalizeCall(invocationExpression); if (result) { _callsSuppressFinalize = true; } return result; } return false; } private bool IsDisposeBoolCall(IInvocationExpression invocationExpression) { if (invocationExpression.TargetMethod == null || invocationExpression.TargetMethod.ContainingType != _type || !IsDisposeBoolMethod(invocationExpression.TargetMethod)) { return false; } if (invocationExpression.Instance.Kind != OperationKind.InstanceReferenceExpression) { return false; } var instanceReferenceExpression = (IInstanceReferenceExpression)invocationExpression.Instance; if (instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Implicit && instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Explicit) { return false; } if (invocationExpression.ArgumentsInParameterOrder.Length != 1) { return false; } IArgument argument = invocationExpression.ArgumentsInParameterOrder[0]; if (argument.Value.Kind != OperationKind.LiteralExpression) { return false; } var literal = (ILiteralExpression)argument.Value; if (!literal.ConstantValue.HasValue || !true.Equals(literal.ConstantValue.Value)) { return false; } return true; } private bool IsSuppressFinalizeCall(IInvocationExpression invocationExpression) { if (invocationExpression.TargetMethod != _suppressFinalizeMethod) { return false; } if (invocationExpression.ArgumentsInParameterOrder.Length != 1) { return false; } IOperation argumentValue = invocationExpression.ArgumentsInParameterOrder[0].Value; if (argumentValue.Kind != OperationKind.ConversionExpression) { return false; } var conversion = (IConversionExpression)argumentValue; if (conversion.ConversionKind != ConversionKind.Cast && conversion.ConversionKind != ConversionKind.CSharp && conversion.ConversionKind != ConversionKind.Basic) { return false; } if (conversion.Operand == null || conversion.Operand.Kind != OperationKind.InstanceReferenceExpression) { return false; } var instanceReferenceExpression = (IInstanceReferenceExpression)conversion.Operand; if (instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Implicit && instanceReferenceExpression.InstanceReferenceKind != InstanceReferenceKind.Explicit) { return false; } return true; } } } }
using Shouldly; using StructureMap.Configuration.DSL; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using Xunit; namespace StructureMap.Testing.Graph { public class ContainerTester : Registry { public ContainerTester() { _container = new Container(registry => { //registry.Scan(x => x.Assembly("StructureMap.Testing.Widget")); registry.For<Rule>(); registry.For<IWidget>(); registry.For<WidgetMaker>(); }); } private IContainer _container; private void addColorInstance(string Color) { _container.Configure(r => { r.For<Rule>().Use<ColorRule>().Ctor<string>("color").Is(Color).Named(Color); r.For<IWidget>().Use<ColorWidget>().Ctor<string>("color").Is(Color).Named( Color); r.For<WidgetMaker>().Use<ColorWidgetMaker>().Ctor<string>("color").Is(Color). Named(Color); }); } public interface IProvider { } public class Provider : IProvider { } public class ClassThatUsesProvider { private readonly IProvider _provider; public ClassThatUsesProvider(IProvider provider) { _provider = provider; } public IProvider Provider { get { return _provider; } } } public class DifferentProvider : IProvider { } private void assertColorIs(IContainer container, string color) { container.GetInstance<IService>().ShouldBeOfType<ColorService>().Color.ShouldBe(color); } [Fact] public void can_inject_into_a_running_container() { var container = new Container(); container.Inject(typeof(ISport), new ConstructorInstance(typeof(Football))); container.GetInstance<ISport>() .ShouldBeOfType<Football>(); } [Fact] public void Can_set_profile_name_and_reset_defaults() { var container = new Container(r => { r.For<IService>() .Use<ColorService>().Named("Orange").Ctor<string>("color").Is( "Orange"); r.For<IService>().AddInstances(x => { x.Type<ColorService>().Named("Red").Ctor<string>("color").Is("Red"); x.Type<ColorService>().Named("Blue").Ctor<string>("color").Is("Blue"); x.Type<ColorService>().Named("Green").Ctor<string>("color").Is("Green"); }); r.Profile("Red", x => { x.For<IService>().Use("Red"); }); r.Profile("Blue", x => { x.For<IService>().Use("Blue"); }); }); assertColorIs(container, "Orange"); assertColorIs(container.GetProfile("Red"), "Red"); assertColorIs(container.GetProfile("Blue"), "Blue"); assertColorIs(container, "Orange"); } [Fact] public void CanBuildConcreteTypesThatAreNotPreviouslyRegistered() { IContainer manager = new Container( registry => registry.For<IProvider>().Use<Provider>()); // Now, have that same Container create a ClassThatUsesProvider. StructureMap will // see that ClassThatUsesProvider is concrete, determine its constructor args, and build one // for you with the default IProvider. No other configuration necessary. var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>(); classThatUsesProvider.Provider.ShouldBeOfType<Provider>(); } [Fact] public void CanBuildConcreteTypesThatAreNotPreviouslyRegisteredWithArgumentsProvided() { IContainer manager = new Container( registry => registry.For<IProvider>().Use<Provider>()); var differentProvider = new DifferentProvider(); var args = new ExplicitArguments(); args.Set<IProvider>(differentProvider); var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>(args); differentProvider.ShouldBeTheSameAs(classThatUsesProvider.Provider); } [Fact] public void can_get_the_default_instance() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); _container.Configure(x => x.For<Rule>().Use("Blue")); _container.GetInstance<Rule>().ShouldBeOfType<ColorRule>().Color.ShouldBe("Blue"); } [Fact] public void GetInstanceOf3Types() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); var rule = _container.GetInstance(typeof(Rule), "Blue") as ColorRule; rule.ShouldNotBeNull(); rule.Color.ShouldBe("Blue"); var widget = _container.GetInstance(typeof(IWidget), "Red") as ColorWidget; widget.ShouldNotBeNull(); widget.Color.ShouldBe("Red"); var maker = _container.GetInstance(typeof(WidgetMaker), "Orange") as ColorWidgetMaker; maker.ShouldNotBeNull(); maker.Color.ShouldBe("Orange"); } [Fact] public void GetMissingType() { var ex = Exception<StructureMapBuildPlanException>.ShouldBeThrownBy( () => _container.GetInstance(typeof(string))); } [Fact] public void InjectStub_by_name() { IContainer container = new Container(); var red = new ColorRule("Red"); var blue = new ColorRule("Blue"); container.Configure(x => { x.For<Rule>().Add(red).Named("Red"); x.For<Rule>().Add(blue).Named("Blue"); }); red.ShouldBeTheSameAs(container.GetInstance<Rule>("Red")); blue.ShouldBeTheSameAs(container.GetInstance<Rule>("Blue")); } [Fact] public void TryGetInstance_returns_instance_for_an_open_generic_that_it_can_close() { var container = new Container( x => x.For(typeof(IOpenGeneric<>)).Use(typeof(ConcreteOpenGeneric<>))); container.TryGetInstance<IOpenGeneric<object>>().ShouldNotBeNull(); } [Fact] public void TryGetInstance_returns_null_for_an_open_generic_that_it_cannot_close() { var container = new Container( x => x.For(typeof(IOpenGeneric<>)).Use(typeof(ConcreteOpenGeneric<>))); container.TryGetInstance<IAnotherOpenGeneric<object>>().ShouldBeNull(); } [Fact] public void TryGetInstance_ReturnsInstance_WhenTypeFound() { _container.Configure(c => c.For<IProvider>().Use<Provider>()); var instance = _container.TryGetInstance(typeof(IProvider)); instance.ShouldBeOfType(typeof(Provider)); } [Fact] public void TryGetInstance_ReturnsNull_WhenTypeNotFound() { var instance = _container.TryGetInstance(typeof(IProvider)); instance.ShouldBeNull(); } [Fact] public void TryGetInstanceViaGeneric_ReturnsInstance_WhenTypeFound() { _container.Configure(c => c.For<IProvider>().Use<Provider>()); var instance = _container.TryGetInstance<IProvider>(); instance.ShouldBeOfType(typeof(Provider)); } [Fact] public void TryGetInstanceViaGeneric_ReturnsNull_WhenTypeNotFound() { var instance = _container.TryGetInstance<IProvider>(); instance.ShouldBeNull(); } [Fact] public void TryGetInstanceViaName_ReturnsNull_WhenNotFound() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); var rule = _container.TryGetInstance(typeof(Rule), "Yellow"); rule.ShouldBeNull(); } [Fact] public void TryGetInstanceViaName_ReturnsTheOutInstance_WhenFound() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); var rule = _container.TryGetInstance(typeof(Rule), "Orange"); rule.ShouldBeOfType(typeof(ColorRule)); } // SAMPLE: TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound [Fact] public void TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); // "Orange" exists, so an object should be returned var instance = _container.TryGetInstance<Rule>("Orange"); instance.ShouldBeOfType(typeof(ColorRule)); } // ENDSAMPLE [Fact] public void TryGetInstanceViaNameAndGeneric_ReturnsNull_WhenTypeNotFound() { addColorInstance("Red"); addColorInstance("Orange"); addColorInstance("Blue"); // "Yellow" does not exist, so return null var instance = _container.TryGetInstance<Rule>("Yellow"); instance.ShouldBeNull(); } } public interface ISport { } public class Football : ISport { } public interface IOpenGeneric<T> { void Nop(); } public interface IAnotherOpenGeneric<T> { } public class ConcreteOpenGeneric<T> : IOpenGeneric<T> { public void Nop() { } } public class StringOpenGeneric : ConcreteOpenGeneric<string> { } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.AppService.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.AppService.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using System.Collections.Generic; using ResourceManager.Fluent.Core; using System.IO; using ResourceManager.Fluent; using ResourceManager.Fluent.Models; using System.Linq; using System; /// <summary> /// The base implementation for web apps and function apps. /// </summary> /// <typeparam name="FluentT">The fluent interface, WebApp or FunctionApp.</typeparam> /// <typeparam name="FluentImplT">The implementation class for FluentT.</typeparam> /// <typeparam name="FluentWithCreateT">The definition stage that derives from Creatable.</typeparam> internal abstract partial class AppServiceBaseImpl<FluentT,FluentImplT,FluentWithCreateT, DefAfterRegionT, DefAfterGroupT, UpdateT> : WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> where FluentImplT : AppServiceBaseImpl<FluentT, FluentImplT, FluentWithCreateT, DefAfterRegionT, DefAfterGroupT, UpdateT>, FluentT where FluentT : class, IWebAppBase where DefAfterRegionT : class where DefAfterGroupT : class where UpdateT : class, WebAppBase.Update.IUpdate<FluentT> { private AppServicePlanImpl appServicePlan; ///GENMHASH:07FBC6D492A2E1E463B39D4D7FFC40E9:66A6C8EDFAA0E618EA9FC53E296A637E internal async override Task<SiteInner> CreateOrUpdateInnerAsync(SiteInner site, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.CreateOrUpdateAsync(ResourceGroupName, Name, site, cancellationToken: cancellationToken); } ///GENMHASH:EB854F18026EDB6E01762FA4580BE789:E0C4A1757552CAB0ED8F92E2EB35D2E2 public override void Stop() { Extensions.Synchronize(() => Manager.Inner.WebApps.StopAsync(ResourceGroupName, Name)); } ///GENMHASH:6779D3D3C7AB7AAAE805BA0ABEE95C51:512E3D0409D7A159D1D192520CB3A8DB internal async override Task<StringDictionaryInner> UpdateAppSettingsAsync(StringDictionaryInner inner, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.UpdateApplicationSettingsAsync(ResourceGroupName, Name, inner, cancellationToken); } ///GENMHASH:88806945F575AAA522C2E09EBC366CC0:FDA787AD964B4EF34BCD2352730B6528 internal async override Task<SiteSourceControlInner> CreateOrUpdateSourceControlAsync(SiteSourceControlInner inner, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.CreateOrUpdateSourceControlAsync(ResourceGroupName, Name, inner, cancellationToken); } ///GENMHASH:620993DCE6DF78140D8125DD97478452:5A132EFB7A05E4DC22E7252CDF660609 internal async override Task<StringDictionaryInner> ListAppSettingsAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.ListApplicationSettingsAsync(ResourceGroupName, Name); } ///GENMHASH:62A0C790E618C837459BE1A5103CA0E5:E67D9CD74CA1A0DECF6EE2FD2CA91749 internal async override Task<SlotConfigNamesResourceInner> ListSlotConfigurationsAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.ListSlotConfigurationNamesAsync(ResourceGroupName, Name); } ///GENMHASH:807E62B6346803DB90804D0DEBD2FCA6:DE0948CBC34F6D6B889CD89BA36F4D94 internal async override Task DeleteSourceControlAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.DeleteSourceControlAsync(ResourceGroupName, Name); } ///GENMHASH:981FA7F7C88705FACC2675A0E796937F:791F75E9324E0F8CD9B54F2D9EF56E3D public FluentImplT WithNewAppServicePlan(string name) { appServicePlan = (AppServicePlanImpl)Manager.AppServicePlans.Define(name); string id = ResourceUtils.ConstructResourceId(Manager.SubscriptionId, ResourceGroupName, "Microsoft.Web", "serverFarms", name, ""); Inner.ServerFarmId = id; return (FluentImplT) this; } ///GENMHASH:CC6E0592F0BCD4CD83D832B40167E562:30CA9232F1D7C8ACB181740BD31D7B58 public async override Task VerifyDomainOwnershipAsync(string certificateOrderName, string domainVerificationToken, CancellationToken cancellationToken = default(CancellationToken)) { IdentifierInner identifierInner = new IdentifierInner() { IdentifierId = domainVerificationToken }; await Manager.Inner.WebApps.CreateOrUpdateDomainOwnershipIdentifierAsync(ResourceGroupName, Name, certificateOrderName, identifierInner, cancellationToken); } ///GENMHASH:6799EDFB0B008F8C0EB7E07EE71E6B34:9AA0391980CD01ABEA62130DB5348393 internal async override Task<SiteConfigResourceInner> CreateOrUpdateSiteConfigAsync(SiteConfigResourceInner siteConfig, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.CreateOrUpdateConfigurationAsync(ResourceGroupName, Name, siteConfig, cancellationToken); } ///GENMHASH:1AD5C303B4B7C1709305A18733B506B2:B2AAE3FC1D57B875FAA6AD38F9DB069C public override void ResetSlotConfigurations() { Extensions.Synchronize(() => Manager.Inner.WebApps.ResetProductionSlotConfigAsync(ResourceGroupName, Name)); } ///GENMHASH:2EDD4B59BAFACBDD881E1EB427AFB76D:6899DBE410B89E7D8EEB69725B8CE588 public FluentImplT WithPricingTier(PricingTier pricingTier) { appServicePlan.WithRegion(RegionName); appServicePlan.WithPricingTier(pricingTier); if (newGroup != null && IsInCreateMode) { appServicePlan.WithNewResourceGroup(ResourceGroupName); ((IndexableRefreshableWrapper<IResourceGroup, ResourceGroupInner>)newGroup).Inner.Location = RegionName; } else { appServicePlan.WithExistingResourceGroup(ResourceGroupName); } AddCreatableDependency(appServicePlan); return (FluentImplT)this; } ///GENMHASH:08CFC096AC6388D1C0E041ECDF099E3D:192EA146CBED61BBAAC7B336DA07F261 public override void Restart() { Extensions.Synchronize(() => Manager.Inner.WebApps.RestartAsync(ResourceGroupName, Name)); } ///GENMHASH:3F0152723C985A22C1032733AB942C96:9A3E19132DCD027C4BA1BBB085642F29 public override IPublishingProfile GetPublishingProfile() { Stream stream = Extensions.Synchronize(() => Manager.Inner.WebApps.ListPublishingProfileXmlWithSecretsAsync(ResourceGroupName, Name)); StreamReader reader = new StreamReader(stream); string xml = reader.ReadToEnd(); return new PublishingProfileImpl(xml); } ///GENMHASH:62F8B201D885123D1E906E306D144662:E1F277FB3368B266611D1FAD9307CC48 internal async override Task<SlotConfigNamesResourceInner> UpdateSlotConfigurationsAsync(SlotConfigNamesResourceInner inner, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.UpdateSlotConfigurationNamesAsync(ResourceGroupName, Name, inner, cancellationToken); } ///GENMHASH:924482EE7AA6A01820720743C2A59A72:AA2A43E94B10FDB1A9E9E89ED9CA279B public override void ApplySlotConfigurations(string slotName) { Extensions.Synchronize(() => Manager.Inner.WebApps.ApplySlotConfigToProductionAsync(ResourceGroupName, Name, new CsmSlotEntity() { TargetSlot = slotName })); Refresh(); } ///GENMHASH:21FDAEDB996672BE017C01C5DD8758D4:B4D4D99FF69FD9180176D4E47741258C internal async override Task<ConnectionStringDictionaryInner> UpdateConnectionStringsAsync(ConnectionStringDictionaryInner inner, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.UpdateConnectionStringsAsync(ResourceGroupName, Name, inner, cancellationToken); } ///GENMHASH:0FE78F842439357DA0333AABD3B95D59:1EF461DA96453123EA3CCA0E640170EC internal async override Task<ConnectionStringDictionaryInner> ListConnectionStringsAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.ListConnectionStringsAsync(ResourceGroupName, Name); } ///GENMHASH:BC033DDD8D749B9BBCDC5BADD5CF2B94:9F4E7075C3242FB2777F45453DB418B6 public FluentImplT WithFreePricingTier() { return WithPricingTier(new PricingTier("Free", "F1")); } ///GENMHASH:256905D5B839C64BFE9830503CB5607B:7AC64BDE9A6045728A97AD3B7E256F87 internal async override Task<SiteConfigResourceInner> GetConfigInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.GetConfigurationAsync(ResourceGroupName, Name); } ///GENMHASH:934D38FBA69BF2F25673598C416DD202:E29466D1FE6AACE8059987F066EC1188 public virtual FluentImplT WithExistingAppServicePlan(IAppServicePlan appServicePlan) { Inner.ServerFarmId = appServicePlan.Id; WithOperatingSystem(appServicePlan.OperatingSystem); if (newGroup != null && IsInCreateMode) { ((IndexableRefreshableWrapper<IResourceGroup, ResourceGroupInner>)newGroup).Inner.Location = appServicePlan.RegionName; } this.WithRegion(appServicePlan.RegionName); return (FluentImplT) this; } ///GENMHASH:8C5F8B18192B4F8FD7D43AB4D318EA69:E232113DB866C8D255AE12F7A61042E8 public override IReadOnlyDictionary<string, IHostNameBinding> GetHostNameBindings() { var collectionInner = Extensions.Synchronize(() => Manager.Inner.WebApps.ListHostNameBindingsAsync(ResourceGroupName, Name)); var hostNameBindings = new List<IHostNameBinding>(); foreach (var inner in collectionInner) { hostNameBindings.Add(new HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>( inner, (FluentImplT) this)); } return hostNameBindings.ToDictionary(b => b.Name.Replace(Name + "/", "")); } ///GENMHASH:EB8C33DACE377CBB07C354F38C5BEA32:391885361D8D6FDB8CD9E96400E16B73 public override void VerifyDomainOwnership(string certificateOrderName, string domainVerificationToken) { Extensions.Synchronize(() => VerifyDomainOwnershipAsync(certificateOrderName, domainVerificationToken)); } ///GENMHASH:9EC0529BA0D08B75AD65E98A4BA01D5D:AD50571B7362BCAADE526027DA36B58F protected async override Task<SiteInner> GetSiteAsync(CancellationToken cancellationToken) { return await Manager.Inner.WebApps.GetAsync(ResourceGroupName, Name, cancellationToken); } ///GENMHASH:BC96AA8FDB678157AC1E6F0AA511AB65:20A70C4EEFBA9DE9AD6AA6D9133187D7 public override IWebAppSourceControl GetSourceControl() { SiteSourceControlInner siteSourceControlInner = Extensions.Synchronize(() => Manager.Inner.WebApps.GetSourceControlAsync(ResourceGroupName, Name)); return new WebAppSourceControlImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>(siteSourceControlInner, (FluentImplT) this); } ///GENMHASH:0F38250A3837DF9C2C345D4A038B654B:57465AB4A649A705C9DC2183EE743214 public override void Start() { Extensions.Synchronize(() => Manager.Inner.WebApps.StartAsync(ResourceGroupName, Name)); } ///GENMHASH:B22FA99F4432342EBBDB2AB426A8D2A2:DB92CE96AE133E965FE6DE31D475D7ED internal AppServiceBaseImpl( string name, SiteInner innerObject, SiteConfigResourceInner configObject, SiteLogsConfigInner logConfig, IAppServiceManager manager) : base (name, innerObject, configObject, logConfig, manager) { } ///GENMHASH:DFC52755A97E7B13EB10FA2EB9538E4A:FCF3A2AD2F52743B995DDA1FE7D020CB public override void Swap(string slotName) { Extensions.Synchronize(() => Manager.Inner.WebApps.SwapSlotWithProductionAsync(ResourceGroupName, Name, new CsmSlotEntity { TargetSlot = slotName })); Refresh(); } ///GENMHASH:FCAC8C2F8D6E12CB6F5D7787A2837016:932BF8229CACF0E669A4DDE8FAEB10D4 internal async override Task DeleteHostNameBindingAsync(string hostname, CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.DeleteHostNameBindingAsync(ResourceGroupName, Name, hostname, cancellationToken); } internal virtual FluentImplT WithNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) { return WithNewAppServicePlan(NewDefaultAppServicePlan().WithOperatingSystem(operatingSystem).WithPricingTier(pricingTier)); } private FluentImplT WithOperatingSystem(OperatingSystem os) { if (os == Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Linux) { Inner.Reserved = true; Inner.Kind = Inner.Kind + ",linux"; } return (FluentImplT)this; } public FluentImplT WithNewAppServicePlan(ICreatable<Microsoft.Azure.Management.AppService.Fluent.IAppServicePlan> appServicePlanCreatable) { AddCreatableDependency(appServicePlanCreatable as IResourceCreator<IHasId>); string id = ResourceUtils.ConstructResourceId(this.Manager.SubscriptionId, ResourceGroupName, "Microsoft.Web", "serverFarms", appServicePlanCreatable.Name, ""); Inner.ServerFarmId = id; WithOperatingSystem(((AppServicePlanImpl)appServicePlanCreatable).OperatingSystem()); return (FluentImplT)this; } private AppServicePlanImpl NewDefaultAppServicePlan() { String planName = SdkContext.RandomResourceName(Name + "plan", 32); AppServicePlanImpl appServicePlan = (AppServicePlanImpl) (this.Manager.AppServicePlans .Define(planName)) .WithRegion(RegionName); if (newGroup != null && IsInCreateMode) { appServicePlan = appServicePlan.WithNewResourceGroup(newGroup) as AppServicePlanImpl; } else { appServicePlan = appServicePlan.WithExistingResourceGroup(ResourceGroupName) as AppServicePlanImpl; } return appServicePlan; } internal override async Task<Models.SiteAuthSettingsInner> UpdateAuthenticationAsync(SiteAuthSettingsInner inner, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.UpdateAuthSettingsAsync(ResourceGroupName, Name, inner, cancellationToken); } public FluentImplT WithNewSharedAppServicePlan() { return WithNewAppServicePlan(Fluent.OperatingSystem.Windows, new PricingTier("Shared", "D1")); } public FluentImplT WithNewFreeAppServicePlan() { return WithNewAppServicePlan(Fluent.OperatingSystem.Windows, new PricingTier("Free", "F1")); } ///GENMHASH:80973546C834C7C29422D77A01231051:254A5188A8B9B221986ACC09C33E3859 public FluentImplT WithNewAppServicePlan(PricingTier pricingTier) { return WithNewAppServicePlan(OperatingSystem(), pricingTier); } ///GENMHASH:D5AD274A3026D80CDF6A0DD97D9F20D4:4A2ED55DAB8B08E815B4AB5554D9C60C public override async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.StartAsync(ResourceGroupName, Name, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:8E71F8927E941B28152FA821CDDF0634:5EC2069F42116C38D303F70C89D7F575 internal override async Task<Models.SiteAuthSettingsInner> GetAuthenticationAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.GetAuthSettingsAsync(ResourceGroupName, Name, cancellationToken); } ///GENMHASH:AE14C7C2170289895AEFF07E3516A2FC:186BCABCD05AC9B90A2EF619765A0DFE public override async Task ResetSlotConfigurationsAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.ResetProductionSlotConfigAsync(ResourceGroupName, Name, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:E7F5C40042323022AA5171FA979A6E79:27DA6227AE38DA9C9AC067D20F4EEEAC public override async Task SwapAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.SwapSlotWithProductionAsync(ResourceGroupName, Name, new CsmSlotEntity { TargetSlot = slotName }, cancellationToken); await RefreshAsync(cancellationToken); } ///GENMHASH:E10A5B0FD0E95947B1A669D51E6BD5C9:977A64CFAC7B27FE0960C4DC670C662E public override async Task<System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding>> GetHostNameBindingsAsync(CancellationToken cancellationToken = default(CancellationToken)) { var bindingsList = await PagedCollection<IHostNameBinding, HostNameBindingInner>.LoadPage( async (cancellation) => await Manager.Inner.WebApps.ListHostNameBindingsAsync(ResourceGroupName, Name, cancellation), Manager.Inner.WebApps.ListHostNameBindingsNextAsync, (inner) => new HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>(inner, (FluentImplT) this), true, cancellationToken); return bindingsList.ToDictionary(binding => binding.Name.Replace(this.Name + "/", "")); } public async override Task ApplySlotConfigurationsAsync(string slotName, CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.ApplySlotConfigToProductionAsync(ResourceGroupName, Name, new CsmSlotEntity { TargetSlot = slotName }, cancellationToken); await RefreshAsync(cancellationToken); } public async override Task StopAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.StopAsync(ResourceGroupName, Name, cancellationToken); await RefreshAsync(cancellationToken); } public async override Task<IPublishingProfile> GetPublishingProfileAsync(CancellationToken cancellationToken = default(CancellationToken)) { Stream stream = await Manager.Inner.WebApps.ListPublishingProfileXmlWithSecretsAsync(ResourceGroupName, Name, null, cancellationToken); StreamReader reader = new StreamReader(stream); string xml = reader.ReadToEnd(); return new PublishingProfileImpl(xml); } public async override Task RestartAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Manager.Inner.WebApps.RestartAsync(ResourceGroupName, Name, null, null, cancellationToken); await RefreshAsync(cancellationToken); } public async override Task<IWebAppSourceControl> GetSourceControlAsync(CancellationToken cancellationToken = default(CancellationToken)) { return new WebAppSourceControlImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> (await Manager.Inner.WebApps.GetSourceControlAsync(ResourceGroupName, Name, cancellationToken), this); } protected async override Task<SiteInner> GetInnerAsync(CancellationToken cancellationToken) { return await Manager.Inner.WebApps.GetAsync(ResourceGroupName, Name, cancellationToken); } internal override async Task<MSDeployStatusInner> CreateMSDeploy(MSDeploy msDeployInner, CancellationToken cancellationToken) { return await Manager.Inner.WebApps.CreateMSDeployOperationAsync(ResourceGroupName, Name, msDeployInner, cancellationToken); } public override Stream GetContainerLogs() { return Extensions.Synchronize(() => GetContainerLogsAsync()); } public override async Task<Stream> GetContainerLogsAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.GetWebSiteContainerLogsAsync(ResourceGroupName, Name, cancellationToken); } public override Stream GetContainerLogsZip() { return Extensions.Synchronize(() => GetContainerLogsZipAsync()); } public override async Task<Stream> GetContainerLogsZipAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.GetContainerLogsZipAsync(ResourceGroupName, Name, cancellationToken); } internal override async Task<Models.SiteLogsConfigInner> UpdateDiagnosticLogsConfigAsync(SiteLogsConfigInner siteLogConfig, CancellationToken cancellationToken = default(CancellationToken)) { return await Manager.Inner.WebApps.UpdateDiagnosticLogsConfigAsync(ResourceGroupName, Name, siteLogConfig, cancellationToken); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Diagnostics.Tracing { [System.FlagsAttribute] public enum EventActivityOptions { Detachable = 8, Disable = 2, None = 0, Recursive = 4, } [System.AttributeUsageAttribute((System.AttributeTargets)(64))] public sealed partial class EventAttribute : System.Attribute { public EventAttribute(int eventId) { } public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { return default(System.Diagnostics.Tracing.EventActivityOptions); } set { } } public System.Diagnostics.Tracing.EventChannel Channel { get { return default(System.Diagnostics.Tracing.EventChannel); } set { } } public int EventId { get { return default(int); } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { return default(System.Diagnostics.Tracing.EventKeywords); } set { } } public System.Diagnostics.Tracing.EventLevel Level { get { return default(System.Diagnostics.Tracing.EventLevel); } set { } } public string Message { get { return default(string); } set { } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { return default(System.Diagnostics.Tracing.EventOpcode); } set { } } public System.Diagnostics.Tracing.EventTags Tags { get { return default(System.Diagnostics.Tracing.EventTags); } set { } } public System.Diagnostics.Tracing.EventTask Task { get { return default(System.Diagnostics.Tracing.EventTask); } set { } } public byte Version { get { return default(byte); } set { } } } public enum EventChannel : byte { Admin = (byte)16, Analytic = (byte)18, Debug = (byte)19, None = (byte)0, Operational = (byte)17, } public enum EventCommand { Disable = -3, Enable = -2, SendManifest = -1, Update = 0, } public partial class EventCommandEventArgs : System.EventArgs { internal EventCommandEventArgs() { } public System.Collections.Generic.IDictionary<string, string> Arguments { get { return default(System.Collections.Generic.IDictionary<string, string>); } } public System.Diagnostics.Tracing.EventCommand Command { get { return default(System.Diagnostics.Tracing.EventCommand); } } public bool DisableEvent(int eventId) { return default(bool); } public bool EnableEvent(int eventId) { return default(bool); } } [System.AttributeUsageAttribute((System.AttributeTargets)(12), Inherited = false)] public partial class EventDataAttribute : System.Attribute { public EventDataAttribute() { } public string Name { get { return default(string); } set { } } } [System.AttributeUsageAttribute((System.AttributeTargets)(128))] public partial class EventFieldAttribute : System.Attribute { public EventFieldAttribute() { } public System.Diagnostics.Tracing.EventFieldFormat Format { get { return default(System.Diagnostics.Tracing.EventFieldFormat); } set { } } public System.Diagnostics.Tracing.EventFieldTags Tags { get { return default(System.Diagnostics.Tracing.EventFieldTags); } set { } } } public enum EventFieldFormat { Boolean = 3, Default = 0, Hexadecimal = 4, HResult = 15, Json = 12, String = 2, Xml = 11, } [System.FlagsAttribute] public enum EventFieldTags { None = 0, } [System.AttributeUsageAttribute((System.AttributeTargets)(128))] public partial class EventIgnoreAttribute : System.Attribute { public EventIgnoreAttribute() { } } [System.FlagsAttribute] public enum EventKeywords : long { All = (long)-1, AuditFailure = (long)4503599627370496, AuditSuccess = (long)9007199254740992, CorrelationHint = (long)4503599627370496, EventLogClassic = (long)36028797018963968, None = (long)0, Sqm = (long)2251799813685248, WdiContext = (long)562949953421312, WdiDiagnostic = (long)1125899906842624, } public enum EventLevel { Critical = 1, Error = 2, Informational = 4, LogAlways = 0, Verbose = 5, Warning = 3, } public abstract partial class EventListener : System.IDisposable { protected EventListener() { } public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { } public virtual void Dispose() { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string> arguments) { } public static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { return default(int); } protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { } protected internal abstract void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData); } [System.FlagsAttribute] public enum EventManifestOptions { AllCultures = 2, AllowEventSourceOverride = 8, None = 0, OnlyIfNeededForRegistration = 4, Strict = 1, } public enum EventOpcode { DataCollectionStart = 3, DataCollectionStop = 4, Extension = 5, Info = 0, Receive = 240, Reply = 6, Resume = 7, Send = 9, Start = 1, Stop = 2, Suspend = 8, } public partial class EventSource : System.IDisposable { protected EventSource() { } protected EventSource(bool throwOnEventWriteErrors) { } protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { } protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[] traits) { } public EventSource(string eventSourceName) { } public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { } public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[] traits) { } public System.Exception ConstructionException { get { return default(System.Exception); } } public static System.Guid CurrentThreadActivityId {[System.Security.SecuritySafeCriticalAttribute]get { return default(System.Guid); } } public System.Guid Guid { get { return default(System.Guid); } } public string Name { get { return default(string); } } public System.Diagnostics.Tracing.EventSourceSettings Settings { get { return default(System.Diagnostics.Tracing.EventSourceSettings); } } public event EventHandler<EventCommandEventArgs> EventCommandExecuted { add {} remove {} } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~EventSource() { } public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest) { return default(string); } public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { return default(string); } public static System.Guid GetGuid(System.Type eventSourceType) { return default(System.Guid); } public static string GetName(System.Type eventSourceType) { return default(string); } public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { return default(System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource>); } public string GetTrait(string key) { return default(string); } public bool IsEnabled() { return default(bool); } public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { return default(bool); } public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { return default(bool); } protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { } public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string> commandArguments) { } public static void SetCurrentThreadActivityId(System.Guid activityId) { } public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { oldActivityThatWillContinue = default(System.Guid); } public override string ToString() { return default(string); } public void Write(string eventName) { } public void Write(string eventName, System.Diagnostics.Tracing.EventSourceOptions options) { } public void Write<T>(string eventName, T data) { } public void Write<T>(string eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { } public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { } public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { } protected void WriteEvent(int eventId) { } protected void WriteEvent(int eventId, byte[] arg1) { } protected void WriteEvent(int eventId, int arg1) { } protected void WriteEvent(int eventId, int arg1, int arg2) { } protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { } protected void WriteEvent(int eventId, int arg1, string arg2) { } protected void WriteEvent(int eventId, long arg1) { } protected void WriteEvent(int eventId, long arg1, byte[] arg2) { } protected void WriteEvent(int eventId, long arg1, long arg2) { } protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { } protected void WriteEvent(int eventId, long arg1, string arg2) { } protected void WriteEvent(int eventId, params object[] args) { } protected void WriteEvent(int eventId, string arg1) { } protected void WriteEvent(int eventId, string arg1, int arg2) { } protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { } protected void WriteEvent(int eventId, string arg1, long arg2) { } protected void WriteEvent(int eventId, string arg1, string arg2) { } protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { } [System.CLSCompliantAttribute(false)] [System.Security.SecurityCriticalAttribute] protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { } protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object[] args) { } [System.CLSCompliantAttribute(false)] [System.Security.SecurityCriticalAttribute] protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] protected internal partial struct EventData { public System.IntPtr DataPointer { get { return default(System.IntPtr); } set { } } public int Size { get { return default(int); } set { } } } } [System.AttributeUsageAttribute((System.AttributeTargets)(4))] public sealed partial class EventSourceAttribute : System.Attribute { public EventSourceAttribute() { } public string Guid { get { return default(string); } set { } } public string LocalizationResources { get { return default(string); } set { } } public string Name { get { return default(string); } set { } } } public partial class EventSourceException : System.Exception { public EventSourceException() { } public EventSourceException(string message) { } public EventSourceException(string message, System.Exception innerException) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventSourceOptions { public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { return default(System.Diagnostics.Tracing.EventActivityOptions); } set { } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { return default(System.Diagnostics.Tracing.EventKeywords); } set { } } public System.Diagnostics.Tracing.EventLevel Level { get { return default(System.Diagnostics.Tracing.EventLevel); } set { } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { return default(System.Diagnostics.Tracing.EventOpcode); } set { } } public System.Diagnostics.Tracing.EventTags Tags { get { return default(System.Diagnostics.Tracing.EventTags); } set { } } } [System.FlagsAttribute] public enum EventSourceSettings { Default = 0, EtwManifestEventFormat = 4, EtwSelfDescribingEventFormat = 8, ThrowOnEventWriteErrors = 1, } [System.FlagsAttribute] public enum EventTags { None = 0, } public enum EventTask { None = 0, } public partial class EventWrittenEventArgs : System.EventArgs { internal EventWrittenEventArgs() { } public System.Guid ActivityId {[System.Security.SecurityCriticalAttribute]get { return default(System.Guid); } } public System.Diagnostics.Tracing.EventChannel Channel { get { return default(System.Diagnostics.Tracing.EventChannel); } } public int EventId { get { return default(int); } } public string EventName { get { return default(string); } } public System.Diagnostics.Tracing.EventSource EventSource { get { return default(System.Diagnostics.Tracing.EventSource); } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { return default(System.Diagnostics.Tracing.EventKeywords); } } public System.Diagnostics.Tracing.EventLevel Level { get { return default(System.Diagnostics.Tracing.EventLevel); } } public string Message { get { return default(string); } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { return default(System.Diagnostics.Tracing.EventOpcode); } } public System.Collections.ObjectModel.ReadOnlyCollection<object> Payload { get { return default(System.Collections.ObjectModel.ReadOnlyCollection<object>); } } public System.Collections.ObjectModel.ReadOnlyCollection<string> PayloadNames { get { return default(System.Collections.ObjectModel.ReadOnlyCollection<string>); } } public System.Guid RelatedActivityId {[System.Security.SecurityCriticalAttribute]get { return default(System.Guid); } } public System.Diagnostics.Tracing.EventTags Tags { get { return default(System.Diagnostics.Tracing.EventTags); } } public System.Diagnostics.Tracing.EventTask Task { get { return default(System.Diagnostics.Tracing.EventTask); } } public byte Version { get { return default(byte); } } } [System.AttributeUsageAttribute((System.AttributeTargets)(64))] public sealed partial class NonEventAttribute : System.Attribute { public NonEventAttribute() { } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// ModelBuildResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Autopilot.V1.Assistant { public class ModelBuildResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Enqueued = new StatusEnum("enqueued"); public static readonly StatusEnum Building = new StatusEnum("building"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Failed = new StatusEnum("failed"); public static readonly StatusEnum Canceled = new StatusEnum("canceled"); } private static Request BuildFetchRequest(FetchModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Fetch(FetchModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> FetchAsync(FetchModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Fetch(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchModelBuildOptions(pathAssistantSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> FetchAsync(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchModelBuildOptions(pathAssistantSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/ModelBuilds", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ResourceSet<ModelBuildResource> Read(ReadModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ModelBuildResource>.FromJson("model_builds", response.Content); return new ResourceSet<ModelBuildResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ResourceSet<ModelBuildResource>> ReadAsync(ReadModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ModelBuildResource>.FromJson("model_builds", response.Content); return new ResourceSet<ModelBuildResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ResourceSet<ModelBuildResource> Read(string pathAssistantSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadModelBuildOptions(pathAssistantSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ResourceSet<ModelBuildResource>> ReadAsync(string pathAssistantSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadModelBuildOptions(pathAssistantSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ModelBuildResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ModelBuildResource> NextPage(Page<ModelBuildResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ModelBuildResource> PreviousPage(Page<ModelBuildResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } private static Request BuildCreateRequest(CreateModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/ModelBuilds", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Create(CreateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> CreateAsync(CreateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the new resource </param> /// <param name="statusCallback"> The URL we should call using a POST method to send status information to your /// application </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Create(string pathAssistantSid, Uri statusCallback = null, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateModelBuildOptions(pathAssistantSid){StatusCallback = statusCallback, UniqueName = uniqueName}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the new resource </param> /// <param name="statusCallback"> The URL we should call using a POST method to send status information to your /// application </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> CreateAsync(string pathAssistantSid, Uri statusCallback = null, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateModelBuildOptions(pathAssistantSid){StatusCallback = statusCallback, UniqueName = uniqueName}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Update(UpdateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> UpdateAsync(UpdateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param> /// <param name="pathSid"> The unique string that identifies the resource to update </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Update(string pathAssistantSid, string pathSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new UpdateModelBuildOptions(pathAssistantSid, pathSid){UniqueName = uniqueName}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resource to update </param> /// <param name="pathSid"> The unique string that identifies the resource to update </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> UpdateAsync(string pathAssistantSid, string pathSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new UpdateModelBuildOptions(pathAssistantSid, pathSid){UniqueName = uniqueName}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static bool Delete(DeleteModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static bool Delete(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteModelBuildOptions(pathAssistantSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the resources to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteModelBuildOptions(pathAssistantSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ModelBuildResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ModelBuildResource object represented by the provided JSON </returns> public static ModelBuildResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ModelBuildResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The SID of the Assistant that is the parent of the resource /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The status of the model build process /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public ModelBuildResource.StatusEnum Status { get; private set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> [JsonProperty("unique_name")] public string UniqueName { get; private set; } /// <summary> /// The absolute URL of the ModelBuild resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The time in seconds it took to build the model /// </summary> [JsonProperty("build_duration")] public int? BuildDuration { get; private set; } /// <summary> /// More information about why the model build failed, if `status` is `failed` /// </summary> [JsonProperty("error_code")] public int? ErrorCode { get; private set; } private ModelBuildResource() { } } }
using System; using Anotar.CommonLogging; #pragma warning disable 1998 public class ClassWithException { public async void AsyncMethod() { try { // ReSharper disable once ReturnValueOfPureMethodIsNotUsed TimeSpan.FromDays(1); } catch { } } public void Debug() { try { LogTo.Debug(); } catch { } } public void DebugString() { try { LogTo.Debug("TheMessage"); } catch { } } public void DebugStringParams() { try { LogTo.Debug("TheMessage {0}", 1); } catch { } } public void DebugStringException() { try { LogTo.DebugException("TheMessage", new Exception()); } catch { } } public void Trace() { try { LogTo.Trace(); } catch { } } public void TraceString() { try { LogTo.Info("TheMessage"); } catch { } } public void TraceStringParams() { try { LogTo.Trace("TheMessage {0}", 1); } catch { } } public void TraceStringException() { try { LogTo.TraceException("TheMessage", new Exception()); } catch { } } public void Info() { try { LogTo.Info(); } catch { } } public void InfoString() { try { LogTo.Info("TheMessage"); } catch { } } public void InfoStringParams() { try { LogTo.Info("TheMessage {0}", 1); } catch { } } public void InfoStringException() { try { LogTo.InfoException("TheMessage", new Exception()); } catch { } } public void Warn() { try { LogTo.Warn(); } catch { } } public void WarnString() { try { LogTo.Warn("TheMessage"); } catch { } } public void WarnStringParams() { try { LogTo.Warn("TheMessage {0}", 1); } catch { } } public void WarnStringException() { try { LogTo.WarnException("TheMessage", new Exception()); } catch { } } public void Error() { try { LogTo.Error(); } catch { } } public void ErrorString() { try { LogTo.Error("TheMessage"); } catch { } } public void ErrorStringParams() { try { LogTo.Error("TheMessage {0}", 1); } catch { } } public void ErrorStringException() { try { LogTo.ErrorException("TheMessage", new Exception()); } catch { } } public void Fatal() { try { LogTo.Fatal(); } catch { } } public void FatalString() { try { LogTo.Fatal("TheMessage"); } catch { } } public void FatalStringParams() { try { LogTo.Fatal("TheMessage {0}", 1); } catch { } } public void FatalStringException() { try { LogTo.FatalException("TheMessage", new Exception()); } catch { } } }